CodeBlanks Logo Icon CodeBlanks

where

Learn filtering with .where.

The where method

The where method picks elements that match a condition. The original list does not change; the result is a new Iterable. It is used for filtering.

Example: var evens = [1, 2, 3, 4].where((n) => n.isEven);. Here the condition n.isEven keeps only even numbers. The result is [2, 4].

Like map, where is lazy. To see the result you use toList(). The condition function keeps elements that return true and drops those that return false.

Filtering with where

The where method takes an arrow function that returns a bool. If the function returns true the element stays; if false it is dropped.

Example: var short = ['cat', 'dog', 'rabbit'].where((s) => s.length < 5);. Here fruits shorter than five letters are picked. Result: ['cat', 'dog'].

Another example: var positive = [-2, 0, 3].where((n) => n > 0);. Only positive numbers remain: [3]. where is the core tool for narrowing data by a condition.

Practice Filter even numbers

Call where on the list [1, 2, 3, 4, 5, 6]. The condition should be (n) => n.isEven. Convert the result to a list with toList() and print it.

Starter code

main.dart
void main() {
  var numbers = [1, 2, 3, 4, 5, 6];
  // use .where to filter even numbers, convert with toList and print
}

Sample solution

main.dart
void main() {
  var numbers = [1, 2, 3, 4, 5, 6];
  var evens = numbers.where((n) => n.isEven);
  print(evens.toList());
}

Expected output

[2, 4, 6]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens to an element when where returns false?

main.dart
var a = [1, 2, 3].where((n) => n > 5);
  • It is added to the list
  • It throws an error
  • It is moved to the end
  • It is dropped, not in the result Correct answer

Explanation: where drops elements that return false.

2 The where call

Question
var numbers = [1, 2, 3, 4, 5, 6];
var evens = numbers.____((n) => n.isEven);
Answer
var numbers = [1, 2, 3, 4, 5, 6];
var evens = numbers.where((n) => n.isEven);

Explanation: where filters by a condition.

3 Match the where parts

Term Meaning
(n) => n.isEven Even number condition
.where(...) Filter call
true Keep element
false Drop element

All lessons in Intermediate