flutter
/

Dart Map – Complete Guide with Examples

Last Sync: Today

On this page

19
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Map – Complete Guide with Examples

What is a Map in Dart?

A Map is an unordered collection of key‑value pairs. Each key must be unique, but values can be duplicated. Maps are also known as dictionaries or associative arrays in other languages. They are useful for storing data that can be looked up by a unique identifier, such as a user ID to user details, or a word to its definition.

Creating Maps

Dart offers several ways to create maps, depending on your needs.

  1. Map Literal

DARTRead-only
1
void main() {
  var fruits = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}; // Map<String, String>
  Map<int, String> users = {1: 'Alice', 2: 'Bob'};                       // explicit types
  print(fruits); // {apple: red, banana: yellow, grape: purple}
}

  1. Empty Map

DARTRead-only
1
void main() {
  var emptyMap = <String, int>{};          // empty Map<String, int>
  Map<String, double> anotherEmpty = {};   // also empty
}

  1. Using Map.from()

DARTRead-only
1
void main() {
  var original = {'a': 1, 'b': 2};
  var copy = Map.from(original); // {'a': 1, 'b': 2}
}

  1. Using Map.of()

DARTRead-only
1
void main() {
  var copy = Map.of({'a': 1, 'b': 2}); // also {'a': 1, 'b': 2}
}

  1. Using Map.fromIterable()

Creates a map from an iterable, using functions to generate keys and values.

DARTRead-only
1
void main() {
  var list = ['apple', 'banana', 'cherry'];
  var map = Map.fromIterable(list,
      key: (item) => item[0],          // first letter as key
      value: (item) => item.length);    // length as value
  print(map); // {a: 5, b: 6, c: 6}
}

  1. Using Map.fromIterables()

Creates a map from separate iterables of keys and values.

DARTRead-only
1
void main() {
  var keys = ['name', 'age', 'city'];
  var values = ['Alice', 30, 'New York'];
  var map = Map.fromIterables(keys, values);
  print(map); // {name: Alice, age: 30, city: New York}
}

  1. Using Map.identity()

Creates an identity‑based map, which uses identical() rather than == for key equality. Useful when keys are objects and you want to distinguish them even if their content is the same.

DARTRead-only
1
void main() {
  var map = Map.identity();
  var key1 = Object();
  var key2 = Object();
  map[key1] = 'value1';
  map[key2] = 'value2';
  print(map.length); // 2
}

  1. Unmodifiable Map

DARTRead-only
1
void main() {
  var fixed = Map.unmodifiable({'a': 1, 'b': 2});
  // fixed['c'] = 3; // Throws UnsupportedError
}

Accessing Values

DARTRead-only
1
void main() {
  var fruits = {'apple': 'red', 'banana': 'yellow'};
  print(fruits['apple']);        // red
  print(fruits['mango']);        // null (key not found)
  
  // Using .containsKey to check before access
  if (fruits.containsKey('banana')) {
    print('Banana is ${fruits['banana']}');
  }
  
  // Get all keys or values
  print(fruits.keys);   // (apple, banana)
  print(fruits.values); // (red, yellow)
}

Adding and Updating Entries

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2};
  
  // Add or update a single entry
  map['c'] = 3;        // add new
  map['a'] = 10;       // update existing
  
  // Add multiple entries
  map.addAll({'d': 4, 'e': 5});
  
  // Add only if key is absent
  map.putIfAbsent('f', () => 6); // adds f:6
  map.putIfAbsent('a', () => 99); // does nothing because 'a' exists
  
  print(map); // {a: 10, b: 2, c: 3, d: 4, e: 5, f: 6}
}

Removing Entries

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2, 'c': 3, 'd': 4};
  
  map.remove('b');           // removes key 'b'
  map.removeWhere((key, value) => value % 2 == 0); // removes keys with even values
  map.clear();               // removes all
}

Iterating Over a Map

DARTRead-only
1
void main() {
  var fruits = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'};
  
  // Iterate over keys
  for (var key in fruits.keys) {
    print('$key is ${fruits[key]}');
  }
  
  // Iterate over values
  for (var color in fruits.values) {
    print('Color: $color');
  }
  
  // Iterate over entries (key-value pairs)
  fruits.forEach((key, value) {
    print('$key → $value');
  });
}

Common Map Methods and Properties

    • keys – returns an iterable of all keys.
    • values – returns an iterable of all values.
    • entries – returns an iterable of MapEntry objects.
    • length – number of key‑value pairs.
    • isEmpty / isNotEmpty – checks if the map is empty.
    • containsKey(key) – checks if a key exists.
    • containsValue(value) – checks if a value exists (slower).
    • update(key, update, {ifAbsent}) – updates an existing entry.
    • updateAll(update) – updates all entries.
    • removeWhere(condition) – removes entries that satisfy a condition.
    • cast() – casts the map to a different type.
    • map() – transforms each entry into a new value (returns an iterable).

