.forEach()

Anonymous contributor's avatar
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:

2
4
6
8
10

All contributors

Contribute to Docs

Learn Dart on Codecademy