Reputation: 301
var searchRef = _firestore
.collection("vehicles")
.where("models.plane", isEqualTo: "true")
.where("models.bus", isEqualTo: "true");
In this query method I can query multiple value but I want to do this dynamically. If the user enters the plane, I want to query the plane or if the user enters the plane and the bus, I want to query the plane and the bus, or if the user enters the plane, bus and sports car, I want to query the plane, bus and sports car. That is, the number of variables to be queried and the variables will vary from user to user.
How can I convert this code to dynamic code.
Upvotes: 0
Views: 6121
Reputation: 512
It seems you want to return the documents which contains all the array items.
so for that I would suggest.
List<String> item = ["motor", "car", "plane"];
var sRef = sRef = _firestore
.collection("vehicles1");
for (int i = 0; i < item.length; i++) {
sref = sref.where("models", arrayContains: item[i]);
}
// finally
print(sref.snapshotChanges()) //something like this
basically what above code will do is it will generate a complex query something like
_firestore.collection("vehicles").where("models", arrayContains: item[0]).where("models", arrayContains: item[1]).where("models", arrayContains: item[2]) //... and so on till for loop ends
Upvotes: 0
Reputation: 50900
That's not possible at the moment. You would have to fetch documents containing either of those values and then manually filter them in your Flutter app.
You just need to pass that array as the value of arrayContains
.
var sRef = _firestore
.collection("vehicles1")
.where("models", arrayContains: item);
This query will return all the documents in vehicles
collection where the array models
contain either of the items in the array you pass. Then you can filter through that array and check which documents' models array contains all those items.
You can check this answer: Flutter filter list as per given condition
Upvotes: 2