ronline
ronline

Reputation: 2411

Multiple Where Cases in a Flutter Stream Builder built from Firestore Collection

I can't find documentation or example how to use multiple where clauses in Flutter Stream Builder returned by Firestore Collection.

The bellow query works

      Firestore
          .instance
          .collection (collectionName)
          .where      ("index",   arrayContains:  search)
          .orderBy    ('date',    descending:     true  )
          .snapshots()

but return zero if I add an additional where clause

      Firestore
          .instance
          .collection (collectionName)
          .where      ("index",   arrayContains:  search)
          .where      ('allowed_roles', arrayContains: GlobalVars.userRole.toString() )
          .orderBy    ('date',    descending:     true  )
          .snapshots() 

The compound query examples in Firebase documentation look pretty much as above but there is missing Flutter or Dart examples.

EDITED : I have also tried the query build pattern as workaround but it doesn't work neither. Flutter really doesn't want the arrayContains clause more than once.

  CollectionReference collectionRef = Firestore.instance.collection (collectionName);
  Query p =  collectionRef.where      ('allowed_roles', arrayContains: "3");
  Query q =  p.where      ('index', arrayContains: "Dan");

  Stream s = q.snapshots(); 

What I am missing here is what solution should programmer use for this problem a logical AND is a pretty basic equation and it is unusual to stuck on this feature.

Upvotes: 0

Views: 1530

Answers (2)

ronline
ronline

Reputation: 2411

As brought up in the comments Firebase doesn't take more than one arrayContains clause .

The only solution for my case is to hooking a conditional statement for allow_roles array in my activities :

if( document['allowed_roles'].contains( GlobalVars.userRole ))

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317692

You can't have two arrayContains filters in a query:

      .where      ("index",   arrayContains:  search)
      .where      ('allowed_roles', arrayContains: GlobalVars.userRole.toString() )

According to the documentation, only one arrayContains is supported at a time. This is a limitation of Firestore and can't be changed. The query is certainly generating an error - you should add code to check for errors instead of blindly assuming that it succeeds.

Upvotes: 3

Related Questions