In this blog post, we will discuss how to filter a list in Flutter based on some condition. Filtering a list is an essential operation that can be used in various scenarios, such as sorting data, selecting items based on specific criteria, or removing unwanted items from the list.
Problem Statement
Consider you have a list of movies and you want to filter them by their animation status. You might want to display only animated movies or non-animated movies in your app.
List<dynamic> AllMovies = [ {'id': '1', 'title': 'Movie1', 'isAnimated': true}, {'id': '2', 'title': 'Movie2', 'isAnimated': false}, {'id': '3', 'title': 'Movie3', 'isAnimated': true}, {'id': '4', 'title': 'Movie4', 'isAnimated': false} ];
You might attempt to filter this list using the where
method as shown below:
List<dynamic> AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList();
However, you will find that the result is empty. This is because Dart’s collection methods like where
, forEach
, etc., are lazy operations. They don’t actually compute the result until you call a method on it or try to iterate over the resulting list.
The Solution Is Here
One solution is to use a function that wraps around the where
method and calls toList()
explicitly. Let’s create a function called getCategoryList
for this purpose.
List<dynamic> getCategoryList(List<dynamic> inputlist) { List outputList = inputlist.where((o) => o['category_id'] == '1').toList(); return outputList; }
This function takes a list of dynamic items as an argument and returns the filtered list. You can use this function to get the list of movies based on their category ID.
Example Usage
To use the getCategoryList
function, you simply need to call it with your input list and pass it as an argument:
void main() { List<dynamic> AllMovies = [ {'id': '1', 'title': 'Movie1', 'category_id': '1'}, {'id': '2', 'title': 'Movie2', 'category_id': '1'}, {'id': '3', 'title': 'Movie3', 'category_id': '2'}, ]; List<dynamic> filteredList = getCategoryList(AllMovies); print(filteredList); // Output: [{'id': '1', 'title': 'Movie1', 'category_id': '1'}, {'id': '2', 'title': 'Movie2', 'category_id': '1'}] }
By wrapping the where
method in a function and explicitly calling toList()
, you ensure that the result is materialized, providing you with the desired output.
Conclusion
In this blog post, we discussed how to filter a list in Flutter based on some condition. We identified a common problem when using lazy collection methods like where
and proposed a solution by creating a function that explicitly calls toList()
. By applying these concepts, you can now confidently work with lists in your Flutter applications.