For Each
In the following Dart Program, we apply forEach method for a list, a set and a map.
- List:
- Set:
- Map
void main() {
var nums = [1, 2, 3, 4, 5, 6, 7];
nums.forEach((element) {
element *= 11;
print(element);
});
print(nums);
}
22
33
44
55
66
77
[1, 2, 3, 4, 5, 6, 7]
void main() {
var eng = {"one", "two", "three", "four", "five"};
var fr = ["un", "deux", "trois", "quatre", "cinq"];
var engAndFr = eng;
var index = 0;
engAndFr.forEach((element) {
element = element + " " + fr[index];
index++;
print(element);
});
print(engAndFr);
}
two deux
three trois
four quatre
five cinq
{one, two, three, four, five}
void main() {
String carDescription = "My car is";
var car = {
"model": "R8",
"Horsepower": "602",
"Energy": "Gasoline",
"transmission": "automatic"
};
car.forEach((key, value) {
carDescription += " " + value;
});
print(carDescription);
}
You may ask a questio here : Why forEach is unable to modify the elements of the list and the set ?
The element parameter of the forEach callback is just a normal local variable, and assigning to it has no effect outside the callback.
Why ?
Dart does not have variable references, all elements are passed as a reference to an object, not to a variable. (In other words, Dart is purely "call-by-sharing" like both Java and JavaScript).
The same goes for iterators: they return the value in the iterable, but it has no reference back to the iterable after that.
Source