Iterable
- Dart course
- Intermediate
- Lesson 45/116
- 5 min
Learn iterable collections with Iterable.
Iterable<T>
Iterable<T> is the top collection interface. It is the common ancestor of List, Set and Queue. An Iterable is a sequence whose elements can be traversed one by one; but it does not support index access.
Every List or Set is also an Iterable. Methods like where, map and fold work through Iterable. These methods are lazy; the result is produced only when needed.
Example: Iterable<int> numbers = [1, 2, 3, 4, 5]; var evens = numbers.where((n) => n.isEven);. Here evens is not computed yet; it is produced when toList() is called.
Lazy evaluation
When you call where or map on an Iterable the result is not computed at once. Elements are produced only when an operation like toList(), length or a loop runs.
This is called lazy evaluation. The advantage is that no unnecessary computation happens. For example if you want only the first three even numbers from a large list the whole list is not filtered.
The toList() method turns the lazy result into a concrete list. This way you can print the result or access it by index.
Practice Filter with Iterable
Define Iterable<int> numbers = [1, 2, 3, 4, 5]. Filter even numbers with where. Convert the result to a list with toList() and print it. Then print evens.length.
Starter code
void main() {
// define an Iterable<int>, filter evens with where
// convert to a list with toList and print
}Sample solution
void main() {
Iterable<int> numbers = [1, 2, 3, 4, 5];
var evens = numbers.where((n) => n.isEven);
print(evens.toList());
print(evens.length);
}Expected output
[2, 4] 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Define an Iterable
Iterable<int> numbers = [1, 2, 3, 4, 5];
var evens = numbers.____((n) => n.isEven);
Iterable<int> numbers = [1, 2, 3, 4, 5];
var evens = numbers.where((n) => n.isEven);
Explanation: the where method filters elements by a condition.
2 Which property does Iterable have?
- Lazy and does not support indexing Correct answer
- Holds only numbers
- Supports index access
- Has a fixed size
Explanation: Iterable is lazy and does not support index access.
3 Match the Iterable methods
| Term | Meaning |
|---|---|
where(...) |
Filter |
map(...) |
Transform |
toList() |
Convert to list |
fold(...) |
Combine |