On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. sync* and yield
  4. 2. Generators Are Lazy
  5. 3. yield*: Hand Over Many at Once
  6. 4. A Peek at async* (Streams)
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 055: Generators

DayExtra Topics
Lecture055 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

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* and yield
  • Use its values in a for loop or with .toList()
  • Understand that generators are lazy
  • Hand over a whole list at once with yield*
  • Recognise an asynchronous generator (async* and Stream)

1. sync* and yield

A generator is marked sync* and returns an Iterable. Instead of return, it uses yield to hand out each value:

dart
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

code
[1, 2, 3, 4, 5]
n = 1
n = 2
n = 3

Each 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:

dart
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

code
  (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:

dart
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:

dart
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)

code
3...
2...
1...
Lift off!

Future, async and await are explained in Lecture 056.

sync*async*
ReturnsIterable<T>Stream<T>
Values arriveimmediately, when asked forover time
Read withfor, .toList(), take, where …await for

Code Examples

Example 1: Fibonacci and a Timetable

dart
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

code
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
144
9:00  Dart
10:00  Flutter
11:00  Break
12:00  Firebase

fibonacci() 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*

dart
Iterable<int> numbers() {
  yield 1;
}
code
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

dart
Iterable<int> numbers() sync* {
  return [1, 2, 3];
}
code
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

  1. What two things turn a function into a synchronous generator?
  2. What does countTo(4).toList() give?
  3. What does yield* do?
  4. Why doesn't fibonacci().take(5) run forever?
  5. Which keyword marks an asynchronous generator, and what type does it return?

Practice Answers

  1. sync* after the parameters, and yield to give out values (return type Iterable).
  2. [1, 2, 3, 4]
  3. Gives out every value from another iterable, one by one.
  4. Generators are lazy, so only five values are ever made.
  5. async*, returning a Stream.

Key Takeaways

  • sync* + yield = a generator that returns an Iterable, 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, first or break.
  • async* makes a Stream of values over time, read with await for.