问题
I'm trying to act on a specific document change type on my Firestore Stream. I noticed that when a doc gets added or removed, I get multiple copies when I iterate over the snapshot. I'm listening to the stream in my Stateful Widget tree but I'm not calling setState anywhere. Here is relevant code:
@override Widget build(BuildContext context) {
var usersOnStreamQuery = placeCollection.doc(place).collection('usersOn');
...
body: Builder(builder: (BuildContext context) {
usersOnStreamQuery
.snapshots(includeMetadataChanges: true)
.listen((data) {
data.docChanges.forEach((change) {
String type;
print(
'document type ${change.type} on doc ${change.doc.data()}');
switch (change.type) {
case DocumentChangeType.added:
type = 'joined';
break;
case DocumentChangeType.removed:
type = 'left';
break;
default:
}
The number of times each gets reported changes, but I noticed I get the same number of each per session. For example this is for all the same document:
flutter: document type DocumentChangeType.added on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.added on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.added on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.added on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.added on doc {x: 60, y: 7}
and then the same quantity of below when the doc is removed. In both cases, I expect only one and can verify in my firestore collection there is only one doc in it.
flutter: document type DocumentChangeType.removed on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.removed on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.removed on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.removed on doc {x: 60, y: 7}
flutter: document type DocumentChangeType.removed on doc {x: 60, y: 7}
来源:https://stackoverflow.com/questions/65173092/why-is-my-firestore-stream-producing-duplicate-results-on-my-foreach-on-the-snap