我在网上找到了一些类似的解决方案,但我的代码无法使用它。
我相信问题出在 async/await 和 forEach 循环上,但我无法修复它。基本上,下面的代码不会将用户添加到 usersList,而是会相应地打印每个 if 块的调试行。
Stream<List<AppUser>> showSuggestionStream() {
List<AppUser> usersList = [];
return _firestore.collection('users').snapshots().map((snap) {
snap.docs.forEach((u) async {
final user = u.data();
final friendsCollection =
await u.reference.collection('friends').doc(uid).get();
if (friendsCollection.exists) {
if (friendsCollection.data()['status'] == 'accepted') {
print(
'FriendsCollection exist and we are friends, no need to add to usersList');
} else {
print('FriendsCollection exist and we are not friends');
usersList.add(AppUser(
uid: u.id,
displayName: user['name'],
email: user['email'],
photoUrl: user['photoUrl'],
phoneNumber: user['phoneNumber'],
providerData: user['providerData'],
));
}
} else {
print('No friends collection');
usersList.add(AppUser(
uid: u.id,
displayName: user['name'],
email: user['email'],
photoUrl: user['photoUrl'],
phoneNumber: user['phoneNumber'],
providerData: user['providerData'],
));
}
});
return usersList.toList();
});
}
编辑:
我想了想,决定换一种方式尝试。我正在远离 async/await,希望这是正确的方法。
但是仍然无法让好友的子集起作用。我不确定如何将 Future<List<Friend>>
转换为 List<Friend>
。
Stream<List<AppUser>> searchUsersStream() {
return _firestore
.collection('users')
.snapshots()
.map((snap) => snap.docs
.map((doc) => AppUser(
uid: doc.id,
displayName: doc.data()['name'],
email: doc.data()['email'],
phoneNumber: doc.data()['phoneNumber'],
photoUrl: doc.data()['photoUrl'],
providerData: doc.data()['providerData'],
// friends: doc.reference
// .collection('friends')
// .doc(uid)
// .snapshots()
// .map((doc) => Friend(userId: doc.id, name: doc.name))
// .toList()
))
.toList());
}
答案 0 :(得分:-1)
List<AppUser> usersList = new List();