Dart – How to loop/iterate a list

Let’s go through some different approaches to loop/iterate a list in Dart:

void main() {
  List<String> countries = ['Vietnam', 'Singapore', 'Thailand'];

  print('1. Loop a list using forEach:');
  countries.forEach((country) {
    print(country);
  });

  print('\n***********\n');

  print('2. Loop a list using for:');
  for (String country in countries) {
    print(country);
  }

  print('\n***********\n');

  print('3. Loop a list using list length, element index:');
  for (int i = 0; i < countries.length; i++) {
    print(countries[i]);
  }

  print('\n***********\n');

  print('4. Loop a list using while and list length:');
  int index = 0;
  while(index < countries.length) {
    print(countries[index]);
    index++;
  }

  print('\n***********\n');

  print('5. Loop a list using while and iterator:');
  Iterator it = countries.iterator;
  while(it.moveNext()) {
    print(it.current);
  }

  print('\n***********\n');

  print('6. Loop a list using map:');
  countries.asMap().forEach((key, value) {
    print('key = $key ---> value = $value');
  });
}

Output:

1. Loop a list using forEach:
Vietnam
Singapore
Thailand

***********

2. Loop a list using for:
Vietnam
Singapore
Thailand

***********

3. Loop a list using list length, element index:
Vietnam
Singapore
Thailand

***********

4. Loop a list using while and list length:
Vietnam
Singapore
Thailand

***********

5. Loop a list using while and iterator:
Vietnam
Singapore
Thailand

***********

6. Loop a list using map:
key = 0 ---> value = Vietnam
key = 1 ---> value = Singapore
key = 2 ---> value = Thailand
Tagged : / / / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Gürkan Şahin
Gürkan Şahin
4 days ago

Hi! 🙂
Thanks a lot for this good work!

2
0
Would love your thoughts, please comment.x
()
x