FLUTTER INTERVIEW QUESTIONS

What are sync*, async*, yield and yield* in Dart?

Jelena Lecic
3 min readDec 31, 2019

--

Ok, we have already seen async keyword lots of times before, but what is this async with a star next to it? Or sync*?

To put it simply - Those are all keywords used in generator functions.

Generator functions produce sequence of values(in contrast to regular functions that return single value).

Generator functions can be:

  • Asynchronous (return a Stream of values)
  • Synchronous (return an Iterable with values)

Yield is a keyword that ‘returns’ single value to the sequence, but does not stop the generator function.

Interesting thing with generators is that they generate values on demand - meaning, values get generated when someone tries to iterate over the iterator, or starts to listen to the stream, not before.

Let’s see how sync* generator works:

void main() {
print('create iterator');
Iterable<int> numbers = getNumbers(3);
print('starting to iterate...');
for (int val in numbers) {
print('$val');
}
print('end of main');
}
Iterable<int> getNumbers(int number) sync* {
print('generator started');
for (int i = 0; i < number; i++) {
yield i;
}…

--

--

Responses (5)