In this tutorial you will learn about the Dart Generators and its application with practical example.
Dart Generators
Generator is function allows you to lazily produce a sequence of values. Dart comes with built-in support for two type of generator functions –
Synchronous generator:- It returns an Iterable object, which delivers values synchronously. A synchronous generator function can be implemented by marking the function body as sync* along with a yield statements to generate values.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
main() { print("W3Adda - Dart Synchronous Generator Example."); evenNumbersDownFrom(5).forEach(print); } // sync* functions return an iterable Iterable<int> evenNumbersDownFrom(int n) sync* { int k = n; while (k >= 0) { if (k % 2 == 0) { // 'yield' suspends the function yield k; } k--; } } |
Output:-
Asynchronous generator:- It returns a Stream object, which delivers values asynchronously. An asynchronous generator function can be implemented by marking the function body as async*, and use yield statements to generate values.
Example:-
1 2 3 4 5 6 7 8 9 10 |
main() { print("W3Adda - Dart Asynchronous Generator Example."); asyncNaturalsTo(5).forEach(print); } // sync* functions return an stream Stream<int> asyncNaturalsTo(int n) async* { int k = 0; while (k < n) yield k++; } |
Output:-