For Each Loop in Dart
For Each Loop
The for each loop iterates over all list elements or variables. It is useful when you want to loop through list/collection. The syntax of for-each loop is:
collection.forEach(void f(value));
Example 1: Print Each Item Of List Using Foreach
This will print each name of football players.
void main(){
  List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];
  footballplayers.forEach( (names)=>print(names));
}
Run Online
Example 2: Print Each Total and Average Of Lists
This program will print the total sum of all numbers and also the average value from the total.
void main(){
  List<int> numbers = [1,2,3,4,5];
  
  int total = 0;
  
   numbers.forEach( (num)=>total= total+ num);
  
  print("Total is $total.");
  
  double avg = total / (numbers.length);
  
  print("Average is $avg.");
  
}
Run Online
For In Loop In Dart
There is also another for loop, i.e., for in loop. It also makes looping over the list very easily.
void main(){
    List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];
  for(String player in footballplayers){
    print(player);
  }
}
Run Online
How to Find Index Value Of List
In dart, asMap method converts the list to a map where the keys are the index and values are the element at the index.
void main(){
List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];
footballplayers.asMap().forEach((index, value) => print("$value index is $index"));
}
Run Online
Example 3: Print Unicode Value of Each Character of String
This will split the name into Unicode values and then find characters from the Unicode value.
void main(){
  
String name = "John";
     
for(var codePoint in name.runes){
  print("Unicode of ${String.fromCharCode(codePoint)} is $codePoint.");
}
}
Run Online
Video
Watch our video on for each loop in Dart.