On this page11 sections
Lecture 055: Generators
| Day | Extra Topics |
| Lecture | 055 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
A normal function builds its whole answer and returns it once. A generator hands out values one at a time, only when they're asked for. It can even produce an endless sequence, because it only makes the values you actually use.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 020–022 (loops), 025 (functions) and 048 (where, take-style list methods).
Section 4 previews Lecture 056 (async).
Learning Objectives
- Write a synchronous generator with
sync*andyield - Use its values in a
forloop or with.toList() - Understand that generators are lazy
- Hand over a whole list at once with
yield* - Recognise an asynchronous generator (
async*andStream)
1. sync* and yield
A generator is marked sync* and returns an Iterable. Instead of return, it uses yield
to hand out each value:
Iterable<int> countTo(int n) sync* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
void main() {
print(countTo(5).toList()); // [1, 2, 3, 4, 5]
for (var n in countTo(3)) {
print('n = $n');
}
}Output
[1, 2, 3, 4, 5]
n = 1
n = 2
n = 3Each yield gives one value to whoever is asking, then the function pauses until the next value
is wanted.
2. Generators Are Lazy
A generator only does the work for the values you take:
Iterable<int> evens(int limit) sync* {
for (var i = 0; i <= limit; i += 2) {
print(' (making $i)');
yield i;
}
}
print(evens(100).take(2).toList());Output
(making 0)
(making 2)
[0, 2]The limit is 100, but only two values were ever made, because take(2) stopped asking.
3. yield*: Hand Over Many at Once
yield* passes along every value from another iterable:
Iterable<String> greetings() sync* {
yield 'Hello';
yield 'Salam';
yield* ['Hola', 'Bonjour'];
}
print(greetings().toList()); // [Hello, Salam, Hola, Bonjour]4. A Peek at async* (Streams)
async* is the same idea for values that arrive over time. It returns a Stream, can use
await, and is read with await for:
Stream<int> countdown(int from) async* {
for (var i = from; i >= 1; i--) {
await Future.delayed(Duration(milliseconds: 300));
yield i;
}
}
Future<void> main() async {
await for (var n in countdown(3)) {
print('$n...');
}
print('Lift off!');
}Output (one line every 0.3 seconds)
3...
2...
1...
Lift off!Future, async and await are explained in Lecture 056.
sync* | async* | |
|---|---|---|
| Returns | Iterable<T> | Stream<T> |
| Values arrive | immediately, when asked for | over time |
| Read with | for, .toList(), take, where … | await for |
Code Examples
Example 1: Fibonacci and a Timetable
Iterable<int> fibonacci() sync* {
var a = 0, b = 1;
while (true) {
yield a;
var next = a + b;
a = b;
b = next;
}
}
Iterable<String> timetable(List<String> subjects, int startHour) sync* {
var hour = startHour;
for (var subject in subjects) {
yield '$hour:00 $subject';
hour++;
}
}
void main() {
print(fibonacci().take(10).toList());
print(fibonacci().where((n) => n > 100).first);
for (var slot in timetable(['Dart', 'Flutter', 'Break', 'Firebase'], 9)) {
print(slot);
}
}Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
144
9:00 Dart
10:00 Flutter
11:00 Break
12:00 Firebasefibonacci() has a while (true) loop that never ends, and that's fine. take(10) and
.first stop asking once they have what they need.
Common Beginner Mistakes
1. Forgetting sync*
Iterable<int> numbers() {
yield 1;
}Error: Expected ';' after this.
Error: Undefined name 'yield'.Without sync*, yield means nothing to Dart. Write Iterable<int> numbers() sync* { ... }.
2. Using return with a value in a generator
Iterable<int> numbers() sync* {
return [1, 2, 3];
}Error: 'sync*' and 'async*' can't return a value.Use yield* [1, 2, 3];.
3. Calling .toList() on an endless generator: fibonacci().toList() never finishes.
Always limit it first with take(n), first or a break.
Practice Questions
- What two things turn a function into a synchronous generator?
- What does
countTo(4).toList()give? - What does
yield*do? - Why doesn't
fibonacci().take(5)run forever? - Which keyword marks an asynchronous generator, and what type does it return?
Practice Answers
sync*after the parameters, andyieldto give out values (return typeIterable).[1, 2, 3, 4]- Gives out every value from another iterable, one by one.
- Generators are lazy, so only five values are ever made.
async*, returning aStream.
Key Takeaways
sync*+yield= a generator that returns anIterable, one value at a time.- Generators are lazy: they only make the values you ask for.
yield*passes along a whole iterable.- Endless generators are fine if you limit them with
take,firstorbreak. async*makes aStreamof values over time, read withawait for.