Sync and async generators

suggest change

A generator is a function that produces a sequence of values one at a time instead of building and returning a whole collection. Dart has two kinds:

Inside a generator you emit values with yield and forward a whole sequence with yield*. Together with ordinary and async functions this gives four kinds of function bodies:

Body Returns Produces
(none) T one value, now
async Future<T> one value, later
sync* Iterable<T> many values, on demand
async* Stream<T> many values, over time

The examples were run with Dart 3.13.

A first sync* generator

The body of a sync* function does not run when the function is called. Calling it just returns an Iterable. The body starts when someone iterates, and it runs only until the next yield, where it pauses until the next element is requested:

Iterable<int> countdown(int from) sync* {
  print('  [start]');
  for (var i = from; i > 0; i--) {
    print('  [yield $i]');
    yield i;
  }
  print('  [done]');
}

void main() {
  final numbers = countdown(3);
  print('created, is Iterable<int>: ${numbers is Iterable<int>}');
  for (final n in numbers) {
    print('got $n');
  }
  print('first: ${numbers.first}');
}

Output:

created, is Iterable<int>: true
  [start]
  [yield 3]
got 3
  [yield 2]
got 2
  [yield 1]
got 1
  [done]
  [start]
  [yield 3]
first: 3

Notice three things:

Every new iteration (each for loop, toList(), length, first, ...) gets a fresh iterator that runs the body from the beginning.

Infinite sequences

Because values are produced only on demand, a generator can describe an infinite sequence. The consumer decides how much of it to take using the normal Iterable methods:

Iterable<int> naturals() sync* {
  var n = 1;
  while (true) {
    yield n++;
  }
}

Iterable<int> fibonacci() sync* {
  var (a, b) = (0, 1);
  while (true) {
    yield a;
    (a, b) = (b, a + b);
  }
}

void main() {
  print(naturals().take(5).toList());
  print(naturals().where((n) => n % 7 == 0).take(3).toList());
  print(fibonacci().skip(10).first);
  print(fibonacci().takeWhile((f) => f < 100).join(' '));
  print(naturals().map((n) => n * n).elementAt(9));
}

Output:

[1, 2, 3, 4, 5]
[7, 14, 21]
55
0 1 1 2 3 5 8 13 21 34 55 89
100

map, where, skip and take are lazy too, so the whole pipeline pulls just as many values as it needs. Don't call toList(), length or last directly on an infinite generator: they iterate to the end, which never comes.

The body runs again on every iteration

Laziness means repeated work. Every call to length, toList() or a for loop re-runs the generator:

Iterable<int> randomish() sync* {
  print('  (body runs)');
  yield 1;
  yield 2;
}

void main() {
  final it = randomish();
  print(it.length);
  print(it.toList());
  final cached = it.toList();
  print(cached.length);
  print(cached.last);
}

Output:

  (body runs)
2
  (body runs)
[1, 2]
  (body runs)
2
2

If the generator is expensive, reads external state or has side effects, and you need the values more than once, materialize them once with toList() and reuse the list.

Delegating with yield*

yield* expr emits every element of another iterable, in order, as if you had looped over it and yielded each one. It's the way to compose generators and to write recursive ones:

Iterable<String> lines(String header, List<String> body, String footer) sync* {
  yield header;
  yield* body;
  yield footer;
}

Iterable<T> concat<T>(Iterable<Iterable<T>> parts) sync* {
  for (final p in parts) {
    yield* p;
  }
}

Iterable<Object?> flatten(Iterable<Object?> items) sync* {
  for (final item in items) {
    if (item is Iterable<Object?>) {
      yield* flatten(item);
    } else {
      yield item;
    }
  }
}

void main() {
  print(lines('<ul>', ['<li>a</li>', '<li>b</li>'], '</ul>').join('\n'));
  print(concat([[1, 2], {3}, Iterable.generate(2, (i) => 10 + i)]).toList());
  print(flatten([1, [2, [3, [4, 5]], 6], [], 7]).toList());
}

Output:

<ul>
<li>a</li>
<li>b</li>
</ul>
[1, 2, 3, 10, 11]
[1, 2, 3, 4, 5, 6, 7]

