
List in a dart programming is the growable list of elements.
It is a data structure, that adds, removes, and iterates the list of elements in the insertion order.
This post shows you multiple ways of iterating a list of objects in Dart and flutter programming.
Dart List Iteration examples
There are multiple ways to iterate a List in Dart.
For loop with index
This is a basic normal for loop, which every programming language provides. It assigns index=0 and iterates each element until the list.length condition is met.
Here is an example
void main() {
List<String> words = ["one", "two", "three"];
print(words);
for (int i = 0; i < words.length; i++) {
print(words[i]);
}
}
Output:
[one, two, three]
one
two
three
Enhanced for-in loop
It is enhanced for in loop to iterate the list of objects and elements.
void main() {
List<String> words = ["one", "two", "three"];
print(words);
for (final word in words) {
print(word);
}
}
Output:
[one, two, three]
one
two
three
forEach list dart example
forEach is a dart way of iteration using the new syntax.
Syntax:
void forEach(void Function(String) action)
Iterates each element and executes a function with each element.
void main() {
List<String> words = ["one", "two", "three"];
print(words);
words.forEach((item) {
print(item);
});
}
While looping in dart
while loop is another way to iterate then the loop of elements using boolean expressions.
Here is an example.
void main() {
List<String> words = ["one", "two", "three"];
print(words);
var k = 0;
while (k < words.length) {
print(words[k]);
k++;
}
}
Output:
[one, two, three]
one
two
three