如何在Flutter项目中合并两个Firestore查询,以及如何从这两个流中删除重复的文档? [英] How to merge two firestore queries in the Flutter project and How do I remove the duplicate documents from these two streams?

查看:60
本文介绍了如何在Flutter项目中合并两个Firestore查询,以及如何从这两个流中删除重复的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在flutter项目中合并两个firestore查询流.我该怎么做呢?我尝试了StreamZip([Stream1,stream2])方法来合并流,它对我有用.但是流中可能包含相同的文档.因此,当我列出它们时,所有文档都被列出,即使有重复也是如此.如何从这两个流中删除重复的文档?

I needed to combine two firestore query stream in my flutter project. How do I do this? I tried StreamZip([Stream1, stream2]) method to combine the streams and it worked for me. but the streams maybe contains the same documents. so when I listed them all of the documents are listed, even there is a duplicate of it. How do I remove the duplicate documents from these two streams?

   Stream<List<QuerySnapshot>> getData() {
    Stream defaultStream1 = _firestore
        .collection("Gyms")
        .where("gymPlaceTags", arrayContainsAny: ["dubai"])
        .orderBy('createdAt', descending: true)
        .snapshots();
    Stream defaultStream2 = _firestore
        .collection("Gyms")
        .where("gymFavTags", arrayContainsAny: ["ajman"])
        .orderBy('createdAt', descending: true)
        .snapshots();
    return StreamZip([defaultStream1, defaultStream2]);
  }

推荐答案

您需要执行几个步骤:

  1. map 该流以返回另一个 List< DocumentSnapshot> 而不是 List< QuerySnapshot>
  2. map 函数中,使用List上的 fold 删除重复项并映射到 List< DocumentSnapshot>
  3. fold 函数中,遍历 QuerySnapshot 中的每个文档,并检查是否存在具有相同ID的文档,然后再添加.

  1. map the stream to return another a List<DocumentSnapshot> instead of List<QuerySnapshot>
  2. In the map function, use fold on the List to remove duplicates and map to List<DocumentSnapshot>
  3. In the fold function, go over every document in the QuerySnapshot and check if the document with the same id is already present before adding.

Stream<List<DocumentSnapshot>> merge(Stream<List<QuerySnapshot>> streamFromStreamZip) {
  return streamFromStreamZip.map((List<QuerySnapshot> list) {
    return list.fold([], (distinctList, snapshot) {
      snapshot.documents.forEach((DocumentSnapshot doc) {
        final newDocument = distinctList.firstWhere(
                (DocumentSnapshot listed) =>
                    listed.documentId == doc.documentId,
                orElse: () => null) == null;
        if (newDocument) {
          distinctList.add(doc);
        }
      });
      return distinctList;
    });
  });
}

注意:我没有运行这段代码,但是应该是这样的.

Note: I didn't run this code, but it should be something like this.

这篇关于如何在Flutter项目中合并两个Firestore查询,以及如何从这两个流中删除重复的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