Maps
Maps is an unordered pair of key and values. The keys of the map must unique, values can be the same. Map is also called dictionary or hash .The size of a map is not fixed, we can add, delete edit the values of the map. The size of the map depends upon the number of elements in the map. The values in the map can only be accessed through the key name, not by the index values.
- Creating a map using constructor:
void main() {
Map<String, int> map = Map();
}
Here we have created a map named map whose key type is String and value type is int .
- Adding a value and printing the map:
void main() {
Map<String, int> map = Map();
map['number'] = 1;
print(map);
}
Output:{number: 1}
Accessing value by its key : print(map[‘number’]); .
Printing all keys and values of the map:
void main() {
Map<String, int> map = Map();
map['number1'] = 1;
map['number2'] = 2;
map['number3'] = 3;
for (String keys in map.keys) {
print(keys);
}
for (int values in map.values) {
print(values);
}
}
Output:
number1
number2
number3
1
2
3
Printing Key-Value pair:
map.forEach((key, value) {
print("$key:$value");
});
OutPut:
number1:1
number2:2
number3:3