Basudev Nayak
Basudev Nayak

Reputation: 1024

How to use WhereIn in flutter with firestore?

In an ecommerce flutter app project I am using the shortInfo field of my items collection as an unique id for each product. When add to cart is pressed it saves the shortInfo to an array field called userCartList at my users collection and I am using WhereIn to query this array but when I have more than 10 product my app crashes. What am I doing wrong here?

Here is my firestore structure:

Users Collection

Items Collection

Here is a snippet of the query I am making:

StreamBuilder<QuerySnapshot>( 
    stream: EcommerceApp.firestore
                        .collection("items")
                        .where("shortInfo", whereIn: EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList))
                        .snapshots()
)

Upvotes: 6

Views: 9600

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5819

The problem here is that Firestore does not allow you to make an array membership query with more that 10 records. If you check this documentation you will see that:

Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR

Behind the scenes your whereIn operator is making the same query showed in the example in the documentation and if you use more than 10 records, Firestore will not accept it and you will get an error. I suggest that you break the EcommerceApp.userCartList array into multiple arrays with a max of 10 records to make the query, this will allow Firestore to operate the whereIn within it's limits and it will work.

Let me know if you have any more questions on this matter.

Upvotes: 7

Related Questions