How to add an OR condition to flutter Firebase queries

Viewed 2133

I am trying to add an OR condition to my flutter firebase query.

Here is my code but I want to check where receiver_name is equal to kim OR sender_name is equal to kim

StreamBuilder( 
  stream: Firestore.instance.collection("payments").where("receiver_name", isEqualTo: userActive).snapshots(),
  builder: (context, snapshot){
 

  return Container ( child:ListView.builder(
      shrinkWrap: true,
    itemCount: snapshot.data.documents.length,
    padding: EdgeInsets.all(0),
    controller: ScrollController(keepScrollOffset: false),
    itemBuilder: (context, index){

      DocumentSnapshot documentSnapshot = snapshot.data.documents[index];
                                        
1 Answers

As @ChristopherMoore commented, OR conditions on multiple fields are not possible with Firestore. Executing a separate query and merging them client-side is the most common workaround. For more on this see:

The reason for not marking your question as a duplicate of those, is to point out another way to accomplish the same result with a single query.


Add an array of participants to each document

If you add an array field participants to your documents, with in it the UID fields of the sender and the receiver, you can then use an array-contains query to get all payments in which the user was either the sender or the receiver.

To add a UID to such an array, be sure to use the array-union operator:

documentRef.updateData({"participants": FieldValue.arrayUnion("uidOfUser")});

And then to query it, you'd use:

collectionRef.where('participants', arrayContains: "uidOfUser")
Related