Dart Programming Tutorial on Dart Programming Map

the map object is a simple key/value pair. keys and values in a map may be of any type. a map is a dynamic collection. in other words, maps can grow and shrink at runtime.

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.

map – properties

the map class in the dart:core package defines the following properties −

sr.no property & description
1 keys

returns an iterable object representing keys

2 values

returns an iterable object representing values

3 length

returns the size of the map

4 isempty

returns true if the map is an empty map

5 isnotempty

returns true if the map is an empty map

map - functions

following are the commonly used functions for manipulating maps in dart.

sr.no function name & description
1 addall()

adds all key-value pairs of other to this map.

2 clear()

removes all pairs from the map.

3 remove()

removes key and its associated value, if present, from the map.

4 foreach()

applies f to each key-value pair of the map.