Dart Runes forEach()
Syntax & Examples

Runes.forEach() method

The `forEach` method in Dart applies the function f to each element of this collection in iteration order.


Syntax of Runes.forEach()

The syntax of Runes.forEach() method is:

 void forEach(void f(int element)) 

This forEach() method of Runes applies the function f to each element of this collection in iteration order.

Parameters

ParameterOptional/RequiredDescription
frequiredThe function to apply to each element, taking an integer element as its argument.

Return Type

Runes.forEach() returns value of type void.



✐ Examples

1 Applying a function to each element in a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We use the forEach() method with a function that prints each element.
  3. The function applied is printing each element of the list.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3];
  numbers.forEach((element) => print(element));
}

Output

1
2
3

2 Applying a function to each element in a list of strings

In this example,

  1. We create a list words containing strings.
  2. We use the forEach() method with a function that prints the uppercase version of each word.
  3. The function applied is printing each word in uppercase.

Dart Program

void main() {
  List<String> words = ['hello', 'world'];
  words.forEach((word) => print(word.toUpperCase()));
}

Output

HELLO
WORLD

3 Applying a function to each element in a set of numbers

In this example,

  1. We create a set uniqueNumbers containing integers.
  2. We use the forEach() method with a function that prints each number multiplied by 2.
  3. The function applied is printing each number in the set multiplied by 2.

Dart Program

void main() {
  Set<int> uniqueNumbers = {1, 2, 3};
  uniqueNumbers.forEach((number) => print(number * 2));
}

Output

2
4
6

Summary

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