Skip to main content
A Map is a collection object that associates keys with values. Each key must be unique within the collection, while values may be duplicated. Dart maps are instances of the generic Map<K, V> class, where K represents the type of the key and V represents the type of the value.

Declaration and Initialization

Maps can be initialized using map literals or the Map constructor. Map Literals The most common method for creating a map is using curly braces {} with key: value pairs. Dart infers the types of K and V based on the content unless explicitly typed.
// Type inferred as Map<String, String>
var elements = {
  'H': 'Hydrogen',
  'He': 'Helium',
  'Li': 'Lithium',
};

// Explicitly typed literal
var atomicNumbers = <String, int>{
  'H': 1,
  'He': 2,
  'Li': 3,
};

// Constant Map (compile-time constant)
const finalMap = {1: 'A', 2: 'B'};
Map Constructor The default constructor creates a LinkedHashMap, which preserves insertion order.
// explicit definition
Map<int, String> codes = Map();
codes[404] = 'Not Found';
codes[200] = 'OK';

Access and Modification

Interaction with map elements is primarily handled via the subscript operator []. Retrieving Values The subscript operator returns the value associated with the provided key. If the key is not present, it returns null. Consequently, the return type of a lookup on Map<K, V> is nullable V?.
var inventory = {'apples': 10, 'oranges': 5};

// Returns 10 (int?)
var count = inventory['apples']; 

// Returns null because 'bananas' is not a key
var missing = inventory['bananas']; 
Adding and Updating Values The subscript assignment operator []= is used for both adding new pairs and updating existing ones.
var settings = <String, bool>{};

// Adds a new key-value pair
settings['darkMode'] = true;

// Updates the value for the existing key
settings['darkMode'] = false;

Core Properties

  • keys: Returns an Iterable<K> containing all keys in the map.
  • values: Returns an Iterable<V> containing all values in the map.
  • length: Returns the number of key-value pairs as an int.
  • isEmpty / isNotEmpty: Boolean checks for the presence of elements.
var user = {'id': 101, 'name': 'Alice'};

print(user.keys);   // (id, name)
print(user.values); // (101, Alice)
print(user.length); // 2

Iteration

Maps provide multiple mechanisms for iteration. forEach Accepts a function that takes a key and a value.
var scores = {'Alice': 95, 'Bob': 80};

scores.forEach((key, value) {
  print('$key: $value');
});
entries The entries property returns an Iterable<MapEntry<K, V>>. This allows iteration via a standard for-in loop.
for (var entry in scores.entries) {
  print('${entry.key} scored ${entry.value}');
}

Control Flow Operators

Dart supports collection operators within map literals to dynamically build maps. Spread Operator (...) Inserts all key-value pairs from another map into the current map.
var first = {'a': 1, 'b': 2};
var second = {'c': 3, ...first}; // {'c': 3, 'a': 1, 'b': 2}
Collection If and For Allows conditional inclusion or algorithmic generation of entries during initialization.
var hasPermission = true;
var menu = {
  'home': '/home',
  if (hasPermission) 'admin': '/admin',
};

var numbers = [1, 2, 3];
var squared = {
  for (var n in numbers) n: n * n
}; // {1: 1, 2: 4, 3: 9}

Key Methods

  • containsKey(Object? key): Returns true if the map contains the specified key.
  • containsValue(Object? value): Returns true if the map contains the specified value.
  • remove(Object? key): Removes the key and its associated value, returning the value removed.
  • clear(): Removes all pairs from the map.
  • putIfAbsent(K key, V Function() ifAbsent): Look up the value of key, or add a new value if it isn’t there.
Master Dart with Deep Grasping Methodology!Learn More