-
List
6-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
Lecture1.6
-
Traverse a List in Dart
In the previous lesson, we declared a List
, now we have to access each element from the list. there are many ways who achieved this we will be discussing only the most used of them.
forEach()
forEach()
extract items from the List
one by one and return item in function in forEach
, element extracted here are in sequential order
void main() { List<String> movies=["Avengers","IronMan","Harry Potter-I","Harry Potter-II"]; movies.forEach((movie){ print(movie); }); }
OUTPUT
Avengers IronMan Harry Potter-I Harry Potter-II
There is another sentence of forEach
:
void main() { List<String> movies=["Avengers","IronMan","Harry Potter-I","Harry Potter-II"]; for(String str in movies){ print(str); } }
OUTPUT
Avengers IronMan Harry Potter-I Harry Potter-II
for Loop
But sometimes you require items as well as index number also so for that we can use the basic for loop syntax
void main() { List<String> movies=["Avengers","IronMan","Harry Potter-I","Harry Potter-II"]; for(int i=0;i<movies.length;i++){ print("Index $i, Item= ${movies[i]}"); } }
OUTPUT
Index 0, Item= Avengers Index 1, Item= IronMan Index 2, Item= Harry Potter-I Index 3, Item= Harry Potter-II
0