Maps
Maps in Dart are collections of key-value pairs, where each key is associated with exactly one value. They are useful when we need to associate data with unique keys and can provide quick lookups by key. Here’s a guide to help us get started with Maps in Dart:
Creating a Map
We can create a map using the Map
constructor or a map literal.
// Using Map constructor
Map<String, int> ages = Map<String, int>();
// Using map literal
Map<String, int> ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
Adding and Updating Entries
We can add or update entries in a map by assigning a value to a key.
// Adding new entries
ages['David'] = 40;
ages['Eve'] = 22;
// Updating an existing entry
ages['Alice'] = 31; // Updates Alice's age to 31
Accessing Values
We can access the value associated with a key using the key.
int aliceAge = ages['Alice']; // 31
int bobAge = ages['Bob']; // 25
Removing Entries
We can remove entries from a map using the remove
method.
ages.remove('Bob'); // Removes the entry with key 'Bob'
Iterating Over a Map
We can iterate over the entries in a map using a forEach
loop, a for-in
loop, or other iteration methods.
// Using forEach
ages.forEach((key, value) {
print('$key: $value');
});
// Using for-in loop
for (var entry in ages.entries) {
print('${entry.key}: ${entry.value}');
}
Checking for Keys or Values
We can check if a map contains a specific key or value using containsKey
and containsValue
.
bool hasAlice = ages.containsKey('Alice'); // true
bool hasAge30 = ages.containsValue(30); // false (because Alice's age was updated to 31)
Getting Keys and Values
We can get all keys or values in a map using the keys
and values
properties.
Iterable<String> keys = ages.keys; // ['Alice', 'Charlie', 'David', 'Eve']
Iterable<int> values = ages.values; // [31, 35, 40, 22]
Example
Here’s a small example demonstrating how to use maps in Dart:
void main() {
Map<String, int> ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
// Adding new entries
ages['David'] = 40;
ages['Eve'] = 22;
// Updating an existing entry
ages['Alice'] = 31;
// Accessing values
print('Alice is ${ages['Alice']} years old.');
// Removing an entry
ages.remove('Bob');
// Iterating over a map
ages.forEach((key, value) {
print('$key is $value years old.');
});
// Checking for keys or values
print(ages.containsKey('Charlie')); // true
print(ages.containsValue(30)); // false
// Getting keys and values
print('Keys: ${ages.keys}'); // Keys: (Alice, Charlie, David, Eve)
print('Values: ${ages.values}'); // Values: (31, 35, 40, 22)
}
Maps in Dart provide powerful functionality for working with key-value pairs, making them ideal for many common programming tasks.