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
numberscontaining integers. - We then get an
Iteratorfor the list using theiteratorproperty. - We use a
whileloop 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
characterscontaining strings. - We then get an
Iteratorfor the set using theiteratorproperty. - We use a
whileloop 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
stringscontaining strings. - We then get an
Iteratorfor the iterable using theiteratorproperty. - We use a
whileloop 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.