Petr Jelínek
Petr Jelínek

Reputation: 1441

Firestore where query cannot change condition in runtime

I am working on my Flutter app and I am using Firebase as backend. I am also using firestore as my database.

I have this problem that I want to filter out some item, based on user´s selection. I defined variable filteredCategory in my DataService and create setter here aswell.

void setFilteredCategory(String category) {
    filteredCategory = category;
}

Then I called this setter from filter widget

DataService().setFilteredCategory(category);

But nothing changed in the where() method. It just ignored the change.

Stream<dynamic> get getItems {
    return items
        .document(uid)
        .collection("items")
        .where("category", isEqualTo: filteredCategory)
        .snapshots()
        .map(_snapshotToUserData);
  }

I also tried to set this variable after some time using sleep() method and this approach worked, so I dont know, what is wrong here. Do you have any suggestions?

Thanks.

Upvotes: 0

Views: 608

Answers (3)

Augustin Bralley
Augustin Bralley

Reputation: 336

Try creating a new instance of items each time like:

Stream<dynamic> get getItems {
return Firestore.instance.collection("foo").document(uid).collection("items")
    .where("category", isEqualTo: filteredCategory)
    .snapshots()
    .map(_snapshotToUserData);

Upvotes: 0

J. S.
J. S.

Reputation: 9635

It's likely that your Stream query isn't changing because it's just being rendered as part of the Widget. Unless you use setState to make sure the query is rebuilt using the new value, it won't change. Try this:

void setFilteredCategory(String category) {
  setState((){
    filteredCategory = category;
  });
}

If that is not having the result you expect, you can completely move your query from the Widget part and pass it to the state itself.

Upvotes: 1

imtoori
imtoori

Reputation: 600

In order to update the stream that the StreamBuilder is using you should put DataService().setFilteredCategory(category); inside a setState call

setState((){
  DataService().setFilteredCategory(category);
});

Upvotes: 0

Related Questions