Maps in Dart

To demonstrate the usage of maps, which are Dart’s built-in associative data types, we’ll create a translation of the provided code and explanation. Maps in Dart are equivalent to dictionaries in other languages.

void main() {
  // Creating an empty map
  var m = <String, int>{};

  // Setting key/value pairs
  m['k1'] = 7;
  m['k2'] = 13;

  // Printing a map will show all its key/value pairs
  print('map: $m');

  // Getting a value for a key
  var v1 = m['k1'];
  print('v1: $v1');

  // If the key doesn't exist, it returns null
  var v3 = m['k3'];
  print('v3: $v3');

  // The number of key/value pairs in the map
  print('len: ${m.length}');

  // Removing key/value pairs from a map
  m.remove('k2');
  print('map: $m');

  // Removing all key/value pairs from a map
  m.clear();
  print('map: $m');

  // Checking if a key is present in the map
  var prs = m.containsKey('k2');
  print('prs: $prs');

  // Declare and initialize a new map in the same line
  var n = {'foo': 1, 'bar': 2};
  print('map: $n');

  // Check if two maps are equal
  var n2 = {'foo': 1, 'bar': 2};
  if (MapEquality().equals(n, n2)) {
    print('n == n2');
  }

}

class MapEquality {
  const MapEquality();
  bool equals(Map a, Map b) {
    if (a.length != b.length) return false;
    for (var key in a.keys) {
      if (a[key] != b[key]) return false;
    }
    return true;
  }
}

Explanation

To create an empty map in Dart, you can use the literal map syntax:

var m = <String, int>{};

Set key/value pairs using typical name[key] = val syntax:

m['k1'] = 7;
m['k2'] = 13;

Printing a map with print(m) will show all of its key/value pairs:

print('map: $m');

Get a value for a key with name[key]:

var v1 = m['k1'];
print('v1: $v1');

If the key doesn’t exist, Dart returns null:

var v3 = m['k3'];
print('v3: $v3');

The length property returns the number of key/value pairs in the map:

print('len: ${m.length}');

The remove method removes key/value pairs from a map:

m.remove('k2');
print('map: $m');

The clear method removes all key/value pairs from a map:

m.clear();
print('map: $m');

The containsKey method checks if a key is present in the map:

var prs = m.containsKey('k2');
print('prs: $prs');

You can also declare and initialize a new map in the same line:

var n = {'foo': 1, 'bar': 2};
print('map: $n');

To check if two maps are equal, we can use a custom equality function:

var n2 = {'foo': 1, 'bar': 2};
if (MapEquality().equals(n, n2)) {
  print('n == n2');
}

The MapEquality class contains a method to check if two maps are equal by comparing their keys and values.