Table of contents
1.
Introduction
2.
Implementation of Map
2.1.
Using Map Literals
2.1.1.
Using Explicit Data Types
2.1.2.
Using var keywords 
2.2.
Using Map Constructor
3.
Properties of Maps
4.
Methods in Maps
5.
Frequently Asked Questions
5.1.
Can we pass a list to a map of explicit define data types?
5.2.
What is the difference between clear() and remove() functions in the map?
5.3.
How is a map is same as a dictionary?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Maps in Dart

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will be learning about the Map in dart. The Map is a data structure that stores the data in the form of key-value pairs means every value is associated with a key. This data structure also resembles the structure of a dictionary, due to which in python it is called a Dictionary. To learn more about python dictionary, go to this link.

In the Map, all the keys should be unique, there is no such constraint on values. A map is a dynamic collection that means it can contract and expands at runtime. We can declare the Map using curly braces {} with a comma (,) separated entries. Now let’s discuss its implementation.

Implementation of Map

A map can be implemented or declared using two ways in dart:

  1. Using Map Literals
  2. Using Map Constructor

Implementation and examples of both the ways are given below.

Using Map Literals

In this kind of declaration, we do not just declare the Map instead we initialize it with the data also. Here we assign the key-value pairs separated with a comma (,) and enclosed in the curly braces {}.

Since dart is a type of infer language, means it can automatically know the data type. So we can declare Map using two ways:

Using Explicit Data Types

 Here, you cannot change the data type.

Syntax:

Map<int,String> mp = {1:"Ninja1",2:"Ninja2",3:"Ninja3"}

 

Using var keywords 

Here you can change the data type.

Syntax:

var mp = {1:"Ninja1",2:"Ninja2","Third":"Ninja3"};

Example: Creating a map of type var.
Code:

void main() { 
  var mp = {1:"Ninja1",2:"Ninja2","Third":"Ninja3"};
  print(mp);
}


Output:

{1: Ninja1, 2: Ninja2, Third: Ninja3}


Explanation: Since the map is of type var, so it can have keys and values of any data type.


Example: Creating a map of predefined data types.
Code:

void main() { 
  Map<int,String> mp = {1:"Ninja1",2:"Ninja2",3:"Ninja3"};
  print(mp);
}


Output:

{1: Ninja1, 2: Ninja2, 3: Ninja3}


Explanation: Map ‘mp’ will only have the keys of data type int and values of data type String

 

Example: In this example, we will try to change the data type of key other than what is defined during the declaration.
Code:

void main() { 
  //Here changing data type generates error
  Map<int,String> mp = {1:"Ninja1",2:"Ninja2","Third":"Ninja3"};
  print(mp);
}


Output:

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:3:47:
Error: A value of type 'String' can't be assigned to a variable of type 'int'.
  Map<int,String> mp = {1:"Ninja1",2:"Ninja2","Third":"Ninja3"};
                                              ^
Error: Compilation failed.


Explanation: We changed the data type of the key of the third element. It is showing an error because we have declared the key's data type as int.

Example: In this example, we will add an element to the map.
Code:

void main() { 
  //Adding elements to a map.
  var mp = {"S.No.":155, "Name":"Ninja1"};
  mp["Branch"] = "CSE";
  print(mp);
}


Output:

{S.No.: 155, Name: Ninja1, Branch: CSE}


Explanation: Adding a new element to our map ‘mp’ where the key is “Branch” and the value is “CSE”.

Using Map Constructor

In this kind of declaration, we first declare the map object and then initialize the value to it. Here also, we can use the var keyword or the explicit data types.

Syntax:

Map<String,String> mp =  Map();
//OR
var mp =  Map();


Example: We will create a map using a map constructor and in the last, we will print the map.
Code:

void main() { 
  Map<String,String> mp =  Map();
  mp["Sansa"] = "Stark";
  mp["Rhaegar"] = "Targaryen";
  mp["Tyrion"] = "Lannister";
  print(mp);
}


Output:

{Sansa: Stark, Rhaegar: Targaryen, Tyrion: Lannister}


Explanation: This map has the character's name of GOT where the key is the name of the character and the value is the name of his house. 

Example: In this example, we will insert a list as a value.
Code:

void main() { 
  var mp =  Map();
  mp["Stark"] = "Sansa";
  //Using list inside map.
  mp["Targaryen"] = ["Rhaegar","Aegon"];
  mp["Lannister"] = "Tyrion";
  print(mp);
}


