What does 'yield' keyword do in flutter?
yield
adds a value to the output stream of the surrounding async*
function. It's like return
, but doesn't terminate the function.
See https://dart.dev/guides/language/language-tour#generators
Stream asynchronousNaturalsTo(n) async* {
int k = 0;
while (k < n) yield k++;
}
When the yield statement executes, it adds the result of evaluating its expression to the stream. It doesn’t necessarily suspend (though in the current implementations it does).
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.
async* sync* yield* yield
are called generator functions. You might use these mostly in Bloc pattern.async*
is also aasync
, you could use Asynchronous as usual.sync*
cannot be used assync
, you will receive the error that noticed "The modifier sync must be followed by a star".yield
andyield*
can only be used with generator functions (async*
sync*
).
And there are four combinations.
-
async* yield
will return aStream<dynamic>
.
Stream<int> runToMax(int n) async* {
int i = 0;
while (i < n) {
yield i;
i++;
await Future.delayed(Duration(seconds: 300));
}
}
-
async* yield*
will call a function and returnStream<dynamic>
.
Stream<int> countDownFrom(int n) async* {
if (n > 0) {
yield n;
yield* countDownFrom(n - 1);
}
}
-
sync* yield
will return aIterable<dynamic>
.
Iterable<int> genIterates(int max) sync* {
var i = 0;
while (i < max) {
yield i;
i++;
}
}
-
sync* yield*
will call a function and returnIterable<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.