The `forEach` static method in Dart performs an action for each element of an iterable, in turn.
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.
Parameter | Optional/Required | Description |
---|---|---|
elements | required | An iterable collection of elements. |
action | required | A function to be called for each element of the iterable. |
Future.forEach() returns value of type Future
.
In this example,
numbers
.Future.forEach
to perform a square operation on each number in the list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Future.forEach(numbers, (number) {
print('Square of $number: ${number * number}');
});
}
Square of 1: 1 Square of 2: 4 Square of 3: 9 Square of 4: 16 Square of 5: 25
In this example,
words
.Future.forEach
to get the length of each word in the list.void main() {
List<String> words = ['Hello', 'World', 'Dart'];
Future.forEach(words, (word) {
print('Length of $word: ${word.length}');
});
}
Length of Hello: 5 Length of World: 5 Length of Dart: 4
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.