Here are a couple of simple Dart maps, created using map literals:
Note: Dart infers that has the type Map<String, String>
and nobleGases
has the type Map<int, String>
. If you try to add the wrong type of value to either map, the analyzer or runtime raises an error. For more information, read about
You can create the same objects using a Map constructor:
var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
var nobleGases = Map();
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';
Add a new key-value pair to an existing map just as you would inJavaScript:
Retrieve a value from a map the same way you would in JavaScript:
assert(gifts['first'] == 'partridge');
If you look for a key that isn’t in a map, you get a null in return:
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);
To create a map that’s a compile-time constant,add const
before the map literal:
As of Dart 2.3, maps support spread operators (…
and )and collection if and for, just like lists do.For details and examples, see thespread operator proposal and the
For more information about maps, seeGenerics and.