Output:

{Stark: Sansa, Targaryen: [Rhaegar, Aegon], Lannister: Tyrion}


Explanation: This map has house names of GOT where the keys are the houses and the values are member from that house. In the 'Targaryen' house, we have two members which are in the form of a list. 

Properties of Maps

After declaration and initialization, when we want to access the components of the Map, we use its properties which are there in the Map class in dart.

S.No. Properties Description
1 keys It gives us all the keys as the iterable object.
2 values It gives us all the values as the iterable object.
3 length It gives us the length of the Map.
4 isEmpty It returns true if Map is empty, else false.
5 isNotEmpty It returns false if Map is empty, else true. 

Example: This example shows the implementation of all the above properties.

Code:

// Implementation of all above properties.
void main() { 
  var mp =  Map();
  mp["Instructor Name"] = "Ninja1";
  mp["No. of Sub."] = 3;
  //Using list inside map.
  mp["Subjects"] = ["COA","OS","DBMS"];
  //Using map in map
  mp["Experience"] = {"COA":4,"OS":3,"DBMS":5};
  print(mp);
  print("Keys are: ${mp.keys}");
  print("Values are: ${mp.values}");
  print("Length: ${mp.length}");
  print("Is map is empty: ${mp.isEmpty}");
  print("Is map is not Empty: ${mp.isNotEmpty}");
}


Output:

{Instructor Name: Ninja1, No. of Sub.: 3, Subjects: [COA, OS, DBMS], Experience: {COA: 4, OS: 3, DBMS: 5}}
Keys are: (Instructor Name, No. of Sub., Subjects, Experience)
Values are: (Ninja1, 3, [COA, OS, DBMS], {COA: 4, OS: 3, DBMS: 5})
Length: 4
Is Map is empty: false
Is Map is not Empty: true

Methods in Maps

Methods in Map are being provided to us in order to manipulate the Map when required. There are a bunch of methods that the map class has provided us are:

S.No. Method’s Name Description
1 addAll(Map<key,value> other) Adds another key-value pair map to it.
2 clear() Delete all the entries from the Map.
3 remove(Object key) Delete the entry with the given key only.
4 forEach() It is used to iterate over the Map.

Example: This example shows the implementation of all the above methods.

Code:

// Implementation of above methods.
void main() { 
  var mp = {"Name":"Ninja1","Age":24,"Skills":["WebD","Android","ML"]};
  var mp2 = {"Institute":"Coding Ninjas","Year":5};
  mp.forEach((key,val) => print('$key: $val'));
  mp.addAll(mp2);
  print("Map after Adding new values-----------");
  mp.forEach((key,val) => print('$key: $val'));
  mp.remove("Age");
  print("Map after removing age key-------------");
  mp.forEach((key,val) => print('$key: $val'));
  mp.clear();
  print("Map after calling clear method----------");
  print(mp);
}


Output:

Name: Ninja1
Age: 24
Skills: [WebD, Android, ML]
Map after Adding new values-----------
Name: Ninja1
Age: 24
Skills: [WebD, Android, ML]
Institute: Coding Ninjas
Year: 5
Map after removing the age key-------------
Name: Ninja1
Skills: [WebD, Android, ML]
Institute: Coding Ninjas
Year: 5
Map after calling clear method----------
{}


Check out this problem - Redundant Braces

Frequently Asked Questions

Can we pass a list to a map of explicit define data types?

If we are using the var keyword to define a map, then it is fine to pass the list, but if we have provided the data type to the key and value of the map, then we are bound to use only the defined data type in the map as a key value.

 

What is the difference between clear() and remove() functions in the map?

In a map, the clear() function removes all key-value pairs from the map and makes the map an empty map, whereas the remove(Object key) function takes an object as an argument and removes only that object from the map.

 

How is a map is same as a dictionary?

Just like in the dictionary, there is a word, and meaning is associated with that word. In the map, we use the same concept there is a key, and a value is associated with that key. In a map, keys and values can be of different data types. 

Conclusion

This article thoroughly discussed the Maps in dart and the syntax we write to use them. We also rigorously discussed its properties and methods.We hope that this blog helped you enrich your knowledge regarding Maps in Dart. We can use the concepts of dart in building an android app to learn in-depth about android development. Check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow. 
Happy Coding!

Live masterclass