{

Flutter/Dart How to: Different ways to iterate a list of elements


List in a dart programming is the growable list of elements. Different ways to iterate and loop a list in Dart and Flutter

It is a data structure, that adds, removes and iterates the list of elements in the insertion order.

This post shows you multiple ways of iterating a list of objects in Dart and flutter programming.

Dart List Iteration examples

There are multiple ways to iterate a List in Dart.

For loop with index

This is a basic normal for loop, which every programming language provides. It assigns index=0 and iterates each element until the list.length condition is met.

Here is an 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

It is enhanced for in loop to iterate 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

forEach list dart example

forEach is a dart way of iteration using the new syntax.

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 loop in dart

while loop is another way to iterate then the loop of elements using boolean expressions.

Here is an example.

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example