Map forEach()
Map forEach()
method applies given action to each key-value pair of this Map.
Syntax
The syntax to perform an action for each key-value pair of the Map map1
is
map1.forEach(action); //or map1.forEach((key, value) { //code });
where action
is a function that takes key
, value
as arguments.
The method returns void
.
ADVERTISEMENT
Examples
Print each of the key-value pair in Map
In the following Dart Program, we take a Map fruits
, and print each key-value pair of the Map fruits
, using Map.forEach()
method.
main.dart
void main() { var fruits = {'apple': 25, 'banana': 10, 'cherry': 6}; fruits.forEach((key, value) { print('$key : $value'); }); }
Output
apple : 25 banana : 10 cherry : 6
Passing function to Map.forEach()
In the following Dart Program, we define a function printKeyValue()
that takes key, value of this Map as arguments. We pass this function printKeyValue
as argument to forEach().
main.dart
void printKeyValue(key, value) { print('$key : $value'); } void main() { var fruits = {'apple': 25, 'banana': 10, 'cherry': 6}; fruits.forEach(printKeyValue); }
Output
apple : 25 banana : 10 cherry : 6
Conclusion
In this Dart Tutorial, we learned how to execute a function or action for each key-value pair of this Map, using Map.forEach()
method.