Home > other >  Query Firestore collection with OR operator with Flutter
Query Firestore collection with OR operator with Flutter

Time:11-29

I am trying to filter my data with conditions of 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);

How can I implement this query in Flutter/Dart?

CodePudding user response:

You have to merge your two APIs into one. There are a couple of ways to use it.

  1. Create two methods for your queries.
      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. You can call inside initState or using StreamBuilder widget. I used 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. Dispose your stream
  @override
  void dispose() {
    super.dispose();
    roomSubscription?.cancel();
  }

I didn't test my answer. If you get any issues please comment down below.

  • Related