Introduction

Dart Generator Functions are used to generate a sequence of values on-demand in a lazy manner. Such a value sequence can be generated either synchronously or asynchronously. There are two types of built-in generator functions available to support both scenarios:

  • Synchronous Generator: The synchronous generator function returns an Iterable object. That means the values are generated first and then returned lazily on-demand by the function.

Iterable: A collection of values or “elements”, that can be accessed sequentially.

  • Asynchronous Generator: The asynchronous generator function returns a Stream object. The sequence of values is generated on demand as each becomes available.

Stream: A source of asynchronous data events.

With the help of an example, we can understand generator functions. We will generate numbers starting from a given number, 5 in our case, until 0, using generator functions. We will observe both ways (asynchronous and synchronous generators) to create this number sequence.

Using sync* - synchronous generator

The function Iterable<int> countDownFromSync(int num) sync* takes a number as num, and sends out all numbers starting from num until 0. The synchronous generator function is marked with sync*. The values are returned using the yield keyword. The iterable sequence receives the number sequence and prints each number using a for loop. This number sequence is not generated until it has been accessed by the for loop.

sync* helps generate values in a synchronous manner. Note that the Starting... message is printed before for the loop’s execution. The DONE message is executed at end.

Get hands-on with 1200+ tech skills courses.