首页 > 解决方案 > 是否可以在 Dart 中等待 for 循环?

问题描述

我是 Dart 的新手,因此在异步编程方面遇到了麻烦。我正在尝试遍历元素列表(我们现在称它们为成分)并在数据库中查询包含该成分的食谱。为了实现这一点,我有一个列表“ingredientsSelectedList”并将其传递给未来,该未来应该查询 Firestore 数据库并将结果添加到“possibleRecipes”列表中。问题是,在返回“possibleRecipes”列表之前,我无法弄清楚如何“等待”for 循环完成。每次我运行它时,它都会返回一个空列表。希望我没有把它弄得太复杂,并提前感谢所有花时间阅读本文的人:)

PS:我花了几个小时在网上找到解决方案,但找不到任何东西。

Future searchRecipe(ingredients) async {
    var possibleRecipes = []; //List to store results
    for (int i = 0; i < ingredients.length; ++i) {
      var currentIngredient = ingredients[i];
      //now query database for recipes with current ingredient
      var fittingRecipes = Firestore.instance
          .collection('recipes-01')
          .where('ingr.$currentIngredient', isEqualTo: true);
      fittingRecipes.snapshots().listen((data) => data.documents.forEach((doc) {
            possibleRecipes.add(doc['name']); //add names of results to the list
          }));
    }
    return possibleRecipes; //this returns an empty list
}

标签: for-loopasynchronousflutterdartfuture

解决方案


是的你可以

只需使用此代码

Future searchRecipe( List ingredients) async {
var possibleRecipes = []; //List to store results


 ingredients.forEach((currentIngredient) async{
//you can await anything here. e.g  await Navigator.push(context, something);
      //now query database for recipes with current ingredient
      var fittingRecipes = await Firestore.instance
          .collection('recipes-01')
          .where('ingr.$currentIngredient', isEqualTo: true);
      fittingRecipes.snapshots().listen((data) => data.documents.forEach((doc) {
            possibleRecipes.add(doc['name']); //add names of results to the list
          }));
    });
    return possibleRecipes; //this returns an empty list
}

推荐阅读