yield* accepts any Iterable: a list, a set, another generator, or the result of map. Recursion shows more recursive generators, such as tree traversals, permutations and subsets.

Stopping early with return

A plain return; ends a generator. The sequence is simply shorter. A generator can't return a value: return 42; in a sync* or async* function is a compile error.

Iterable<String> readUntilBlank(List<String> input) sync* {
  for (final line in input) {
    if (line.isEmpty) return;
    yield line.trim();
  }
  print('  reached end of input');
}

void main() {
  print(readUntilBlank(['a ', ' b', '', 'c']).toList());
  print(readUntilBlank(['x', 'y']).toList());
}

Output:

[a, b]
  reached end of input
[x, y]

Argument checks are lazy too

Since nothing in the body runs at call time, validation at the top of a generator is delayed until the first iteration. That can be far away from the buggy call, which makes the error confusing. The fix is to split the function: an ordinary function validates eagerly and then returns a private generator:

Iterable<int> range(int start, int end) sync* {
  if (end < start) throw ArgumentError('end < start');
  for (var i = start; i < end; i++) {
    yield i;
  }
}

Iterable<int> checkedRange(int start, int end) {
  if (end < start) throw ArgumentError('end < start');
  return _range(start, end);
}

Iterable<int> _range(int start, int end) sync* {
  for (var i = start; i < end; i++) {
    yield i;
  }
}

void main() {
  final lazy = range(5, 1);
  print('range(5, 1) returned without error');
  try {
    lazy.toList();
  } on ArgumentError catch (e) {
    print('error on iteration: ${e.message}');
  }

  try {
    checkedRange(5, 1);
  } on ArgumentError catch (e) {
    print('error on call: ${e.message}');
  }
}

Output:

range(5, 1) returned without error
error on iteration: end < start
error on call: end < start

Any exception thrown inside a sync* body reaches the code that is iterating, at the moment the failing element is requested.

Making a class iterable

To make your own class work with for-in and all the Iterable methods, extend IterableBase (or mix in Iterable) and implement iterator. A generator saves you from writing an Iterator class by hand: return the iterator of a sync* method. Other sync* methods can expose alternative views of the same data:

import 'dart:collection';

class Grid<T> extends IterableBase<(int, int, T)> {
  final int width, height;
  final List<T> _cells;

  Grid(this.width, this.height, T fill)
      : _cells = List.filled(width * height, fill);

  void operator []=((int, int) pos, T value) =>
      _cells[pos.$2 * width + pos.$1] = value;

  @override
  Iterator<(int, int, T)> get iterator => _entries().iterator;

  Iterable<(int, int, T)> _entries() sync* {
    for (var y = 0; y < height; y++) {
      for (var x = 0; x < width; x++) {
        yield (x, y, _cells[y * width + x]);
      }
    }
  }

  Iterable<T> row(int y) sync* {
    for (var x = 0; x < width; x++) {
      yield _cells[y * width + x];
    }
  }
}

void main() {
  final g = Grid(3, 2, '.');
  g[(1, 0)] = '#';
  g[(2, 1)] = '@';
  print(g.where((c) => c.$3 != '.').toList());
  print(g.length);
  print(g.row(1).join());
  for (final (x, y, v) in g.take(2)) {
    print('$x,$y = $v');
  }
}

Output:

