Dart Map class forEach method examples

As a brief note to self, here’s an example of the forEach method on a Dart Map class. First, a sample Dart Map:

final states = {
    'AK' : 'Alaska',
    'AL' : 'Alabama', 
    'AR' : 'Arizona'
};

Then the Dart Map class forEach method, specifying its keys and values in the anonymous function:

states.forEach((k,v) {
    print('The abbreviation $k stands for $v.');
});

Also, here’s a single-line syntax version of that example:

states.forEach((k,v) => print('The abbreviation $k stands for $v.'));

If you needed to see some examples of the the Dart Map class forEach method syntax, I hope these are helpful.

Bonus: More Map class syntax

As a little bonus, you can also declare that Map like this, specifying the types in the Map:

final Map<String, String> states = {
    'AK' : 'Alaska',
    'AL' : 'Alabama', 
    'AR' : 'Arizona'
};

In some cases it helps to be more explicit about types, so I thought I’d include that example as well.

Here’s another Map approach you can use, first specifying the types when creating the Map, and then adding key/value pairs to the Map:

var states = new Map<String, String>();

states['AK'] = 'Alaska';
states['AL'] = 'Alabama';
states['AR'] = 'Arizona';

Again, I hope all of these Dart Map examples are helpful.