Dart Tutorials

Dart List forEach()
Syntax & Examples

Syntax of List.forEach()

The syntax of List.forEach() method is:

 void forEach(void action(E element)) 

This forEach() method of List invokes action on each element of this iterable in iteration order.

Parameters

ParameterOptional/RequiredDescription
actionrequiredthe function to be applied to each element of the iterable

Return Type

List.forEach() returns value of type void.



✐ Examples

1 Print each number

In this example,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the forEach() method to apply a function that prints each number.
  3. Each number is printed to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  numbers.forEach((number) => print(number)); // Output: 1 2 3 4 5
}

Output

1
2
3
4
5

2 Print each character

In this example,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd', 'e'.
  2. We then use the forEach() method to apply a function that prints each character.
  3. Each character is printed to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  characters.forEach((char) => print(char)); // Output: a b c d e
}

Output

a
b
c
d
e

3 Print each string

In this example,

  1. We create a list named strings containing the strings 'apple', 'banana', 'cherry'.
  2. We then use the forEach() method to apply a function that prints each string.
  3. Each string is printed to standard output.

Dart Program

void main() {
  List<String> strings = ['apple', 'banana', 'cherry'];
  strings.forEach((str) => print(str)); // Output: apple banana cherry
}

Output

apple
banana
cherry

Summary

In this Dart tutorial, we learned about forEach() method of List: the syntax and few working examples with output and detailed explanation for each example.