ZetCode

Dart Map

last modified January 28, 2024

Dart Map tutorial shows how to work with a map collection in Dart language.

A map is a collection of key/value pairs. The value is retrieved from a map with its associated key. Maps are also called dictionaries, associative arrays, or hash tables.

Depending on the iteration order, there are three types of maps in Dart:

By default, creating an instance using Map constructor (Map, Map.from, or Map.of) creates a LinkedHashMap.

A map is created with a map literal or with a map constructor. To work with maps, we import the dart:collection library.

Dart Map literal

A map literal consists of a pair of curly brackes, in which we specify the key/value pairs. The pairs are separated by comma. The key is separated from the value by colon.

main.dart
void main() {
  var data = {'name': 'John Doe', 'occupation': 'gardener'};
  print(data);

  print(data.runtimeType);

  var words = <int, String>{1: 'sky', 2: 'falcon', 3: 'rock'};
  print(words);

  print(words.runtimeType);
}

In the example, we create two maps with map literals.

var data = {'name': 'John Doe', 'occupation': 'gardener'};

Here we have a simple map with two pairs. The 'name' and 'occupation' are keys, the 'John Doe' and 'gardener' are values.

var words = <int, String>{1: 'sky', 2: 'falcon', 3: 'rock'};

In the second map, we also specify the data types for the keys and values. The data types precede the curly brackets.

$ dart main.dart
{name: John Doe, occupation: gardener}
_InternalLinkedHashMap<String, String>
{1: sky, 2: falcon, 3: rock}
_InternalLinkedHashMap<int, String>

Dart Map size

With the length property, we can determine the size of the map.

main.dart
void main() {
  var fruit = {1: 'Apple', 2: 'Orange'};
  print(fruit.length);

  print('There are ${fruit.length} elements in the map');
}

The example creates a simple map collection and prints its size.

$ dart main.dart
2
There are 2 elements in the map

Dart empty map

With isEmpty and isNotEmpty, we can determine whether the map is empty or not empty.

main.dart
void main() {
  var words = {
    1: 'sky',
    2: 'fly',
    3: 'ribbon',
    4: 'falcon',
    5: 'rock',
    6: 'ocean',
    7: 'cloud'
  };

  print(words.isEmpty);
  print(words.isNotEmpty);

  print('---------------');
  words.clear();

  print(words.isEmpty);
  print(words.isNotEmpty);
}

In the example, we use the isEmpty and isNotEmpty methods.

$ dart main.dart
false
true
---------------
true
false

Dart add pair

A new pair can be added to a map with the assignment operator or the putIfAbsent method. The putIfAbsent adds a new value if it is not in the map. It returns the existing or the new value.

main.dart
void main() {
  var fruit = {1: 'Apple', 2: 'Orange'};

  fruit[3] = 'Banana';
  print(fruit);

  var val = fruit.putIfAbsent(3, () => 'Mango');
  print(fruit);
  print(val);

  var val2 = fruit.putIfAbsent(4, () => 'Cherry');
  print(fruit);
  print(val2);
}

We add new pairs to the map in the example.

fruit[3] = 'Banana';

We add a new pair 3: 'Banana'.

var val = fruit.putIfAbsent(3, () => 'Mango');

Since there is already a pair with key 3, the new pair is not added to the map. The method returns Banana.

var val2 = fruit.putIfAbsent(4, () => 'Cherry');

The 4: 'Cherry' pair is added to the map. The method returns Cherry.

$ dart main.dart
{1: Apple, 2: Orange, 3: Banana}
{1: Apple, 2: Orange, 3: Banana}
Banana
{1: Apple, 2: Orange, 3: Banana, 4: Cherry}
Cherry

Dart map removing pairs

We can remove pairs from the map with remove, removeWhere, or clear.

main.dart
void main() {
  var words = {
    1: 'sky',
    2: 'fly',
    3: 'ribbon',
    4: 'falcon',
    5: 'rock',
    6: 'ocean',
    7: 'cloud'
  };

  words.remove(1);
  print(words);

  words.removeWhere((key, value) => value.startsWith('f'));
  print(words);

  words.clear();
  print(words);
}

The example removes pairs from the map of words.

words.remove(1);

With remove, we delete the pair having key 1.

words.removeWhere((key, value) => value.startsWith('f'));

The removeWhere deletes all pairs whose values (words) begin with letter f.

words.clear();

The clear method removes all pairs from the map.

$ dart main.dart
{2: fly, 3: ribbon, 4: falcon, 5: rock, 6: ocean, 7: cloud}
{3: ribbon, 5: rock, 6: ocean, 7: cloud}
{}

Dart Map fromIterables

The fromIterables method creates a new map from the provided iterables.

main.dart
void main() {
  var letters = ['I', 'II', 'V', 'X', 'L'];
  var numbers = [1, 2, 5, 10, 50];

  var data = Map<String, int>.fromIterables(letters, numbers);
  print(data);
}

In the example, we create a map from two lists.

$ dart main.dart
{I: 1, II: 2, V: 5, X: 10, L: 50}

