Home > database >  Firebase Flutter - Request with multiple where arrayContains
Firebase Flutter - Request with multiple where arrayContains

Time:01-16

In my firebase documents, I have a field named "tags" that is a List, for example tags = ["Amazing", "Great", "Disappointing"].

I want to filter the documents to query, so the user select a list of tags, for example filteredTags = [Amazing", "Great"]. In my request, I want to retrieve all documents that have all elements of filteredTags in there tags list.

This query does not work because it looks for a list within tags, which is just a list of string :

query = query.where(KeyTags, whereIn: filteredTags);

And this query return an error, because flutter does not allow to have multiple arrayContains in the same query (works if I have only 1 tag in filteredTags list) :

for(dynamic tag in filteredTags){
    query = query.where(KeyTags, arrayContains: tag);
  }

Finally, this one work but is not what I look for (it retrieves documents that have one of the filteredTags, whereas I want documents that have all of them :

query = query.where(KeyTags, arrayContainsAny: filteredTags);

Any idea of how to do it ?

Thanks !

CodePudding user response:

What you're describing is an arrayContainsAll type operator, which doesn't exist at the moment.

The only way to implement this now is to store the tags as a map with subfields for each tag and then a value, and then query for those values with equality checks in your query. For example:

tags: {
  "Amazing": true, 
  "Great": true, 
  "Disappointing": true
}

And:

query
  .where("tags.Amazing", isEqualTo: true)
  .where("tags.Great", isEqualTo: true)

Also see:

  • Related