-
-
Save designervoid/1ab97f3ac11cc6ac831269e496bf54bf to your computer and use it in GitHub Desktop.
Iterator Example in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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