The syntax of List.retainWhere() method is:
void retainWhere(bool test(E element))
This retainWhere() method of List removes all objects from this list that fail to satisfy test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | the function that determines whether an element should be retained |
List.retainWhere() returns value of type void
.
In this example,
numbers
containing integers.retainWhere
with a condition (element) => element % 2 == 0
to retain only even numbers.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.retainWhere((element) => element % 2 == 0);
print(numbers);
}
[2, 4]
In this example,
fruits
containing strings of fruits.retainWhere
with a condition (element) => element.startsWith('a')
to retain only fruits starting with 'a'.void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.retainWhere((element) => element.startsWith('a'));
print(fruits);
}
[apple]
In this example,
prices
containing double values.retainWhere
with a condition (element) => element >= 15.0
to retain only prices greater than or equal to 15.0.void main() {
List<double> prices = [10.5, 15.2, 20.8, 5.7];
prices.retainWhere((element) => element >= 15.0);
print(prices);
}
[15.2, 20.8]
In this Dart tutorial, we learned about retainWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.