'yield'关键字在颤动中起什么作用?

N.K*_*K.T 12 dart flutter

Dart中实际上有什么yield关键字?想得到一个解释。

Jac*_*ips 22

yield向周围async*函数的输出流添加一个值。就像return,但不会终止函数。

参见https://dart.dev/guides/language/language-tour#generators

Stream asynchronousNaturalsTo(n) async* {
  int k = 0;
  while (k < n) yield k++;
}
Run Code Online (Sandbox Code Playgroud)

执行yield语句时,它将对表达式的求值结果添加到流中。它不一定挂起(尽管在当前的实现中会挂起)。

  • “这就像 return,但不会终止函数。”这是一个多么完美的方式来解释这一点,而不需要深入讨论......谢谢。也就是说,如果你想深入了解这个话题,Tokenyet 下面有一个很好的答案。 (28认同)

Tok*_*yet 20

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));
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. async* yield*将调用一个函数并返回Stream<dynamic>
Stream<int> countDownFrom(int n) async* {
  if (n > 0) {
    yield n;
    yield* countDownFrom(n - 1);
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. sync* yield 将返回一个Iterable<dynamic>
Iterable<int> genIterates(int max) sync* {
  var i = 0;
  while (i < max) {
    yield i;
    i++;
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. sync* yield*将调用一个函数并返回Iterable<dynamic>
Iterable<int> countDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* countDownFrom(n - 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有任何错误,请发表评论以更正答案。

  • @mirkancal这是一个如此清晰的解释,它应该进入答案,而不仅仅是评论。 (4认同)
  • 我认为yield *的正确答案是委托给另一个生成器,而不是调用一个函数。yield *简单地委派给另一台发电机,这意味着当前的发电机停止运行,另一台发电机接管工作直到停止生产。此后,停止生成值,主生成器将继续生成自己的值。 (3认同)

mir*_*cal 17

我认为yield*的正确答案是委托给另一个生成器而不是调用函数。Yield* 只是委托给另一个生成器,这意味着当前生成器停止,另一个生成器接管工作,直到它停止生产。在停止生成值之后,主生成器将恢复生成自己的值。

\n

感谢@Andr\xc3\xa1s Szepesh\xc3\xa1zi 鼓励我发表此评论作为答案,希望它有所帮助。

\n