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,
- We create a list
numbers
containing integers. - We then get an
Iterator
for the list using theiterator
property. - We use a
while
loop withmoveNext()
to iterate over the list. - 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,
- We create a set
characters
containing strings. - We then get an
Iterator
for the set using theiterator
property. - We use a
while
loop withmoveNext()
to iterate over the set. - 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,
- We create an iterable
strings
containing strings. - We then get an
Iterator
for the iterable using theiterator
property. - We use a
while
loop withmoveNext()
to iterate over the iterable. - 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.