firebase - How can i use two dependent async tasks in a Stream-Builder?
问题描述
i want to use a StreamBuilder
with two async tasks. The first async stream gets the open friend requests from Firebase/Firestore. For every friend_request
item, I need a second async task, which gets the profile information for the friend_request
item.
The problem is, that I can't get use the second async task in StreamBuilder
, because the builder can't be asnc. My current code returns the list too early, because it can't await.
I would be very happy to receive help.
StreamBuilder<QuerySnapshot>(
stream: firestoreHandler.streamRequestedFriends(),
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.data.docs.isEmpty)
return Text('No friend requests');
List<FriendRequestItem> friendList = List<FriendRequestItem>();
var friendRequests = snapshot.data.docs;
for (var friendRequest in friendRequests) {
String friendId = friendRequest.data()['friendId'];
// firestoreHandler.getUserById() needs to await
firestoreHandler
.getUserById(friendId)
.then((friendProfile) {
friendList.add(
FriendRequestItem(
photoUrl: friendProfile.data()['profile_picture'],
email: friendProfile.data()['email'],
onAccept: () {
firestoreHandler.acceptFriendRequest(friendId);
},
onDelete: () {
firestoreHandler.removeFriendRequest(friendId);
},
),
);
});
}
return Column(
children: friendList,
);
},
),
解决方案
For this, you've to use FutureBuilder inside the StreamBuilder.
StreamBuilder<QuerySnapshot>(
stream: firestoreHandler.streamRequestedFriends(),
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.data.docs.isEmpty)
return Text('No friend requests');
List<FriendRequestItem> friendList = List<FriendRequestItem>();
var friendRequests = snapshot.data.docs;
for (var friendRequest in friendRequests) {
String friendId = friendRequest.data()['friendId'];
return FutureBuilder(
future: firestoreHandler.getUserById(friendId),
builder: (context, snapshotFuture) {
if (snapshot.connetionState == ConnectionState.done) {
friendList.add(
FriendRequestItem(
photoUrl: snapshotFuture.data.data()['profile_picture'],
email: snapshotFuture.data.data()['email'],
onAccept: () {
firestoreHandler.acceptFriendRequest(friendId);
},
onDelete: () {
firestoreHandler.removeFriendRequest(friendId);
},
),
);
return Column(
children: friendList,
);
}
return CircularProgressIndicator();
},
);
}
},
);
推荐阅读
- laravel - Laravel 会话超时
- google-apps-script - 如何使用 YouTube 数据 API 和 YouTube 分析报告为品牌帐户中的每个视频获取 YouTube 分析报告
- sql-server - 寻求帮助退出循环
- angular - 在实际项目中使用 Angular 2+ 和 .Net CORE 实现登录功能的好概念是什么?
- css - 如何通过css将一侧划分为2d?
- excel - 如何通过 excel 宏打开带有通配符选项的 .PDF 文件
- php - file_get_contents 显示特定域的错误
- javascript - GraphQL 类型关系 / Mongoose Schema / populate()
- java - JBPM:执行过程的 POST 请求出错
- python - 比较不同大小的股票指数 Python