Skip to content

Instantly share code, notes, and snippets.

@designervoid
Forked from thatisuday/fruits-iterator.dart
Created April 14, 2021 13:11
Show Gist options
  • Save designervoid/1ab97f3ac11cc6ac831269e496bf54bf to your computer and use it in GitHub Desktop.
Save designervoid/1ab97f3ac11cc6ac831269e496bf54bf to your computer and use it in GitHub Desktop.
Iterator Example in Dart
// A `Fruit` object contains `name` and `color`
class Fruit {
final String name;
final String color;
Fruit( this.name, this.color );
}
// A `Fruits` collection contains the List of `Fruit` object
// `iterator` getter returns an instance of `FruitsIterator` instance
class Fruits {
List<Fruit> fruits = [];
Fruits( this.fruits );
FruitsIterator get iterator {
return FruitsIterator( this.fruits );
}
}
// `FruitsIterator` walks through a List of `Fruit` object
// and returns `String` values, hence it must extend `Iterator<String>` class
class FruitsIterator extends Iterator<String> {
List<Fruit> fruits = [];
String _current;
int index = 0;
FruitsIterator( this.fruits );
// `oveNext`method must return boolean value to state if next value is available
bool moveNext() {
if( index == fruits.length ) {
_current = null;
return false;
} else {
_current = fruits[ index++ ].name;
return true;
}
}
// `current` getter method returns the current value of the iteration when `moveNext` is called
String get current => _current;
}
void main() {
// create `Fruits` from a List of `Fruit` objects
var fruits = Fruits([
Fruit( 'Banana', 'Green' ),
Fruit( 'Mango', 'Yellow' ),
Fruit( 'Apple', 'Red' )
]);
// get an iterator from Fruits object
var iterator = fruits.iterator;
// walk through iterator using `moveNext()` method and `current` getter
while( iterator.moveNext() ) {
print( 'Fruit name: ${ iterator.current }' );
}
// Result:
// Fruit name: Banana
// Fruit name: Mango
// Fruit name: Apple
// Iterator Doc: https://api.dartlang.org/stable/2.6.1/dart-core/Iterator-class.html
// Iterable Doc: https://api.dartlang.org/stable/2.6.1/dart-core/Iterable-class.html
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment