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
Parameter | Optional/Required | Description |
---|---|---|
elements | required | An iterable collection of elements. |
action | required | A 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,
- We create a list of integers called
numbers
. - We use
Future.forEach
to perform a square operation on each number in the list. - 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,
- We create a list of strings called
words
. - We use
Future.forEach
to get the length of each word in the list. - 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.