Async Coding With Dart: Generators

MIB Coder
1 min readNov 10, 2019

--

What you are going to learn: What are Generators? How to implement a synchronous generator function? How to implement the asynchronous generator function?

Here is the latest version of this article, https://mibcoder.com

Generators in dart

What are Generators?

Generators can create sequence of values synchronously (by this we can create Iterable) and asynchronously (by this we can create Stream).

How to implement a synchronous generator function?

There are two thing to implement sync generator:

i- Mark function with “sync*” it defines function is generator and will return Iterable.

Iterable<int> createSyncGenerator(int n) sync* {
-----------
}

ii- Use “yeild” statement to deliver value

-------------
yield k++;
-------------

Here is example:

synchronous Generator

How to implement asynchronous generator function?

There are two thing to implement async generator:

i- Mark function with “async*” it defines function is generator and will return Stream.

Stream<int> createAsyncGenerator(int n) async* {
-------------------
}

ii- Use “yeild” statement to emit value in stream

-------------
yield k++;
-------------

Here is complete code:

asynchronous Generator

Thanks for reading, if you like please follow me.

--

--