for-loop - 是否可以在 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
}
解决方案
是的你可以
只需使用此代码
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
}
推荐阅读
- c - ZFS 快照(或其他文件系统快照)能否恢复文件系统内存组件?
- javascript - 如何在使用 AWS ECS FARGATE 时为 Web 应用程序存储上传的文件
- haskell - Haskell List Comprehension:List 中用作谓词的布尔项
- javascript - 将数组增加到最大项目
- c++ - 使用概念检查成员函数
- php - PHP-GD 已安装,但在 wordpress 安装期间需要
- c# - 无法向空 TcpClient 发送数据(检查是否调用了 Connect)”
- javascript - 如何从网站获取html数据
- python - 如何在 PyCharm 中通过 Tensorflow 访问 GPU?
- vba - Networkdays 循环 - 我想获得 Networkdays 循环。但给出一个错误。我正在使用office 2016。提前感谢您的努力