我有一个包含当前观看电影的每个用户的 ID 的观众子集合 viewers 的电影集合。
我需要你的帮助来绑定来自 Firestore 的用户流。做到这一点:
希望有人能帮助我! :)
Stream<List<UserModel>> viewerStream(String movieId) {
List<String> viewersId = [];
List<UserModel> viewers = [];
_firestore
.collection(MOVIECOLLECTION)
.doc(movieId)
.collection(VIEWERS)
.get().then((value) {
value.docs.forEach((element) {
viewersId.add(element.id);
}); //works fine, I get my userIds
if (viewersId == null || viewersId.length == 0) return null;
return _firestore
.collection(USERSCOLLECTION)
.where(FieldPath.documentId, whereIn: viewersId)
.snapshots()//since here, nothing works
.map((query) {
query.docs.forEach((element) {
viewers.add(UserModel.fromDocumentSnapshot(documentSnapshot: element));
});
});
return viewers;
});
}```
答案 0 :(得分:0)
试试这个
_firestore
.collection(USERSCOLLECTION)
.where(FieldPath.documentId, whereIn: viewersId)
.snapshots()
.listen((event) => onViewersChange(event.docChanges));
对于文档的每次更改
onViewersChange(List<DocumentChange<Map<String, dynamic>>> docChanges) {
docChanges.forEach((docChange) {
if (docChange.type == DocumentChangeType.added) {
docChange.doc.data(); // Add to your Viewers List
} else if (docChange.type == DocumentChangeType.modified) {
docChange.doc.data(); // Replace this data to the existing data in Viewers List
} else if (docChange.type == DocumentChangeType.removed) {
docChange.doc.data(); //Remove this data from your viewerList
}
});
}
答案 1 :(得分:0)
我试过你给我看的东西,但现在我的听众总是返回空:
The method 'listen' was called on null.
Receiver: null
Tried calling: listen(Closure: (List<UserModel>) => List<UserModel>)
这是我的代码:
Stream<List<UserModel>> viewersStream(String movieId) {
List<String> viewersId = [];
List<UserModel> viewers = [];
onViewersChange(List<DocumentChange> docChanges, List<UserModel> viewersList) {
docChanges.forEach((docChange) {
if (docChange.doc != null && docChange.doc.exists) {
if (docChange.type == DocumentChangeType.added) {
viewersList.add(UserModel.fromDocumentSnapshot(
documentSnapshot: docChange.doc));
docChange.doc.data(); // Add to your Viewers List
} else if (docChange.type == DocumentChangeType.modified) {
docChange.doc
.data(); // Replace this data to the existing data in Viewers List
viewersList.forEach((element) {
if (element.id == docChange.doc.id) {
element = UserModel.fromDocumentSnapshot(
documentSnapshot: docChange.doc);
}
});
} else if (docChange.type == DocumentChangeType.removed) {
docChange.doc.data();
viewersList.removeWhere((element) => (element.id ==
docChange.doc.id)); //Remove this data from your viewerList
}
}
});
}
_firestore
.collection(MOVIECOLLECTION)
.doc(viewerId)
.collection(VIEWERS)
.get()
.then((value) {
value.docs.forEach((element) {
viewersId.add(element.id);
});
_firestore
.collection(USERSCOLLECTION)
.where(FieldPath.documentId, whereIn: viewersId)
.snapshots()
.listen((event) {
onViewersChange(event.docChanges, viewers);
return viewers;
});
});
}