What is List retainWhere() in Dart?
The retainWhere() method removes all items from the list that fail to satisfy the specified condition.
Syntax
void retainWhere (
bool test(
E element
)
)
Parameter
This function takes element as a parameter and removes the rest of the items that do not specify the condition.
Return type
It returns nothing, so its return type is void.
Code
The following code shows how to use the method retainWhere() in Dart:
void main(){List numbers = [2, 6, 23, 14, 34, 8, 12, 57, 41, 1, 6];print('Original list before removing elements: ${numbers}');// Using retainWhere()// keep items greater than 10// and remove the rest of the items.numbers.retainWhere((item) => item > 10);// Display resultprint(' The new list after removing elements: ${numbers}');// Creating listList<String> names = ['Maria', 'Elizabeth', 'David', 'Elisa', 'Naomi', 'John', 'Joe'];print('Original list before removing elements: ${names}');// Using retainWhere()// keep items whose length is greater than or equal to 5// and remove the rest of the items.names.retainWhere((item) => item.length >= 5);//Display resultprint(' The new list after removing elements: ${names}');}
Explanation
- Line 2: We create the list of numbers and initialize it.
- Line 7: We use
retainWhere(), which keeps items greater than 10 and removes the rest of the items. - Line 8: We display the results.
- Line 12: We create the list of string
nameand initialize it. - Line 17: We use
retainWhere(), which keeps items whose length is greater than or equal to 5 and removes the rest of the items. - Line 19: We display the results.