[(1, 0, #), (2, 1, @)]
6
..@
0,0 = .
1,0 = #

IterableBase implements length, where, take, toString and the rest on top of iterator. Override length or elementAt if your class can answer them faster than by iterating.

A first async* generator

An async* function returns a Stream<T>. Inside it you can use await as in an async function, and yield to emit stream events. The body starts when the stream is listened to, not when the function is called. When the body finishes the stream sends its done event:

Stream<int> ticker(int count, Duration interval) async* {
  print('  [ticker started]');
  for (var i = 1; i <= count; i++) {
    await Future<void>.delayed(interval);
    yield i;
  }
  print('  [ticker finished]');
}

Future<void> main() async {
  final stream = ticker(3, const Duration(milliseconds: 100));
  print('stream created');
  final sw = Stopwatch()..start();
  await for (final n in stream) {
    print('tick $n at ~${(sw.elapsedMilliseconds / 100).round() * 100} ms');
  }
  print('all done');
}

Output:

stream created
  [ticker started]
tick 1 at ~100 ms
tick 2 at ~200 ms
tick 3 at ~300 ms
  [ticker finished]
all done

await for is the consuming side: it waits for each event and exits the loop when the stream is done. It can only be used inside an async (or async*) function. See Async and Await for the basics of futures and await.

Cancellation runs finally

When the listener cancels its subscription, the generator stops at its current yield and does not continue. Any enclosing finally blocks still run, so that's where you release resources (close files, sockets, timers). Breaking out of await for and using take, first or firstWhere all cancel the subscription:

Stream<int> numbers() async* {
  try {
    for (var i = 1; ; i++) {
      print('  yielding $i');
      yield i;
    }
  } finally {
    print('  cleanup in finally');
  }
}

Future<void> main() async {
  await for (final n in numbers()) {
    print('got $n');
    if (n == 2) break;
  }
  print('after loop');

  final firstThree = await numbers().take(3).toList();
  print(firstThree);
}

Output:

  yielding 1
got 1
  yielding 2
got 2
  cleanup in finally
after loop
  yielding 1
  yielding 2
  yielding 3
  cleanup in finally
[1, 2, 3]

The same applies to sync* generators: if the consumer stops iterating early, the rest of the body, including finally, simply never runs, because an Iterator has no "cancel" operation. Don't rely on finally in a sync* generator for cleanup.

Back-pressure: pausing the subscription

yield in an async* function also respects pausing. While the subscription is paused, the generator is suspended at its yield and doesn't produce more values. A slow consumer automatically slows down the producer:

import 'dart:async';

Stream<int> producer() async* {
  for (var i = 1; i <= 4; i++) {
    print('  produce $i');
    yield i;
  }
  print('  producer finished');
}

void main() {
  late StreamSubscription<int> sub;
  sub = producer().listen(
    (n) {
      print('consume $n');
      if (n == 2) {
        print('pause');
        sub.pause();
        Timer(const Duration(milliseconds: 100), () {
          print('resume');
          sub.resume();
        });
      }
    },
    onDone: () => print('done'),
  );
}

Output:

  produce 1
consume 1
  produce 2
consume 2
pause
resume
  produce 3
consume 3
  produce 4
consume 4
  producer finished
done

await for pauses the subscription for you while the loop body awaits something, so you get back-pressure without writing any of this by hand.

Transforming streams

await for inside an async* function is the easiest way to write a stream transformer: read events from one stream, emit events on another. yield* forwards every event of another stream. Here, three small generators turn arbitrary text chunks into batches of lines, skipping comments:

Stream<String> readLines(List<String> chunks) async* {
  var pending = '';
  for (final chunk in chunks) {
    await Future<void>.delayed(const Duration(milliseconds: 10));
    final parts = (pending + chunk).split('\n');
    pending = parts.removeLast();
    yield* Stream.fromIterable(parts);
  }
  if (pending.isNotEmpty) yield pending;
}

Stream<T> where<T>(Stream<T> source, bool Function(T) test) async* {
  await for (final value in source) {
    if (test(value)) yield value;
  }
}

Stream<List<T>> batches<T>(Stream<T> source, int size) async* {
  var batch = <T>[];
  await for (final value in source) {
    batch.add(value);
    if (batch.length == size) {
      yield batch;
      batch = <T>[];
    }
  }
  if (batch.isNotEmpty) yield batch;
}

Future<void> main() async {
  final chunks = ['alpha\nbe', 'ta\n# comment\ngam', 'ma\ndelta\nepsi', 'lon'];
  final lines = readLines(chunks);
  final noComments = where(lines, (l) => !l.startsWith('#'));
  await for (final b in batches(noComments, 2)) {
    print(b);
  }
}

Output:

[alpha, beta]
[gamma, delta]
[epsilon]

For simple cases Stream already has where, map, expand and asyncMap. Generators shine when the transformation keeps state between events, like the pending buffer and the batch list above. Real code reading a file would use file.openRead().transform(utf8.decoder).transform(const LineSplitter()), which does the same chunk-to-line work.

Errors in async* generators

An exception thrown in an async* body (and not caught there) is delivered to the listener as an error event, and then the stream closes. With await for, the error is rethrown at the loop, so a normal try/catch around it works.

To report an error but keep going, emit it as an event with yield* Stream.error(...):

Stream<int> parseAll(List<String> inputs) async* {
  for (final s in inputs) {
    yield int.parse(s);
  }
}

Stream<int> parseAllLenient(List<String> inputs) async* {
  for (final s in inputs) {
    final n = int.tryParse(s);
    if (n == null) {
      yield* Stream.error(FormatException('bad number', s));
    } else {
      yield n;
    }
  }
}

Future<void> main() async {
  try {
    await for (final n in parseAll(['1', '2', 'x', '4'])) {
      print('value $n');
    }
  } on FormatException catch (e) {
    print('stopped: ${e.message} (${e.source})');
  }

  parseAllLenient(['1', 'x', '3', 'y']).listen(
    (n) => print('value $n'),
    onError: (Object e) => print('error: ${(e as FormatException).source}'),
    onDone: () => print('done'),
  );
}

Output:

value 1
value 2
stopped: Invalid radix-10 number (x)
value 1
error: x
value 3
error: y
done

Note that await for always stops at the first error event. To see errors without stopping, use listen with onError (and keep cancelOnError at its default of false), or map errors to values with handleError.

Polling with an async* loop

An infinite async* loop with a delay is a clean way to turn a polling API into a stream. Here the stream only emits when the status changes, and the consumer ends polling by breaking out of the loop:

import 'dart:async';

Stream<String> watchStatus(Future<String> Function() check,
    {Duration every = const Duration(milliseconds: 100)}) async* {
  String? last;
  while (true) {
    final status = await check();
    if (status != last) {
      yield status;
      last = status;
    }
    await Future<void>.delayed(every);
  }
}

Future<void> main() async {
  final responses = ['starting', 'starting', 'running', 'running', 'stopped'];
  var calls = 0;
  Future<String> fakeCheck() async =>
      responses[(calls++).clamp(0, responses.length - 1)];

  await for (final s in watchStatus(fakeCheck)) {
    print('status: $s (after $calls checks)');
    if (s == 'stopped') break;
  }
}

Output:

status: starting (after 1 checks)
status: running (after 3 checks)
status: stopped (after 5 checks)

Because the stream is single-subscription and pull-driven, nothing polls until someone listens, and polling stops as soon as the listener cancels. Compare that with a Timer.periodic feeding a StreamController, where you must wire up onListen, onPause and onCancel yourself to get the same behaviour. Cancellation and timeouts covers adding a timeout to such a stream.

Streams returned by async* functions are single-subscription: listening twice throws Bad state: Stream has already been listened to. Call the function again for a new stream, or use asBroadcastStream(). See Common pitfalls.

Common mistakes

yield must appear directly in the generator body. It can't be used inside a closure, such as a forEach callback, because the closure is a separate function:

Iterable<int> doubled(List<int> xs) sync* {
  xs.forEach((x) {
    yield x * 2;
  });
}
p1.dart:3:5: Error: 'yield' can only be used in 'sync*' or 'async*' methods.
    yield x * 2;
    ^^^^^

Use a for-in loop instead: for (final x in xs) yield x * 2;.

The return type must be Iterable<T> for sync* (or a supertype such as Object), and Stream<T> for async*. Declaring a List doesn't work:

List<int> evens(int n) sync* {
  for (var i = 0; i < n; i += 2) yield i;
}
p2.dart:1:1: Error: Functions marked 'sync*' must have a return type assignable to 'Iterable'.
List<int> evens(int n) sync* {
^^^^

Other things to keep in mind:

Summary

See also Ranges for a sync* range generator, Isolates for moving heavy work off the main isolate, and Async and Await.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents