Iterator class in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Iterator class in Dart is an interface that is used when we want to get items, one at a time, from an object.

The iterator is initially positioned before the first element. Before accessing the first element the iterator need to be advanced using the moveNext to point to the first element. If we reached the end of the object then moveNext returns false, and all further calls to moveNext will also return false.

It should be noted that if change anything in the object during the iteration, then the behaviour is unspecified.

We make use of the current property of the Iterator class when we want to get the current element of the object while iterating over it.

Let's take a look at an example where we have a list of different fruits, and we make use of the iterator to iterate over them one by one.

Example

Consider the example shown below −

 Live Demo

void main(){
   var fruits = ['apple','mango','banana'];
   var fruit = fruits.iterator;
   while(fruit.moveNext()){
      print(fruit.current);
   }
}

Output

apple
mango
banana

Iterator can also be used on maps, but since we can't iterate over the key-value pairs stored in the map. We will make use of the iterator over the keys object and the values object separately.

Example

Consider the example shown below −

 Live Demo

void main(){
   var map = new Map();
   map['apple'] = true;
   map['banana'] = true;
   map['kiwi'] = false;
   var valuesIterator = map.values.iterator;
   while(valuesIterator.moveNext()){
      print(valuesIterator.current);
   }

   var keysIterator = map.keys.iterator;
   while(keysIterator.moveNext()){
      print(keysIterator.current);
   }
}

Output

true
true
false
apple
banana
kiwi
raja
Published on 21-May-2021 13:00:52
Advertisements