Introduction
In Flutter/Dart, we may wish to filter items in a List. In this post, we'll look at how to do it.
How to filter items in a List in Flutter
Filter items in a list using where()
method
var list = [5, 2, 0, 1];
print(list.where((item) => item >= 2).toList());
The output:
[5, 2]
Getting the first item from a list that matches a specific condition using the firstWhere()
method
var list = [5, 2, 0, 1, 6];
print(list.firstWhere((item) => item > 2));
The output:
5
Getting the last item from a list that matches the given condition using the lastWhere()
method
var list = [5, 2, 0, 1, 6];
print(list.lastWhere((item) => item > 2));
The output:
6
Conclusion
In this article, we presented several methods to filter items in a list in Flutter/Dart.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}