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: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
UsecontainsKey() to verify if a key is present:
Check if Value Exists
UsecontainsValue() to check if any key has that value:
| Method | Description | Returns |
|---|---|---|
containsKey(key) | Checks if the key exists | true or false |
containsValue(value) | Checks if any key has this value | true or false |
Removing Entries
Use theremove() method to delete a key-value pair:
Map Properties
Maps provide several useful properties:Get All Keys
Get All Values
Get Number of Entries
Check if Empty
Common Map Properties
| Property | Description | Example |
|---|---|---|
keys | Returns all keys | edades.keys |
values | Returns all values | edades.values |
length | Number of key-value pairs | edades.length |
isEmpty | Returns true if map is empty | edades.isEmpty |
isNotEmpty | Returns true if map has entries | edades.isNotEmpty |
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
| Feature | List | Map |
|---|---|---|
| Access | By numeric index (0, 1, 2…) | By unique key (any type) |
| Order | Maintains insertion order | Maintains insertion order* |
| Duplicates | Values can repeat | Keys must be unique, values can repeat |
| Use Case | Ordered collections | Key-value associations |
| Speed | O(1) by index | O(1) by key |
*Dart maps maintain insertion order, but this is an implementation detail. If order matters, consider using a List instead.