Dart List removeWhere()
Syntax & Examples


Syntax of List.removeWhere()

The syntax of List.removeWhere() method is:

 void removeWhere(bool test(E element)) 

This removeWhere() method of List removes all objects from this list that satisfy test.

Parameters

ParameterOptional/RequiredDescription
testrequiredthe predicate function to test each element

Return Type

List.removeWhere() returns value of type void.



✐ Examples

1 Remove even numbers from the list

In this example,

  1. We create a list of integers named numbers.
  2. We then use the removeWhere() method on numbers with a predicate function that removes elements divisible by 2 (i.e., even numbers).
  3. After the operation, the list contains only odd numbers.
  4. We print the modified list to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  numbers.removeWhere((element) => element % 2 == 0);
  print(numbers);
}

Output

[1, 3, 5]

2 Remove fruits with length greater than 5

In this example,

  1. We create a list of strings named fruits containing fruit names.
  2. We then use the removeWhere() method on fruits with a predicate function that removes fruits with a length greater than 5 characters.
  3. After the operation, the list contains only fruits with 5 or fewer characters in their names.
  4. We print the modified list to standard output.

Dart Program

void main() {
  List<String> fruits = ['apple', 'banana', 'cherry', 'orange'];
  fruits.removeWhere((fruit) => fruit.length > 5);
  print(fruits);
}

Output

[apple]

3 Remove prices less than 10

In this example,

  1. We create a list of doubles named prices representing item prices.
  2. We then use the removeWhere() method on prices with a predicate function that removes prices less than 10.
  3. After the operation, the list contains only prices greater than or equal to 10.
  4. We print the modified list to standard output.

Dart Program

void main() {
  List<double> prices = [9.99, 15.49, 4.75, 23.99, 8.25];
  prices.removeWhere((price) => price < 10);
  print(prices);
}

Output

[15.49, 23.99]

Summary

In this Dart tutorial, we learned about removeWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.