【问题标题】:Query Firestore collection with OR operator with Flutter使用 Flutter 使用 OR 运算符查询 Firestore 集合
【发布时间】:2023-04-08 10:38:02
【问题描述】:

我正在尝试使用you are participant or the room is public 的条件过滤我的数据

// get list of rooms contains your Uid
var participantSnapshot = _roomCollection.where('participants', arrayContains: 'userUid');
// get list of public room
var publicRoomSnapshot = _roomCollection.where('private', isEqualTo: false);

如何在 Flutter/Dart 中实现这个查询?

【问题讨论】:

  • 这是流调用还是未来调用?
  • 这是一个流调用

标签: flutter dart google-cloud-firestore


【解决方案1】:

您必须将两个 API 合并为一个。有几种使用方法。

  1. 为您的查询创建两种方法。
      Stream<List<RoomModel>> stream1(String userUid) {
        var ref = FirebaseFirestore.instance
            .collection('rooms')
            .where('participants', arrayContains: userUid);
    
        return ref
            .snapshots()
            .map((list) => list.docs.map((doc) => RoomModel.fromForestore(doc)).toList());
      }
    
      Stream<List<RoomModel>> stream2() {
        var ref = FirebaseFirestore.instance
            .collection('rooms')
            .where('private', isEqualTo: false);
    
        return ref
            .snapshots()
            .map((list) => list.docs.map((doc) => RoomModel.fromForestore(doc)).toList());
      }
  1. 您可以在initState 内部调用或使用StreamBuilder 小部件。我用initState

List<RoomModel> allRooms = [];
StreamSubscription roomSubscription;

  @override
  void initState() {
    super.initState();
    var s4 = StreamGroup.merge([stream1(uid), stream2()]).asBroadcastStream();
    roomSubscription = s4.listen((event) {
      event.forEach((element) {
         if (element is RoomModel) {
            allRooms.removeWhere((e) => e.docId == element.docId);
            allRooms.add(element);
          }
      });
    });
  }
  1. 处理您的信息流
  @override
  void dispose() {
    super.dispose();
    roomSubscription?.cancel();
  }

我没有测试我的答案。如果您有任何问题,请在下方评论。

【讨论】:

  • 我尝试使用你建议的这段代码,并使用StreamBuilder,它似乎只能检索公共房间
  • 这应该可以。你的返回类型是否相等?
  • 嗯,这很有趣,我只是将流的顺序从[participantStream, publicRoomStream] 更改为[publicRoomStream, participantStream] 现在返回预期结果,非常感谢您在这里指导我
猜你喜欢
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2012-12-07
  • 2017-07-08
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多