是否可以在Dart中等待for-loop? [英] Is it possible to await a for-loop in Dart?

查看:49
本文介绍了是否可以在Dart中等待for-loop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Dart的新手,因此在异步编程方面遇到了麻烦.我试图遍历元素列表(现在将其称为配料),并在数据库中查询包含配料的配方.为此,我有一个列表"ingredientsSelectedList"并将其传递给将来应查询Firestore数据库并将结果添加到"possibleRecipes"列表中的将来.问题是,在返回"possibleRecipes"列表之前,我无法弄清楚如何等待" for循环完成.每当我运行它时,它都会返回一个空列表.希望我不会太复杂,在此先感谢所有花时间阅读本文的人:)

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:我已经花了数小时在网上找到解决方案,但找不到任何东西.

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
}

推荐答案

是的,您可以

只需使用此代码

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
}

这篇关于是否可以在Dart中等待for-loop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