Dart List forEach()

Dart List forEach() method is used to iterate over the elements of a list and execute a block of code for each element.

Syntax

The syntax to call forEach() method on the List list is

list.forEach((element)=>{
  //code
})

During each iteration, forEach() receives the respective element as argument.

ADVERTISEMENT

Example

In this example, we take a list of integers, iterate over the numbers using forEach(), and print them.

main.dart

void main() {
  var list = [2, 4, 8, 16, 32];
  list.forEach((n) => {print('$n')});
}

Output

2
4
8
16
32

Execute a Function for each Element

We can call a function inside forEach() block, and execute a function for each element in the list.

In the following example, we call isEvenOdd() function for each element in the list.

main.dart

void main() {
  var list = [2, 5, 7, 16, 32];
  list.forEach((n) => {isEvenOdd(n)});
}

void isEvenOdd(int n) {
  if (n % 2 == 0) {
    print('$n is even number.');
  } else {
    print('$n is odd number.');
  }
}

Output

2 is even number.
5 is odd number.
7 is odd number.
16 is even number.
32 is even number.

Conclusion

In this Dart Tutorial, we learned how to use forEach() method to iterate over List elements, with examples.