Dart Tutorials

Dart List iterator
Syntax & Examples

Syntax of List.iterator

The syntax of List.iterator property is:

 Iterator<E> iterator 

This iterator property of List a new Iterator that allows iterating the elements of this Iterable.

Return Type

List.iterator returns value of type Iterator<E>.



✐ Examples

1 Iterate over a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We then get an Iterator for the list using the iterator property.
  3. We use a while loop with moveNext() to iterate over the list.
  4. Within the loop, we print each element using iter.current.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  Iterator<int> iter = numbers.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

1
2
3
4
5

2 Iterate over a set of characters

In this example,

  1. We create a set characters containing strings.
  2. We then get an Iterator for the set using the iterator property.
  3. We use a while loop with moveNext() to iterate over the set.
  4. Within the loop, we print each element using iter.current.

Dart Program

void main() {
  Set<String> characters = {'a', 'b', 'c'};
  Iterator<String> iter = characters.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

a
b
c

3 Iterate over an iterable of strings

In this example,

  1. We create an iterable strings containing strings.
  2. We then get an Iterator for the iterable using the iterator property.
  3. We use a while loop with moveNext() to iterate over the iterable.
  4. Within the loop, we print each element using iter.current.

Dart Program

void main() {
  Iterable<String> strings = ['apple', 'banana', 'cherry'];
  Iterator<String> iter = strings.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

Output

apple
banana
cherry

Summary

In this Dart tutorial, we learned about iterator property of List: the syntax and few working examples with output and detailed explanation for each example.