Skip to main content

What are Maps?

Maps (also called dictionaries) are collections that store data in key-value pairs. Each key is unique and maps to a specific value, making it easy to look up data quickly.

Creating Maps

Create a map by specifying the key and value types:
The syntax Map<String, int> means keys are Strings and values are integers. You can use any type for both keys and values.

Accessing Values

Access values using the key in square brackets:
Accessing a non-existent key returns null, not an error. Always check if a key exists before using its value if you’re unsure.

Adding and Updating Values

Adding New Entries

Assign a value to a new key to add it to the map:

Updating Existing Entries

Assigning to an existing key updates its value:
There’s no difference in syntax between adding and updating - if the key exists, it updates; if not, it adds.

Checking for Keys and Values

Check if Key Exists

Use containsKey() to verify if a key is present:

Check if Value Exists

Use containsValue() to check if any key has that value:

Removing Entries

Use the remove() method to delete a key-value pair:
The remove() method doesn’t throw an error if the key doesn’t exist - it simply does nothing.

Map Properties

Maps provide several useful properties:

Get All Keys

Get All Values

Get Number of Entries

Check if Empty

Common Map Properties

Complete Example

When to Use Maps

Quick Lookups

Find data instantly using a unique identifier (like ID, name, or code)

Associations

Connect related data, like names to phone numbers or products to prices

Counting

Track occurrences or frequencies of items

Configuration

Store settings and preferences with named keys

Maps vs Lists

*Dart maps maintain insertion order, but this is an implementation detail. If order matters, consider using a List instead.

Best Practices

Check before accessing: Use containsKey() to avoid null values:
Use descriptive keys: Choose meaningful key names that clearly represent the data: