Flutter Future的构建者,future被多次调用

时间:2020-08-19 12:19:53

标签: android flutter google-cloud-firestore

问题:我在 SingleChildScrollView 内的中有一个将来的构建器。 它多次调用其未来(无限)。


 FutureBuilder(
                    future: ProductLoaderUtil.getSimilarProducts(
                        context, widget.productItem.productCategoryId),
                    builder: (context, val) {
                      if (val.hasData && (!val.hasError))
                        return ListProductHorizontal(
                          productItemsHorizontal: val.data,
                          flag: false,
                        );
                      else
                        return Container(
                          height: _height * 0.06,
                          color: FakeWhite,
                        );
                    },
                  ),

被调用的函数是这个

         static Future<List<ProductItem>> getSimilarProducts(
                BuildContext context, String category) async {
                List<ProductItem> products = [];
                String categoryName = categories[0];
  
                debugPrint(categoryName + " --- ");
                await Firestore.instance
                    .collection("GlobalDataBase")
                    .document(categoryName)
                    .collection("ITEMS")
                    .limit(4)
                    .getDocuments()
                    .then((value) {
                  value.documents.forEach((element) {
            //        debugPrint(element.data.toString());
                    products.add(ProductItem.fromJson(element.data));
                  });
                });
                return products;
              }

1 个答案:

答案 0 :(得分:1)

这可能是因为您在某个地方使用了setState(),并且当您重新构建窗口小部件树并且FutureBuilder再次调用future方法时,才可以防止这种访问未来initState()中的方法,通过像这样有状态的小部件

// inside state class...
  
   Future getPopluarProductsFuture;

   @override
  void initState() {
    super.initState();
    getPopularProductsFuture = getPopularProducts(
                        context, widget.productItem.productCategoryId);
  }

 // now for the FutureBuilder make it like this 
  FutureBuilder(
   future: getPopularProductsFuture,
   builder: ......
)