【问题标题】:notifyListeners() running on a loopnotifyListeners() 在循环中运行
【发布时间】: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


【解决方案1】:

你在foreach 循环中找到了你的notifyListeners。移到外面

【讨论】:

  • 添加一些代码使它看起来像一个答案而不是一个评论。
  • 仍然出现同样的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 2016-07-18
相关资源
最近更新 更多