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.
Parameter | Optional/Required | Description |
---|---|---|
action | required | the function to be applied to each element of the iterable |
List.forEach() returns value of type void
.
In this example,
numbers
containing the numbers 1, 2, 3, 4, 5
.forEach()
method to apply a function that prints each number.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => print(number)); // Output: 1 2 3 4 5
}
1 2 3 4 5
In this example,
characters
containing the characters 'a', 'b', 'c', 'd', 'e'
.forEach()
method to apply a function that prints each character.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
characters.forEach((char) => print(char)); // Output: a b c d e
}
a b c d e
In this example,
strings
containing the strings 'apple', 'banana', 'cherry'
.forEach()
method to apply a function that prints each string.void main() {
List<String> strings = ['apple', 'banana', 'cherry'];
strings.forEach((str) => print(str)); // Output: apple banana cherry
}
apple banana cherry
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.