Dart Future.forEach()
Syntax & Examples

Future.forEach() static-method

The `forEach` static method in Dart performs an action for each element of an iterable, in turn.


Syntax of Future.forEach()

The syntax of Future.forEach() static-method is:

 Future forEach<T>(Iterable<T> elements, FutureOr action(T element)) 

This forEach() static-method of Future performs an action for each element of the iterable, in turn.

Parameters

ParameterOptional/RequiredDescription
elementsrequiredAn iterable collection of elements.
actionrequiredA function to be called for each element of the iterable.

Return Type

Future.forEach() returns value of type Future.



✐ Examples

1 Performing an action on integers

In this example,

  1. We create a list of integers called numbers.
  2. We use Future.forEach to perform a square operation on each number in the list.
  3. We print the squared value for each number.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  Future.forEach(numbers, (number) {
    print('Square of $number: ${number * number}');
  });
}

Output

Square of 1: 1
Square of 2: 4
Square of 3: 9
Square of 4: 16
Square of 5: 25

2 Performing an action on strings

In this example,

  1. We create a list of strings called words.
  2. We use Future.forEach to get the length of each word in the list.
  3. We print the length of each word.

Dart Program

void main() {
  List<String> words = ['Hello', 'World', 'Dart'];
  Future.forEach(words, (word) {
    print('Length of $word: ${word.length}');
  });
}

Output

Length of Hello: 5
Length of World: 5
Length of Dart: 4

Summary

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