On this page11 sections
Lecture 013: Filtering with where
| Day | 5: Lists & Maps |
| Lecture | 013 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
"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,
wheredoes 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
anyandevery
1. The Idea
where looks at every item and keeps the ones for which your condition is true:
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:
| Operator | Means | Example (n is 12) |
|---|---|---|
> / < | greater / less than | n > 10 is true |
>= / <= | greater / less than or equal | n <= 12 is true |
== / != | equal / not equal | n == 5 is false |
Lecture 015 covers these, and how to combine them, in full.
The original list is not changed:
print(numbers); // [5, 12, 8, 21, 3, 17]2. Why .toList()?
where gives back an iterable, a lazy sequence. It prints with round brackets:
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
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".
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)4. Related Tools
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?)| Tool | Gives |
|---|---|
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
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
Under Rs 100: [45, 60]
Rs 1000 or more: [1500]
Short names: [Pen, Book]
Anything over Rs 2000? false
First over Rs 200: 850Common Beginner Mistakes
1. Storing the result without .toList()
List<int> big = numbers.where((n) => n > 6);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
print(numbers.firstWhere((n) => n > 50));Unhandled exception:
Bad state: No elementCheck with any first, or use where(...).toList() and test isEmpty.
3. = instead of == in the condition
print(numbers.where((n) => n = 12).toList());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
- What does
[2, 9, 4, 11].where((n) => n > 5).toList()give? - Why add
.toList()? - Write a line that keeps only the names longer than 4 letters from
names. - What does
[1, 3, 5].every((n) => n.isOdd)give? - What happens with
[1, 2].firstWhere((n) => n > 5)?
Practice Answers
[9, 11]wherereturns an iterable;.toList()makes a real list you can store and index.var longNames = names.where((name) => name.length > 4).toList();true- It crashes with
Bad state: No element.
Key Takeaways
list.where((x) => condition).toList()keeps the matching items.- The original list doesn't change.
firstWheregives the first match (and crashes if there's none).anyasks "at least one?";everyasks "all of them?".