What are generators in Dart?

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:

  1. Synchronous generator: Returns an iterable object.
  2. Asynchronous generator: Returns a stream object.

Synchronous generator

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 iterable
Iterable evenNo(int num) sync* {
int x = num;
while (x >= 0) {
// Check for even number
if (x % 2 == 0) yield x;
// Decrease variable x
x--;
}
}
// Main Function
void main(){
print("Using Synchronous Generator");
print("Even Numbers between 20:");
// Print even numbers
evenNo(20).forEach(print);
}

Asynchronous generator

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 stream
Stream asyncNo(int num) async* {
int x = 10;
while (x >= num) yield x--;
}
// Main Function
void main(){
print("using Asynchronous Generator:");
asyncNo(0).forEach(print);
}

Free Resources