In Dart, a generator is a unique function that allows the user to produce a value sequence easily. Generators return values on demand when we try to iterate over them. Dart provides two types of generator functions that can be used to generate a sequence of values:
iterable
object.stream
object.A synchronous generator returns an iterable
object (i.e., a collection of values or elements) that may be accessed sequentially. To create the synchronous generator function (s)
, declare the function body as sync*
and use the yield
keyword to generate values.
The following example shows how to implement a synchronous generator:
// sync* functions return an iterableIterable evenNo(int num) sync* {int x = num;while (x >= 0) {// Check for even numberif (x % 2 == 0) yield x;// Decrease variable xx--;}}// Main Functionvoid main(){print("Using Synchronous Generator");print("Even Numbers between 20:");// Print even numbersevenNo(20).forEach(print);}
A stream
object is returned by the asynchronous generator. stream
is a method of receiving a series of events. Each event is either a data event, also known as a stream
element, or an error event, which indicates that something has gone wrong.
To create an asynchronous generator function (s)
, declare the function body as async*
and use the yield
keyword to generate values.
The following example shows how to implement an asynchronous generator:
// async* function(s) return an streamStream asyncNo(int num) async* {int x = 10;while (x >= num) yield x--;}// Main Functionvoid main(){print("using Asynchronous Generator:");asyncNo(0).forEach(print);}