Generators

When you need to lazily produce a sequence of values, consider using a generator function. Dart has built-in support for two kinds of generator functions:

  • Synchronous generator: Returns an Iterable object.

  • Asynchronous generator: Returns a Stream object.

To implement a synchronous generator function, mark the function body as sync*, and use yield statements to deliver values:

Stream<intasynchronousNaturalsTo(int n) async* {

  int k = 0;

  while (k < n) yield k++;

}



If your generator is recursive, you can improve its performance by using yield*:

Iterable<intnaturalsDownFrom(int n) sync* {

  if (n > 0) {

    yield n;

    yieldnaturalsDownFrom(n - 1);

  }

}