'How to design Filters in Flutter?
I am new to flutter and I wonder how to develop filters in flutter something like this (screenshot taken from google images), so I just want to know how to do filtering in a flutter, is there anything like plugins or special widgets? If you provide any reference or code or any tutorials will be helpful for me to learn.ThankYou in Advance.
Solution 1:[1]
You need to break it down in few pieces.
First is your UI: these are just standard Flutter Widgets. You want a user to slide it up? Figure out how to show a Widget by sliding up. You want it to be in the alert popup? Figure out how to do alert popup. Filter UI is not different from any other UI - so you can look for and ask generic UI questions.
Second is how you implement the model. It can be something simple like a Provider that holds the list of Items that you fetched; and then each filter adding more where conditions to your list.
Something like:
var items=<Item>[]; // somehow you would fetch the initial list of items
var filtered;
void addColorFilter(Color color) {
filtered=filtered??items;
filtered=filtered.where( (element) => element.color==color);
notifyListeners();
}
void addSizeFilter(String size) {
filtered=filtered??items;
filtered=filtered.where( (element) => element.size==size);
notifyListeners();
}
void removeFilters() => filtered=null;
void getFiltered() => filtered??items;
And then you can use filtered
iterator in your ListView.builder() to show only filtered items.
To answer your follow-up question here:
You have mix of 'AND' & 'OR' conditions. If you just keep adding iterators like the above, you won't be able to show 2 sizes (M and S) - because no items is both M and S. In this case, where there is a multiple choice filter, you will need to add additional list for each filter type that can have multiple choice. And you will have to rebuild your entire filter.
This might be a good starting point - for your price and size example:
var items=<Item>[]; // somehow you would fetch the initial list of items
Iterator? filtered;
double? lowPrice;
void addLowPrice(double price) {
lowPrice=price;
rebuildFilter();
}
double? highPrice;
void addHighPrice(double price) {
highPrice=price;
rebuildFilter();
}
var sizeOptions=<String>[];
void addSizeFilter(String size) {
sizeOptions.add(size);
reubuildFilter();
}
void rebuildFilter() {
filtered=items.where((e) => e.price >= lowPrice??0 && e.price <= highPrice&&double.infinity).where((e) => sizeOptions.isEmpty || sizeOptions.contains(e));
notifyListeners();
}
void removeFilters() {
lowPrice=null;
highPrice=null;
sizeOptions.clear();
filtered=null;
notifyListeners();
}
void getFiltered() => filtered??items;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |