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
Parameter | Optional/Required | Description |
---|---|---|
action | required | the 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,
- We create a list named
numbers
containing the numbers1, 2, 3, 4, 5
. - We then use the
forEach()
method to apply a function that prints each number. - 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,
- We create a list named
characters
containing the characters'a', 'b', 'c', 'd', 'e'
. - We then use the
forEach()
method to apply a function that prints each character. - 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,
- We create a list named
strings
containing the strings'apple', 'banana', 'cherry'
. - We then use the
forEach()
method to apply a function that prints each string. - 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.