A map is a collection of key/value pairs. The value is retrieved from a map with its associated key. Maps are also called dictionaries, associative arrays, or hash tables.
Depending on the iteration order, there are three types of maps in Dart:
HashMap - unordered
LinkedHashMap - ordered by insertion order
SplayTreeMap - ordered by sorted keys
By default, creating an instance using Map constructor (Map
, Map.from
, or Map.of
) creates a LinkedHashMap
.
A map is created with a map literal or with a map constructor. To work with maps, we import the dart:collection
library.
A map literal consists of a pair of curly brackes, in which we specify the key/value pairs. The pairs are separated by comma. The key is separated from the value by colon.
Maps can be declared in two ways −
Using Map Literals
Using a Map constructor
Declaring a Map using Map Literals
To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }".
Here is its syntax −
var identifier = { key1:value1, key2:value2 [,…..,key_n:value_n] }
Declaring a Map using a Map Constructor
To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map.
The syntax to declare a map is as follows −
var identifier = new Map()
Now, use the following syntax to initialize the map −
map_name[key] = value
Example: Map Literal
void main() {
var details = {'Usrname':'tom','Password':'pass@123'};
print(details);
}
It will produce the following output −
{Usrname: tom, Password: pass@123}
Example: Adding Values to Map Literals at Runtime
void main() {
var details = {'Usrname':'tom','Password':'pass@123'};
details['Uid'] = 'U1oo1';
print(details);
}
It will produce the following output −
{Usrname: tom, Password: pass@123, Uid: U1oo1}
Example: Map Constructor
void main() {
var details = new Map();
details['Usrname'] = 'admin';
details['Password'] = 'admin@123';
print(details);
}
It will produce the following output −
{Usrname: admin, Password: admin@123}
Note − A map value can be any object including NULL.