Maps in Dart are versatile collections that store key-value pairs. They provide an efficient way to organize and retrieve data using unique identifiers.
A map is an object that associates keys with values. Each key in a map must be unique, but values can be repeated. Maps are particularly useful when you need to quickly look up values based on specific keys.
There are several ways to create maps in Dart:
var fruits = {
'apple': 'red',
'banana': 'yellow',
'grape': 'purple'
};
var scores = Map<String, int>();
scores['John'] = 95;
scores['Alice'] = 88;
You can access and modify map elements using square bracket notation:
var fruits = {'apple': 'red', 'banana': 'yellow'};
print(fruits['apple']); // Output: red
fruits['grape'] = 'purple'; // Adding a new key-value pair
fruits['banana'] = 'green'; // Modifying an existing value
Dart provides several helpful methods for working with maps:
length
: Returns the number of key-value pairs in the mapisEmpty
: Checks if the map is emptykeys
: Returns an iterable of all keys in the mapvalues
: Returns an iterable of all values in the mapcontainsKey()
: Checks if a specific key exists in the mapremove()
: Removes a key-value pair from the mapYou can iterate over a map using various methods:
var fruits = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'};
// Using forEach
fruits.forEach((key, value) {
print('$key is $value');
});
// Using for-in loop
for (var entry in fruits.entries) {
print('${entry.key} is ${entry.value}');
}
With Dart's null safety feature, you can create maps that allow or disallow null values:
Map<String, String> nonNullableMap = {'key': 'value'};
Map<String, String?> nullableValueMap = {'key': null};
To further enhance your understanding of Dart collections, explore these related topics:
Maps are a fundamental part of Dart's collection types, offering a powerful way to organize and manipulate data. By mastering maps, you'll be well-equipped to handle complex data structures in your Dart applications.