In Dart, a Map is a collection of key-value pairs, similar to dictionaries in Python or objects in JavaScript. Each key is unique, and it maps to a specific value. Maps are very useful when you want to associate data logically rather than just storing it in a list.
For example, if I wanted to store information about a person:
void main() {
Map person = {
'name': 'Aswini',
'age': 25,
'city': 'Cuddalore'
};
print(person['name']); // Aswini
print(person['age']); // 25
}
Here, 'name', 'age', and 'city' are keys, and 'Aswini', 25, 'Cuddalore' are their corresponding values. You can access values using the key, and you can also add or update entries dynamically:
person['profession'] = 'Developer'; // Adding a new key-value
person['age'] = 26; // Updating an existing value
In practical projects, Iโve used Maps extensively for handling API responses. For example, when fetching JSON data from a server, itโs usually converted into a Map in Dart, making it easy to extract and manipulate specific fields.
One challenge I faced was handling nested Maps from complex JSON responses. To overcome this, I used null-safety operators (?) and the Map<String, dynamic> type to ensure type consistency.
A limitation of Maps is that keys must be unique, so if you try to add a duplicate key, it will overwrite the previous value. As an alternative, if you need multiple values for the same key, you can use a Map of Lists, like Map<String, List<String>>, which allows grouping multiple values under one key.
Maps are highly flexible and essential in Dart for structured data handling and efficient lookups.
