Dart Tutorials

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

ParameterOptional/RequiredDescription
testrequiredthe 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,

  1. We create a list numbers containing integers.
  2. We use retainWhere with a condition (element) => element % 2 == 0 to retain only even numbers.
  3. The resulting list contains only even numbers.
  4. 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,

  1. We create a list fruits containing strings of fruits.
  2. We use retainWhere with a condition (element) => element.startsWith('a') to retain only fruits starting with 'a'.
  3. The resulting list contains only fruits starting with 'a'.
  4. 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,

  1. We create a list prices containing double values.
  2. We use retainWhere with a condition (element) => element >= 15.0 to retain only prices greater than or equal to 15.0.
  3. The resulting list contains only prices meeting the condition.
  4. 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.