.forEach()
Anonymous contributor
Published May 3, 2024
Contribute to Docs
The .forEach()
method in Dart serves as a mechanism for iterating through elements within iterable collections like lists, maps, or sets. This method executes a specified function on each element of the collection.
Syntax
collection.forEach((element) {
// Code to be executed for each element on the collection
});
collection
: The list, map, or set to iterate over.element
: A variable representing the current element on each iteration.
Example
In the example below, a list of numbers is declared. Each number is multiplied by 2 and printed utilizing the .forEach
method:
void main() {List<int> numbers = [1, 2, 3, 4, 5];numbers.forEach((number) {print(number * 2);});}
The above code returns the following output:
246810
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.