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:

  1. Iterable<int> naturalsTo(int n) sync* {
  2. int k = 0;
  3. while (k < n) yield k++;
  4. }

To implement an asynchronous generator function,mark the function body as async*,and use yield statements to deliver values:

  1. Stream<int> asynchronousNaturalsTo(int n) async* {
  2. int k = 0;
  3. while (k < n) yield k++;
  4. }

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

  1. Iterable<int> naturalsDownFrom(int n) sync* {
  2. if (n > 0) {
  3. yield n;
  4. yield* naturalsDownFrom(n - 1);
  5. }
  6. }