How to create a Map using map literal in Dart

A Map is a form of collection, like a List. Data is saved in Maps as key-value pairs.

Note: Any type of key and value can be used.

Creating a Map using Map literal

Like a list, Map can also be created using the var keyword.

However, the main distinction between declarations is that we use [] (square brackets) to define a list while {} (curly braces) are used to declare a map.

Syntax

var map_name = {
  key : value,
  key : value,
  key : value
};

map_name is the name of the map.

Parameters

A Map requires key-value pair data, not a function.

Code

The following code shows how to declare a map using map literal:

void main() {
// Creating Map
var map = {
"name": "Maria",
"id": "143A023",
"address": null,
"gender": "Female"
};
print(map);
}

Note: A Map can contain null values.

Adding values at runtime

We can also add values into the Map at runtime. The following is the syntax to do so:

map_name[key] = value;

Code

The following code shows how to add values to a Map:

void main() {
// Creating Map
var map = {
"name": "Maria",
"id": "143A023",
"address": null,
"gender": "Female"
};
print('****Before updating the map****');
print(map);
// update map
map["age"] = "10";
map["hobbies"] = "Cooking, traveling, writing";
print('****After updating the map****');
print(map);
}

Free Resources