Maps

In general, a map is an object that associates keys and values. Bothkeys and values can be any type of object. Each key occurs only once,but you can use the same value multiple times. Dart support for mapsis provided by map literals and the Map type.

Here are a couple of simple Dart maps, created using map literals:

  1. var gifts = {
  2. // Key: Value
  3. 'first': 'partridge',
  4. 'second': 'turtledoves',
  5. 'fifth': 'golden rings'
  6. };
  7. var nobleGases = {
  8. 2: 'helium',
  9. 10: 'neon',
  10. 18: 'argon',
  11. };

Note: Dart infers that gifts 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 type inference.

You can create the same objects using a Map constructor:

  1. var gifts = Map();
  2. gifts['first'] = 'partridge';
  3. gifts['second'] = 'turtledoves';
  4. gifts['fifth'] = 'golden rings';
  5. var nobleGases = Map();
  6. nobleGases[2] = 'helium';
  7. nobleGases[10] = 'neon';
  8. nobleGases[18] = 'argon';

Note: You might expect to see new Map() instead of just Map(). As of Dart 2, the new keyword is optional. For details, see Using constructors.

Add a new key-value pair to an existing map just as you would inJavaScript:

  1. var gifts = {'first': 'partridge'};
  2. gifts['fourth'] = 'calling birds'; // Add a key-value pair

Retrieve a value from a map the same way you would in JavaScript:

  1. var gifts = {'first': 'partridge'};
  2. assert(gifts['first'] == 'partridge');

If you look for a key that isn’t in a map, you get a null in return:

  1. var gifts = {'first': 'partridge'};
  2. assert(gifts['fifth'] == null);

Use .length to get the number of key-value pairs in the map:

  1. var gifts = {'first': 'partridge'};
  2. gifts['fourth'] = 'calling birds';
  3. assert(gifts.length == 2);

To create a map that’s a compile-time constant,add const before the map literal:

  1. final constantMap = const {
  2. 2: 'helium',
  3. 10: 'neon',
  4. 18: 'argon',
  5. };
  6. // constantMap[2] = 'Helium'; // Uncommenting this causes an error.

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 thecontrol flow collections proposal.

For more information about maps, seeGenerics andMaps.