Skip to content

Instantly share code, notes, and snippets.

@thatisuday
Created November 29, 2019 16:51
Show Gist options
  • Save thatisuday/c98b2d4cf7ddb9dd693db8e15f9d7620 to your computer and use it in GitHub Desktop.
Save thatisuday/c98b2d4cf7ddb9dd693db8e15f9d7620 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