Dart List retainWhere()
Syntax & Examples
Syntax of List.retainWhere()
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
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | the function that determines whether an element should be retained |
Return Type
List.retainWhere() returns value of type void
.
✐ Examples
1 Retain even numbers from a list
In this example,
- We create a list
numbers
containing integers. - We use
retainWhere
with a condition(element) => element % 2 == 0
to retain only even numbers. - The resulting list contains only even numbers.
- We print the modified list.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.retainWhere((element) => element % 2 == 0);
print(numbers);
}
Output
[2, 4]
2 Retain fruits starting with 'a'
In this example,
- We create a list
fruits
containing strings of fruits. - We use
retainWhere
with a condition(element) => element.startsWith('a')
to retain only fruits starting with 'a'. - The resulting list contains only fruits starting with 'a'.
- We print the modified list.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.retainWhere((element) => element.startsWith('a'));
print(fruits);
}
Output
[apple]
3 Retain prices greater than or equal to 15.0
In this example,
- We create a list
prices
containing double values. - We use
retainWhere
with a condition(element) => element >= 15.0
to retain only prices greater than or equal to 15.0. - The resulting list contains only prices meeting the condition.
- We print the modified list.
Dart Program
void main() {
List<double> prices = [10.5, 15.2, 20.8, 5.7];
prices.retainWhere((element) => element >= 15.0);
print(prices);
}
Output
[15.2, 20.8]
Summary
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.