Search⌘ K
AI Features

Dart's Collection: Maps

Explore how to create, access, and manipulate Dart Maps as an unordered collection of unique key-value pairs. Learn about typed literals, null safety during lookups, and methods like add, remove, and containsKey. This lesson equips you with essential knowledge to work with Maps alongside Lists and Sets for effective state and data management in Dart applications.

We have seen how Lists use numerical indices and Sets enforce uniqueness. A Map is an unordered collection of key-value pairs. We use a Map when we want to look up a specific value using a unique identifier known as a key. Every key in a Map must be unique, but multiple keys can point to identical values.

Creating a map

We create a map using curly braces {}. To ensure type safety, we use typed literals by specifying both the key type and the value type inside angle brackets <KeyType, ValueType> just before the braces.

The complete syntax for creating a map looks like this:

final mapName = <KeyType, ValueType>{key1: value1, key2: value2};

While we can create an empty map using a constructor like Map(), modern Dart strongly prefers typed literals because they clearly define the expected data types and reduce boilerplate.

If we assign a value to a key that already exists in the map, ...