Is it possible to await a for-loop in Dart?

十年热恋 提交于 2021-02-08 10:38:44

问题


I'm new to Dart and therefore having trouble with asynchronous programming. I'm trying to loop through a list of elements (let's call them ingredients for now) and query the database for recipes which contain the ingredient. To achieve this, I have a list 'ingredientsSelectedList' and pass it over to a future which is supposed to query the Firestore Database and add the result to the 'possibleRecipes' List. The problem is, that I can't figure out how to 'await' the for loop to finish, before returning the 'possibleRecipes' List. Everytime I run it, it returns an empty list. Hope I didn't make it too complicated and Thanks in advance for everyone that's taking the time to read this :)

PS: I have spent hours to find a solution to this online, but couldn't find anything.

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
}

回答1:


Yes you can

Simply use this code

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
}


来源:https://stackoverflow.com/questions/58560570/is-it-possible-to-await-a-for-loop-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!