On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Idea
  4. 2. Why .toList()?
  5. 3. More Conditions
  6. 4. Related Tools
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 013: Filtering with where

Day5: Lists & Maps
Lecture013 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

"Show me only the products under Rs 100." "Which students passed?" Picking the items that match a condition is one of the most common jobs in any app. In Dart, where does it in one line.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lecture 011 (lists).


Learning Objectives

  • Keep only the items that match a condition with where
  • Turn the result into a list with .toList()
  • Find the first match with firstWhere
  • Check "any?" and "all?" with any and every

1. The Idea

where looks at every item and keeps the ones for which your condition is true:

dart
var numbers = [5, 12, 8, 21, 3, 17];
var big = numbers.where((n) => n > 10).toList();
print(big);   // [12, 21, 17]

Read (n) => n > 10 as: "for each item n, keep it if n > 10". It is a tiny function. Days 10 and 14 explain functions properly; for now, just change the part after =>.

The condition uses a comparison, which is always true or false:

OperatorMeansExample (n is 12)
> / <greater / less thann > 10 is true
>= / <=greater / less than or equaln <= 12 is true
== / !=equal / not equaln == 5 is false

Lecture 015 covers these, and how to combine them, in full.

The original list is not changed:

dart
print(numbers);   // [5, 12, 8, 21, 3, 17]

2. Why .toList()?

where gives back an iterable, a lazy sequence. It prints with round brackets:

dart
print(numbers.where((n) => n > 10));          // (12, 21, 17)
print(numbers.where((n) => n > 10).toList()); // [12, 21, 17]

Add .toList() when you need a real list (to store it, index it or add to it).

3. More Conditions

dart
var evens = numbers.where((n) => n % 2 == 0).toList();
print(evens);    // [12, 8]

% gives the remainder after dividing: 12 % 2 is 0, 5 % 2 is 1. So n % 2 == 0 means "n is even".

dart
var names = ['Ali', 'Sara', 'Ahmed', 'Zara', 'Amna'];
var aNames = names.where((name) => name.startsWith('A')).toList();
print(aNames);   // [Ali, Ahmed, Amna]

print(numbers.where((n) => n > 100).toList());  // [] (nothing matched)
dart
print(numbers.firstWhere((n) => n > 10));    // 12 (the first match only)
print(numbers.any((n) => n > 20));           // true (at least one?)
print(numbers.every((n) => n > 0));          // true (all of them?)
print(numbers.where((n) => n > 10).length);  // 3 (how many match?)
ToolGives
where(test)every matching item (add .toList())
firstWhere(test)the first matching item
any(test)true if at least one item matches
every(test)true if all items match

Code Examples

Example 1: Filtering a Shop

dart
void main() {
  var prices = [120, 850, 45, 1500, 300, 60];
  var products = ['Pen', 'Shoes', 'Eraser', 'Watch', 'Book', 'Pencil'];

  var cheap = prices.where((p) => p < 100).toList();
  var expensive = prices.where((p) => p >= 1000).toList();
  var shortNames = products.where((p) => p.length <= 4).toList();

  print('Under Rs 100: $cheap');
  print('Rs 1000 or more: $expensive');
  print('Short names: $shortNames');
  print('Anything over Rs 2000? ${prices.any((p) => p > 2000)}');
  print('First over Rs 200: ${prices.firstWhere((p) => p > 200)}');
}

Output

code
Under Rs 100: [45, 60]
Rs 1000 or more: [1500]
Short names: [Pen, Book]
Anything over Rs 2000? false
First over Rs 200: 850

Common Beginner Mistakes

1. Storing the result without .toList()

dart
List<int> big = numbers.where((n) => n > 6);
code
Error: A value of type 'Iterable<int>' can't be assigned to a variable of type 'List<int>'.

Add .toList() at the end.

2. firstWhere with no match

dart
print(numbers.firstWhere((n) => n > 50));
code
Unhandled exception:
Bad state: No element

Check with any first, or use where(...).toList() and test isEmpty.

3. = instead of == in the condition

dart
print(numbers.where((n) => n = 12).toList());
code
Error: A value of type 'int' can't be returned from a function with return type 'bool'.

= assigns; == compares. The condition must give true or false.

4. Expecting where to change the list: it builds a new result; the original stays the same.


Practice Questions

  1. What does [2, 9, 4, 11].where((n) => n > 5).toList() give?
  2. Why add .toList()?
  3. Write a line that keeps only the names longer than 4 letters from names.
  4. What does [1, 3, 5].every((n) => n.isOdd) give?
  5. What happens with [1, 2].firstWhere((n) => n > 5)?

Practice Answers

  1. [9, 11]
  2. where returns an iterable; .toList() makes a real list you can store and index.
  3. var longNames = names.where((name) => name.length > 4).toList();
  4. true
  5. It crashes with Bad state: No element.

Key Takeaways

  • list.where((x) => condition).toList() keeps the matching items.
  • The original list doesn't change.
  • firstWhere gives the first match (and crashes if there's none).
  • any asks "at least one?"; every asks "all of them?".