Reputation: 301
I have query like this;
final _firestore = FirebaseFirestore.instance;
var sRef = _firestore
.collection("vehicles")
.where("models.car", isEqualTo: "true")
.where("models.plane", isEqualTo: "true")
.where("models.motor", isEqualTo: "true");
With this query I can query which list include car,plane and motor at the same time. But I want to do query dynamiclly. Therefore I did this for loop;
List<String> item = ["car", "motor", "plane"];
var sRef;
for (int i = 0; i < item.length; i++) {
sRef = _firestore
.collection("vehicles").where("models.$item[i]", isEqualTo: "true");
}
But it didn't work as I expected.
When I want to use the for loop to display the lists containing the elements in the item list, the code additionally shows me the lists containing the last element in the item list.
For example, in this example, it shows me the lists that include car, motor and plane, and it also shows lists that contain only plane, but I don't want to display only the lists that contain plane, I just want to display the lists that contain car, motor, plane.
And these are my Firebase Documents.
When I run the code with for loop that I wrote above, I get an output like this, but I just want to get the list named ALL.
Why I get list named PLANE with list named ALL. I just want get to list named ALL. And How can I do that query dynamically.
Somehow I need to make the query I show at the top dynamic, but as I mentioned above, the for loop I used did not work for this job.
Upvotes: 0
Views: 297
Reputation: 7716
The problem with the code is that only the last .where()
query is registered as you're reassigning the sRef
variable on each loop.
The solution will be to assign a value to the sRef
variable only when the variable is null (that is, it has not been assigned a value yet) and in subsequent loops, just add the .where()
query to the variable with an assigned value.
Change this:
for (int i = 0; i < item.length; i++) {
sRef = _firestore.collection("vehicles").where("models.$item[i]", isEqualTo: "true");
}
to this:
for (int i = 0; i < item.length; i++) {
if (sRef == null) {
sRef = _firestore.collection("vehicles").where("models.$item[i]", isEqualTo: "true");
} else {
sRef = sRef.where("models.${item[i]}", isEqualTo: "true");
}
}
Upvotes: 2