Dart List where()
Syntax & Examples


Syntax of List.where()

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.

Parameters

ParameterOptional/RequiredDescription
testrequiredthe predicate function that defines the test for elements

Return Type

List.where() returns value of type Iterable<E>.



✐ Examples

1 Filter even numbers

In this example,

  1. We create a list numbers containing integers.
  2. We use the where() method with a predicate function to filter even numbers (numbers divisible by 2).
  3. The resulting iterable evenNumbers contains only the even numbers from the original list.
  4. We print the result to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  var evenNumbers = numbers.where((element) => element % 2 == 0);
  print('Even numbers: $evenNumbers');
}

Output

Even numbers: (2, 4)

2 Filter fruits with length > 5

In this example,

  1. We create a list fruits containing strings representing fruits.
  2. We use the where() method with a predicate function to filter fruits with a length greater than 5 characters.
  3. The resulting iterable longFruits contains only the fruits with length greater than 5.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> fruits = ['apple', 'banana', 'cherry', 'orange'];
  var longFruits = fruits.where((fruit) => fruit.length > 5);
  print('Fruits with length > 5: $longFruits');
}

Output

Fruits with length > 5: (banana, cherry, orange)

3 Filter expensive prices

In this example,

  1. We create a set prices containing double values representing prices.
  2. We use the where() method with a predicate function to filter prices that are greater than or equal to 10.
  3. The resulting iterable expensivePrices contains only the prices that are considered expensive.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<double> prices = {9.99, 15.49, 20.00, 5.99};
  var expensivePrices = prices.where((price) => price >= 10);
  print('Expensive prices: $expensivePrices');
}

Output

Expensive prices: (15.49, 20)

Summary

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.