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.
- Map Literal
- Empty Map
- Using
Map.from()
Map.from()
- Using
Map.of()
Map.of()
- Using
Map.fromIterable()
Map.fromIterable()Creates a map from an iterable, using functions to generate keys and values.
- Using
Map.fromIterables()
Map.fromIterables()Creates a map from separate iterables of keys and values.
- Using
Map.identity()
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.
- Unmodifiable Map
Accessing Values
Adding and Updating Entries
Removing Entries
Iterating Over a Map
Common Map Methods and Properties
keys– returns an iterable of all keys.
values– returns an iterable of all values.
entries– returns an iterable ofMapEntryobjects.
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
Collection If and For with Maps
Map literals also support collection if and for for conditional and computed entries.
Complete Example
Key Takeaways
- Maps store key‑value pairs with unique keys.
- Use map literals
{}with type arguments to create maps.
- Use map literals
- Access values with
map[key](returnsnullif key not found).
- Access values with
- Add or update entries using
map[key] = value.
- Add or update entries using
- Remove entries with
remove(),removeWhere(), orclear().
- Remove entries with
- Iterate over keys, values, or entries using
forEachor loops.
- Iterate over keys, values, or entries using
- Common methods:
containsKey,containsValue,putIfAbsent,addAll,update,updateAll.
- Common methods:
- Collection
ifandforwork inside map literals.
- Collection
- Choose the right map constructor for your use case:
Map.from,Map.of,Map.fromIterable,Map.fromIterables,Map.identity,Map.unmodifiable.
- Choose the right map constructor for your use case: