[英]Flutter Future builder, future gets called multiple times
Problem: I have a future builder inside a Column which is inside a SingleChildScrollView问题:我在SingleChildScrollView内的Column中有一个未来的构建器
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,被调用的 function 是这样的,
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这可能是因为你在某个地方使用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: ......
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.