Using update and updateAll

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2};
  
  // update a single key
  map.update('a', (value) => value * 10); // a:10
  map.update('c', (value) => 3, ifAbsent: () => 3); // adds c:3
  
  // update all values
  map.updateAll((key, value) => value * 2); // a:20, b:4, c:6
  print(map);
}

Collection If and For with Maps

Map literals also support collection if and for for conditional and computed entries.

DARTRead-only
1
void main() {
  bool includeExtra = true;
  var map = {
    'a': 1,
    'b': 2,
    if (includeExtra) 'c': 3,
    for (var i in [4, 5]) 'd$i': i,
  };
  print(map); // {a: 1, b: 2, c: 3, d4: 4, d5: 5}
}

Complete Example

DARTRead-only
1
void main() {
  // Create a map of user data
  var users = {
    1: 'Alice',
    2: 'Bob',
    3: 'Charlie',
  };
  
  // Add a new user
  users[4] = 'Diana';
  
  // Update an existing user
  users[2] = 'Robert';
  
  // Check if a user exists
  if (users.containsKey(3)) {
    print('User 3 is ${users[3]}');
  }
  
  // Remove a user
  users.remove(1);
  
  // Iterate over all users
  users.forEach((id, name) {
    print('ID $id: $name');
  });
  
  // Get all names
  var names = users.values.toList();
  print('All names: $names');
}

Key Takeaways

    • Maps store key‑value pairs with unique keys.
    • Use map literals {} with type arguments to create maps.
    • Access values with map[key] (returns null if key not found).
    • Add or update entries using map[key] = value.
    • Remove entries with remove(), removeWhere(), or clear().
    • Iterate over keys, values, or entries using forEach or loops.
    • Common methods: containsKey, containsValue, putIfAbsent, addAll, update, updateAll.
    • Collection if and for work inside map literals.
    • Choose the right map constructor for your use case: Map.from, Map.of, Map.fromIterable, Map.fromIterables, Map.identity, Map.unmodifiable.

Try it yourself

void main() {
  // Create a map of capitals
  var capitals = {
    'France': 'Paris',
    'Japan': 'Tokyo',
    'India': 'New Delhi',
  };
  
  // Add a new capital
  capitals['Italy'] = 'Rome';
  
  // Print all capitals
  capitals.forEach((country, capital) {
    print('The capital of $country is $capital');
  });
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { var map = {'a': 1, 'b': 2}; print(map['c']); }

A
0
B
null
C
Error
D
false
Q2
of 4

How do you add a new key‑value pair to an existing map?

A
map.add('key', 'value')
B
map.put('key', 'value')
C
map['key'] = 'value'
D
map.insert('key', 'value')
Q3
of 4

Which method adds a value only if the key is not already present?

A
addIfAbsent()
B
putIfAbsent()
C
addAll()
D
updateIfAbsent()
Q4
of 4

What does `map.keys` return?

A
A List of keys
B
An Iterable of keys
C
A Set of keys
D
A Map of keys

Frequently Asked Questions

How do I check if a key exists in a Dart Map?

Use the containsKey() method: if (myMap.containsKey('someKey')) { ... }. You can also check myMap['someKey'] != null, but this won't work if the value can legitimately be null.

How do I get all keys or all values from a map?

Use the keys and values properties: var allKeys = myMap.keys; returns an iterable of keys; var allValues = myMap.values; returns an iterable of values. Convert to a list with .toList() if needed.

How do I iterate over a map?

You can iterate using forEach: myMap.forEach((key, value) { ... });. Alternatively, loop over keys or entries: for (var entry in myMap.entries) { print(entry.key); print(entry.value); }.

How do I merge two maps?

Use the spread operator: var merged = {...map1, ...map2};. If there are duplicate keys, the second map's value overwrites the first's. You can also use addAll(): map1.addAll(map2); modifies map1 in place.

What is the difference between `Map.from` and `Map.of`?

Map.from expects a Map and allows you to specify a different key/value type (it does a cast). Map.of also expects a Map but infers the types from the argument; it's more type‑safe. For most cases, prefer Map.of for copying a map of the same type.

How do I create a map from a list of objects?

Use Map.fromIterable() or Map.fromIterables(). For example: Map.fromIterable(list, key: (item) => item.id, value: (item) => item.name). Or if you have separate lists of keys and values, use Map.fromIterables(keys, values).

How do I handle nullable values in a map?

If your map can contain null values, be careful when using map[key] to check for existence, because it returns null both when the key is absent and when the value is null. Use containsKey() to distinguish.

What is the difference between `HashMap`, `LinkedHashMap`, and the default Map?

The default Map literal ({}) creates a LinkedHashMap that preserves insertion order. HashMap is unordered and slightly more efficient but does not guarantee order. LinkedHashMap is usually what you want. You can import dart:collection to use HashMap or LinkedHashMap explicitly if needed.

Previous

dart set

Next

dart collection methods

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.