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
| Parameter | Optional/Required | Description |
|---|---|---|
f | required | The 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,
- We create a list
numberscontaining integers. - We use the
forEach()method with a function that prints each element. - 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,
- We create a list
wordscontaining strings. - We use the
forEach()method with a function that prints the uppercase version of each word. - 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,
- We create a set
uniqueNumberscontaining integers. - We use the
forEach()method with a function that prints each number multiplied by 2. - 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.