【发布时间】:2019-09-01 08:27:01
【问题描述】:
Notifylisteners 不断循环运行
Future<void> fetchAndSetMeal() async {
final List<Meal> loadedProducts = [];
var data = await DataBaseHelpers.getData();
if (data.documents == null) {
return;
}
List<DocumentSnapshot> list = data.documents;
list.forEach((document) async {
var url = await DataBaseHelpers.getImageUrl(document.documentID);
loadedProducts.insert(
0,
Meal(
id: document.documentID,
category: document.data['category'],
description: document.data['description'],
title: document.data['title'],
price: document.data['price'],
imgUrl: url));
});
await Future.delayed(Duration(milliseconds: 300));
print(loadedProducts[0]);
notifyListeners();
_items = loadedProducts;
} }
//打印和网络调用语句也运行两次,而不是//每次调用只运行一次。 notifyListeners() 正在循环运行;
【问题讨论】:
-
我相信问题出在你的 async forEach 声明上。试试这个:
await Future.forEach(list, (document) async {///your block of code here});. -
你是怎么调用 fetchAndSetMeal 的?在 initState 内部还是在 build 方法内部?
-
手动执行此操作让我感到沮丧,因此我改用了 Streams。现在就像一个魅力。谢谢
标签: android flutter dart visual-studio-code