gpt4 book ai didi

firebase - 嵌套的forEach从Firebase检索子集合

转载 作者:行者123 更新时间:2023-12-03 03:22:24 24 4
gpt4 key购买 nike

我正在尝试使用嵌套的foreach来检索要添加到列表的多个子集合:

List<Widget> TaskList() {
List<Widget> lines = [];
firestoreInstance.collection("tasks").where("type", isEqualTo: "urgent").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
firestoreInstance.collection("tasks").document(result.documentID).collection("todo").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
lines.add(Row(
children: <Widget> [
Expanded(flex: 7, child: Text("test", style: TextStyle(fontSize: 20))), Expanded(flex: 1, child: Text("test", style: TextStyle(fontSize: 20))), Expanded(flex: 2, child: Text("test", style: TextStyle(fontSize: 20), textAlign: TextAlign.right)), ], ));
});
});
});
});
return lines;
}

上面的代码可以运行,但列表为空。我想象它与等待查询完成有关系,因为如果我用简单的for循环替换了forEach而没有访问Firebase,它就会起作用(行添加到列表中)。我知道我必须以某种方式使用Future。但是我不能真正为这种嵌套的foreach方案计算语法。

感谢您提供的任何帮助或指向有用示例的指针。

最佳答案

您可以使用asyncawait:

  Future<List<Widget>> TaskList() async {
List<Widget> lines = [];
QuerySnapshot result = await firestoreInstance
.collection("tasks")
.where("type", isEqualTo: "urgent")
.getDocuments();
for (var res in result.documents) {
QuerySnapshot todoResult = await firestoreInstance
.collection("tasks")
.document(res.documentID)
.collection("todo")
.getDocuments();
for (var todoRes in todoResult.documents) {
lines.add(Row(
children: <Widget>[
Expanded(
flex: 7, child: Text("test", style: TextStyle(fontSize: 20))),
Expanded(
flex: 1, child: Text("test", style: TextStyle(fontSize: 20))),
Expanded(
flex: 2,
child: Text("test",
style: TextStyle(fontSize: 20),
textAlign: TextAlign.right)),
],
));
}
}
return lines;
}
}

这样,除非两个查询都完成,否则列表不会被填充。如果要在 future方法中使用此 build方法,请执行以下操作:
  Future<QuerySnapshot> TaskList() async {
QuerySnapshot todoResult;
QuerySnapshot result = await firestoreInstance
.collection("tasks")
.where("type", isEqualTo: "urgent")
.getDocuments();
for (var res in result.documents) {
todoResult = await firestoreInstance
.collection("tasks")
.document(res.documentID)
.collection("todo")
.getDocuments();
}
return todoResult;
}

并在 FutureBuilder中使用上述功能

关于firebase - 嵌套的forEach从Firebase检索子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61757176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com