dart 为什么setState不改变我的变量Flutter?

s4n0splo  于 2022-12-20  发布在  Flutter
关注(0)|答案(1)|浏览(173)

我有一个变量,我在gridView.Builder中为它赋值,并且有一个按钮,当单击该按钮时,我的变量会发生变化,我使用setState进行此操作,但它没有变化,原因可能是什么?

class _CatalogItemsState extends State<CatalogItems> {
  Set<int> _isFavLoading = {};
  bool isFavorite = false;
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(name!),
      ),
      body: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: Column(
          children: [
            Expanded(
              child: FutureBuilder<List<Product>>(
                  future: productFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return buildGridShimmer();
                    } else if (snapshot.hasData) {
                      final catalog = snapshot.data;
                      if (catalog!.isEmpty) {
                        return const Center(
                          child: Text(
                            'Нет товаров',
                            style: TextStyle(
                                fontSize: 25, fontWeight: FontWeight.bold),
                          ),
                        );
                      }
                      return buildCatalog(catalog);
                    } else {
                      print(snapshot.error);
                      return const Text("No widget to build");
                    }
                  }),
            ),
          ],
        ),
      ),
    );
  }

SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(),
            delegate: SliverChildBuilderDelegate(childCount: product.length,
                (BuildContext context, int index) {
              final media =
                  product[index].media?.map((e) => e.toJson()).toList();
              final photo = media?[0]['links']['local']['thumbnails']['350'];
              final productItem = product[index];
              isFavorite = productItem.is_favorite; // this is the new value of the variable, work good
 
IconButton(
                                    icon: Icon(_isFavLoading.contains(index) || isFavorite ? Icons.favorite : Icons.favorite_border, color: Colors.red,),
                                    onPressed: () {
                                       setState(() {
                                          isFavorite = !isFavorite;
                                        });
                                        print('t: ${isFavorite}'); // the value of the variable does not change
                                    },
                              )
qgelzfjb

qgelzfjb1#

这是因为你并没有真正更新你的product对象。你必须在按下图标时改变它的值

onPressed: () {
    setState(() {
       productItem.is_favorite = !isFavorite;
    });
    print('t: ${productItem.is_favorite}'); // the value of the variable does not change
  }

相关问题