This Dart tutorial gives you examples of how to filter elements in List
. The examples should also work for any Dart framework like Flutter and Angular Dart.
There are two methods going to be used in this tutorial: where and whereType.
Using where(bool test(E element))
where is used filter elements that satisfy the predicate function. The function needs to accept a parameter which will be passed with each element in the List
. It must return boolean
- true
means the element will be retained, while false
means the opposite.
where
doesn't mutate the original List
. It creates a new lazy Iterable
view of mapped elements. The function will be invoked only when the returned Iterable
is iterated over. That means if the Iterable
is iterated multiple times, you may get different result if the original List
is modified.
To convert the Iterable
into a List
, just use .toList()
method.
List<String> strings = ['one', 'two', 'three', 'four', 'five'];
Iterable<String> iterable = strings.where((item) {
print('invoked');
return item.length == 3;
});
print('Start iterating');
List<String> filteredList = iterable.toList();
print(filteredList);
// Modify the element and iterate again
strings.removeAt(0);
List<String> filteredList2 = iterable.toList();
print(filteredList2);
If you run the code above, you will see that 'invoked' only printed after 'Start iterating', not when the lazy Iterable
created. You will also find that the original List
is not mutated.
Result:
filteredList: [one, two]
filteredList2: [two]
original: [two, three, four, five]
Using whereType<T>()
Dart allows us to create List<dynamic>
whose elements may have different types. In case you need to get only elements with certain types, you can use whereType
.
Like where
, whereType
also returns a new lazy Iterable
. That means you may get different result when re-iterating the Iterable
if the original List
contains different elements. It doesn't mutate the orignal List
as well.
The code below only takes elements whose type is String
.
List<dynamic> elements = ['one', 'two', 'three', 'four', 'five', 1];
Iterable<String> filtered = elements.whereType();
List<String> filteredList = filtered.toList();
print('filteredList: $filteredList');
Result:
filteredList: [one, two, three, four, five]