我正在尝试从用户所属的组中获取来自 firebase 的所有帖子。我现在的问题是程序不会等到列表 groupsPosts 有数据并继续执行代码。
getTimelineWithGroupPosts() async {
List groupIDs = [];
List<QuerySnapshot> groupsPosts = [];
List allPosts = [];
QuerySnapshot snapshot = await usersGroupsRef
.document(currentUser.id)
.collection("usersGroups")
.getDocuments();
snapshot.documents.forEach((element) {
groupIDs.add(element.documentID.toString());
});
print(groupIDs);
groupIDs.forEach((data) async {
groupsPosts.add(await groupPostsRef
.document(data)
.collection("groupPosts")
.getDocuments());
print(groupsPosts);
});
print(groupsPosts);
groupsPosts.forEach((data) {
allPosts.add(data.documents);
});
print(allPosts);
List<Post> posts = allPosts.map((doc) => Post.fromDocument(doc)).toList();
setState(() {
groupPosts = posts;
});
}
I/flutter (11768): [1de5aec6-612e-41e8-90b2-04781b2a2954, 3545784b-0fca-4d35-bd0d-5d877e58808f, 66036190-304f-4984-9e7a-1a9a92e83466]
I/flutter (11768): []
I/flutter (11768): []
I/flutter (11768): [Instance of 'QuerySnapshot']
I/flutter (11768): [Instance of 'QuerySnapshot', Instance of 'QuerySnapshot']
I/flutter (11768): [Instance of 'QuerySnapshot', Instance of 'QuerySnapshot', Instance of 'QuerySnapshot']
答案 0 :(得分:0)
forEach
不等待返回的期货。而是使用 Future.wait
:
groupPosts.addAll(
await Future.wait(
groupIDs.map(
(data) => groupPostsRef
.document(data)
.collection("groupPosts")
.getDocuments(),
),
),
);