简体   繁体   中英

Flutter Future builder, future gets called multiple times

Problem: I have a future builder inside a Column which is inside a SingleChildScrollView
It calls its future multiple times(Infinite).


 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,
                        );
                    },
                  ),

The function getting called is this,

         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;
              }

that's probably because somewhere you use setState() and when you that your widget tree get re-build and the FutureBuilder call the future method again, to prevent this gain access to the future method in initState() by having a stateful widget like this

// 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: ......
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM