Skip to main content

Map

The Map is a type of collection that stores items in "key-value" pairs, and you can access the values by their key.

There are three types of Maps:

note

In this article, we will learn about Map in general and not dive into details of each type of Map.

In the following code, we have the color name as key and their value in hexadecimal as value:

final colorHex = {
// key: value
'white': '#FFFFFF',
'blue': '#0000FF',
'red': '#FF0000',
};

print(colorHex['white']); // prints #FFFFFF
print(colorHex['blue']); // prints #0000FF
print(colorHex['red']); // prints #FF0000

Dart is smart enough to infer the type of the key is String and the type of the value is String. So Dart infers the map type is <String, String>.

To access the value, we use the key. For example, to print the value of #FFFFFF, we must access it by the key 'white' like this: colorHex['white'].

We can also create maps with different types of key-values for example, <int, String> or <String, boolean>:

// Dart infer the type is <int, string>
final daysOfTheWeek = {
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday',
};

Create a Map

There are a few ways to create maps in Dart. If you want an empty map:

// May cause a type warning. What type of **key-value** will we add?
final emptyMap = {};

// Specifying the type
final emptyMap = <int, String>{};

// Specifying the type
Map<int, String> emptyMap = {};

Useful properties and functions

  • To get the number of elements in the map:
colorHex.length;
  • To check if the map is empty, we can check if the size equals zero, colorHex.length == 0, or we can use isEmpty
colorHex.isEmpty;
  • To check if the list contains a key:
colorHex.containsKey('white');
  • To add more elements to the map:
colorHex['green'] = '00FF00';
  • To change the value of a given key:
colorHex['green']= 'Some random string';
  • To delete all elements of the map:
colorHex.clear()

Let's run the following example in DartPad: