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.
Map
literalLike 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
.
var map_name = {
key : value,
key : value,
key : value
};
map_name
is the name of the map.
A Map
requires key-value pair data, not a function.
The following code shows how to declare a map using map
literal:
void main() {// Creating Mapvar map = {"name": "Maria","id": "143A023","address": null,"gender": "Female"};print(map);}
Note: A
Map
can containnull
values.
We can also add values into the Map
at runtime. The following is the syntax to do so:
map_name[key] = value;
The following code shows how to add values to a Map
:
void main() {// Creating Mapvar map = {"name": "Maria","id": "143A023","address": null,"gender": "Female"};print('****Before updating the map****');print(map);// update mapmap["age"] = "10";map["hobbies"] = "Cooking, traveling, writing";print('****After updating the map****');print(map);}