The syntax of List.where() method is:
Iterable<E> where(bool test(E element))
This where() method of List creates a new lazy Iterable
with all elements that satisfy the predicate test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | the predicate function that defines the test for elements |
List.where() returns value of type Iterable<E>
.
In this example,
numbers
containing integers.where()
method with a predicate function to filter even numbers (numbers divisible by 2).evenNumbers
contains only the even numbers from the original list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
var evenNumbers = numbers.where((element) => element % 2 == 0);
print('Even numbers: $evenNumbers');
}
Even numbers: (2, 4)
In this example,
fruits
containing strings representing fruits.where()
method with a predicate function to filter fruits with a length greater than 5 characters.longFruits
contains only the fruits with length greater than 5.void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'orange'];
var longFruits = fruits.where((fruit) => fruit.length > 5);
print('Fruits with length > 5: $longFruits');
}
Fruits with length > 5: (banana, cherry, orange)
In this example,
prices
containing double values representing prices.where()
method with a predicate function to filter prices that are greater than or equal to 10.expensivePrices
contains only the prices that are considered expensive.void main() {
Set<double> prices = {9.99, 15.49, 20.00, 5.99};
var expensivePrices = prices.where((price) => price >= 10);
print('Expensive prices: $expensivePrices');
}
Expensive prices: (15.49, 20)
In this Dart tutorial, we learned about where() method of List: the syntax and few working examples with output and detailed explanation for each example.