Why is my Firestore Stream producing duplicate results on my forEach on the snaphot?

时光毁灭记忆、已成空白 提交于 2020-12-16 02:24:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!