What does 'yield' keyword do in flutter?

Newaj picture Newaj · Apr 20, 2019 · Viewed 25k times · Source

What does the yield keyword actually do in Dart?

Answer

Tokenyet picture Tokenyet · May 16, 2019

The accepted answer's link is broken, here is an official link about async* sync* yield* yield.

If you have some experiences with other languages, you might stuck at these keywords. Here are some tips for getting over keywords.

  1. async* sync* yield* yield are called generator functions. You might use these mostly in Bloc pattern.

  2. async* is also a async, you could use Asynchronous as usual.

  3. sync* cannot be used as sync, you will receive the error that noticed "The modifier sync must be followed by a star".

  4. yield and yield* can only be used with generator functions (async* sync*).

And there are four combinations.

  1. async* yield will return a Stream<dynamic>.
Stream<int> runToMax(int n) async* {
  int i = 0;
  while (i < n) {
    yield i;
    i++;
    await Future.delayed(Duration(seconds: 300));
  }
}
  1. async* yield* will call a function and return Stream<dynamic>.
Stream<int> countDownFrom(int n) async* {
  if (n > 0) {
    yield n;
    yield* countDownFrom(n - 1);
  }
}
  1. sync* yield will return a Iterable<dynamic>.
Iterable<int> genIterates(int max) sync* {
  var i = 0;
  while (i < max) {
    yield i;
    i++;
  }
}
  1. sync* yield* will call a function and return Iterable<dynamic>.
Iterable<int> countDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* countDownFrom(n - 1);
  }
}

If there are any errors, please leave a comment to correct the answer.