Generators
Prerequisite: Iteration, Iterator , Iterable
void main(){
List<int> myList = [1,2,4,5,7];
for(int i in myList){
print(i);
}
}void main(){
Set<int> mySet = {1,2,4,5,7};
for(int i in mySet){
print(i);
}
}void main(){
// Example with Map
Map<int,String> myIterable ={
1:"Apple",
2:"Orange",
3:"Banana"
};
for(var i in myIterable.keys){
print(i);
}
for(var i in myIterable.values){
print(i);
}
}In simple words , iterable is something you can loop over or a collection of values that can be accessed sequentially
Iterator is something that remember can "where it is " i.e. current position during iteration

Documentation
Sync Generators
There are two types of Generators in Dart
Synchronous Generator
Returns an iterableAsynchronous Generator
Returns a stream
In a normal function you would expect the function body to execute when you call the function , but in case of generator it doesn't execute
void main() {
print("Start of main");
Iterable<int> numbers = getNumbers(6);
print("End of main ");
}
Iterable<int> getNumbers(int number) sync* {
print("Number Generation Started");
for (int i = 0; i < 0; i++) {
yield i;
}
print("Number Generation ended");
}
The generator starts executing when you start iterating over iterable it returned
void main() {
print("Start of main");
Iterable<int> numbers = getNumbers(6);
for (var i in numbers) {
print(i);
}
print("End of main ");
}
Iterable<int> getNumbers(int number) sync* {
print("Number Generation Started");
for (int i = 0; i < number; i++) {
yield i;
}
print("Number Generation ended");
}
Async Generators
Last updated
Was this helpful?