The retainWhere() method removes all items from the list that fail to satisfy the specified condition.
void retainWhere (
bool test(
E element
)
)
This function takes element as a parameter and removes the rest of the items that do not specify the condition.
It returns nothing, so its return type is void.
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}');}
retainWhere(), which keeps items greater than 10 and removes the rest of the items.name and initialize it.retainWhere(), which keeps items whose length is greater than or equal to 5 and removes the rest of the items.