Dart Map collection if & for forms

With the collection if and for forms, we can dynamically create maps in Dart. The syntax is close to list comprehensions known from Haskell or Python.

main.dart
void main() {
  var words = ['sky', 'cloud', 'sod', 'worm', 'put', 'water', 'cup'];

  var i = 0;
  var data = {
    for (var e in words)
      if (e.length == 3) i++: e
  };

  print(data);
}

The example creates a map with a collection if/for form. We create a map from a list of words, where we include only words that have three characters. To each word, we assign a numeric key.

$ dart main.dart
{0: sky, 1: sod, 2: put, 3: cup}

Dart merge maps

We can merge maps with the addAll method or the spread (...) operator.

main.dart
void main() {
  var f1 = {1: 'Apple', 2: 'Orange'};
  var f2 = {3: 'Banana'};
  var f3 = {4: 'Mango'};

  var fruit = {}..addAll(f1)..addAll(f2)..addAll(f3);
  print(fruit);

  var fruit2 = Map.from(f1)..addAll(f2)..addAll(f3);
  print(fruit2);

  var fruit3 = {...f1, ...f2, ...f3};
  print(fruit3);
}

In the example, we have three maps. We merge them with addAll and the spread operator.

$ dart main.dart
{1: Apple, 2: Orange, 3: Banana, 4: Mango}
{1: Apple, 2: Orange, 3: Banana, 4: Mango}
{1: Apple, 2: Orange, 3: Banana, 4: Mango}

Dart containsKey/containsValue

With containsKey and containsValue, we can determine if a map contains a specific key and value.

main.dart
void main() {
  var myMap = {1: 'Apple', 2: 'Orange', 3: 'Banana'};
  print(myMap.containsKey(1));
  print(myMap.containsKey(3));

  print(myMap.containsValue('Apple'));
  print(myMap.containsValue('Cherry'));
}

The example uses the containsKey and containsValue methods for a small map.

$ dart main.dart
true
true
true
false

Dart map iteration

We can iterate over map pairs with forEach method or for statement.

main.dart
void main() {
  var fruit = {1: 'Apple', 2: 'Banana', 3: 'Cherry', 4: 'Orange'};

  fruit.forEach((key, val) {
    print('{ key: $key, value: $val}');
  });

  print('---------------------------');

  fruit.entries.forEach((e) {
    print('{ key: ${e.key}, value: ${e.value} }');
  });

  print('---------------------------');

  for (var key in fruit.keys) print(key);
  for (var value in fruit.values) print(value);
}

In the example, we loop over a map of fruit.

fruit.forEach((key, val) {
  print('{ key: $key, value: $val}');
});

With forEach method, we print the key/value pairs of the fruit map.

fruit.entries.forEach((e) {
  print('{ key: ${e.key}, value: ${e.value} }');
});

In a similar fashion, we loop over the entry objects of the fruit map.

for (var key in fruit.keys) print(key);
for (var value in fruit.values) print(value);

Finally, with for statements, we go through the keys and values separately.

$ dart main.dart
{ key: 1, value: Apple}
{ key: 2, value: Banana}
{ key: 3, value: Cherry}
{ key: 4, value: Orange}
---------------------------
{ key: 1, value: Apple }
{ key: 2, value: Banana }
{ key: 3, value: Cherry }
{ key: 4, value: Orange }
---------------------------
1
2
3
4
Apple
Banana
Cherry
Orange

Dart sort map

When we need to sort maps, we can use the SplayTreeMap. The SplayTreeMap is ordered by sorted keys.

main.dart
import 'dart:collection';

void main() {
  var fruit = new SplayTreeMap<int, String>();

  fruit[0] = 'Banana';
  fruit[5] = 'Plum';
  fruit[6] = 'Strawberry';
  fruit[2] = 'Orange';
  fruit[3] = 'Mango';
  fruit[4] = 'Blueberry';
  fruit[1] = 'Apple';

  print(fruit);

  fruit.forEach((key, val) {
    print('{ key: $key, value: $val}');
  });

  var sortedByValue = new SplayTreeMap<int, String>.from(
      fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));
  print(sortedByValue);
}

We have a map of fruit. By default, the pairs are ordered by the keys -- numerically, in ascending order.

var sortedByValue = new SplayTreeMap<int, String>.from(
    fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));

We create a sorted map by values from the original map. We pass the from function a comparison function, which compares the values of the pairs.

$ dart main.dart
{0: Banana, 1: Apple, 2: Orange, 3: Mango, 4: Blueberry, 5: Plum, 6: Strawberry}
{ key: 0, value: Banana}
{ key: 1, value: Apple}
{ key: 2, value: Orange}
{ key: 3, value: Mango}
{ key: 4, value: Blueberry}
{ key: 5, value: Plum}
{ key: 6, value: Strawberry}
{1: Apple, 0: Banana, 4: Blueberry, 3: Mango, 2: Orange, 5: Plum, 6: Strawberry}

Source

Dart Map - language reference

In this article we have covered Dart maps.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Dart tutorials.