In this chapter, we will learn about dart maps data types and the properties and methods of map that are available in dart.
Dart Map
In dart, a map denote a collection of data in key/value pairs. The key and value can be of any data type. For example,
var person = {'name': 'Phil', 'age': 25, 'isMale': true};
Declaring Map
We can create a map data type in two ways.
1. Using map literal
2. Using map constructor
Using map literal
We can create map data type by enclosing the value in curly braces and separating each pair by comma. For example,
void main() {
var person = {'name': 'Phil', 'age': 25, 'isMale': true};
print(person);
}
Output
{name: Phil, age: 25, isMale: true}
Using map Constructor
Another way to create map data is by passing the new keyword to the Map constructor. For example,
void main() {
var person = new Map();
person['name'] = 'Phil';
person['age'] = 25;
person['isMale'] = true;
print(person);
}
Output
{name: Phil, age: 25, isMale: true}
Note: In map data types, keys must be unique.
Dart Map Properties
Maps data types provide various properties. Some of them are:
Properties | Description |
length | Returns the number of key/value pairs in the map |
values | Returns an iterable object representing values |
keys | Returns an iterable object representing keys |
isEmpty | Returns true if the map is an empty map |
isNotEmpty | Returns false if the map is an empty Map |
Map Properties Examples
void main() {
var person = {'name': 'Phil', 'age': 25, 'isMale': true};
print(person);
print(person.length);
print(person.isEmpty);
print(person.isNotEmpty);
print(person.keys);
print(person.values);
}
Output
{name: Phil, age: 25, isMale: true}
3
false
true
(name, age, isMale)
(Phil, 25, true)
Dart Map Methods
Maps data type also has multiple methods available. Some of them are:
Methods | Description |
clear() | Removes all pairs from the map |
addAll() | Adds all key-value pairs of other to this map |
remove() | Removes key and its associated value |
Map Method Examples
void main() {
var person = {'name': 'Phil', 'age': 25, 'isMale': true};
print(person);
person.addAll({'address': 'New York', 'email': '[email protected]'});
print('After adding: ${person}');
person.remove('age');
print('After removing: ${person}');
person.clear();
print('After clearing: ${person}');
}
Output
{name: Phil, age: 25, isMale: true}
After adding: {name: Phil, age: 25, isMale: true, address: New York, email: [email protected]}
After removing: {name: Phil, isMale: true, address: New York, email: [email protected]}
After clearing: {}