Introduction
In Flutter/Dart, we may wish to iterate over List. In this post, we'll learn how to do it.
Check the following articles if you are looking for more information about how to: filter, sort, reverse, update, and create a List in Flutter/Dart.
How to iterate over List in Flutter
To iterate over a list in Flutter we can use forEach()
, every()
, for loop with the index, or a simple for-each loop.
Iterate over a list using forEach()
method and lambda expression
var list = ['zero', 'one', 'two', 'three'];
list.forEach((listItem) => print(listItem));
Iterate over a list using iterator
var list = ['zero', 'one', 'two', 'three'];
var iter = list.iterator; // get the iterator
while (iter.moveNext()) { // while there is next element
print(iter.current);
}
Iterate over a list using every()
method
var list = ['zero', 'one', 'two', 'three'];
list.every((item) { // print every item in a list
print(item);
return true;
});
Iterate over a list using a simple loop
var list = ['zero', 'one', 'two', 'three'];
for (var item in list) {
print(item);
}
Iterate over a list using a loop with an item index
var list = ['zero', 'one', 'two', 'three'];
for (var i = 0; i < list.length; i++) {
print(list[i]); // print element at a specific index
}
Conclusion
In this article, we presented several ways to iterate over a list in Flutter/Dart.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}