Flutter/Dart How to: Different ways to iterate a list of elements
In Dart programming, a List is a growable collection of elements. It serves as a dynamic data structure allowing the addition, removal, and iteration of elements while preserving their insertion order.
This post presents various methods for iterating through a List of objects in Dart and Flutter programming.
Dart List Iteration Examples
There are multiple approaches to iterate through a List in Dart.
For Loop with Index
This is a fundamental for loop, commonly found in most programming languages. It initializes the index to 0
and iterates through each element until the condition list.length
is met.
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
The enhanced for-in loop simplifies iterating through 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
Using forEach Method
The forEach method offers a concise way to iterate through elements using a lambda function.
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
The while
loop provides an alternative method for iterating through elements using boolean expressions.
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
Conclusion
In Summary, These methods offer readability in iterating through lists in dart programming.