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
Parameter | Optional/Required | Description |
---|---|---|
test | required | the 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,
- We create a list of integers named
numbers
. - We then use the
removeWhere()
method onnumbers
with a predicate function that removes elements divisible by 2 (i.e., even numbers). - After the operation, the list contains only odd numbers.
- 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,
- We create a list of strings named
fruits
containing fruit names. - We then use the
removeWhere()
method onfruits
with a predicate function that removes fruits with a length greater than 5 characters. - After the operation, the list contains only fruits with 5 or fewer characters in their names.
- 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,
- We create a list of doubles named
prices
representing item prices. - We then use the
removeWhere()
method onprices
with a predicate function that removes prices less than 10. - After the operation, the list contains only prices greater than or equal to 10.
- 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.