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.
- 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());
}
- You can call inside
initState
or usingStreamBuilder
widget. I usedinitState
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);
}
});
});
}
- 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.