Have you ever wondered how you get your instagram posts right at your finger tips?

Well, ladies and gentlemen that’s where we use this kind of collection datatypes in dart to process the requests and response.

Familiar with this topic? Play Quiz

What is Map in dart ?

Maps are similar to json data with a key and a value. So, Maps are the datatypes in dart which stores data in the key-value pairs.

Key and values both have their own datatypes, we need to specify the datatypes of keys and values as well.

Now, lets get our handy dirty!

Syntax

  
Map<key_datatype, value_datatype> mapName = {
    key1 : value1, 
    key2 : value2
}; 
  

In the syntax above, you must have noticed angular brackets, inside which key_datatype and value_datatype are mentioned. That’s the place where we have to specify the datatypes that are supported by dart.

A map can have multiple number of keys and values each seperated by comma(,).

Lets imagine a real world use case, we we have to add include the data of a flutter developer working in the company, our data would be like this:

  /// here i am sure that the datatype of the key will remain same
/// but the value may differ 
/// for that key datatype is  string and 
/// value is  dynamic
Map<String,dynamic> userData = { 

    "name": "Jimme Hughes" ,
    "address" : "New zealand" ,
    "phone_number": "+XXXXXXX" ,
    "photo" : "image.png",
    "blood_group": "O -ve), 
    "role": "Flutter Developer", 
    "department" : "Development",
    "age": 34
}
  

Now let’s analyze the data we created. You can notice the following points in the data above:

  • Dataypes of keys and values are defined. In this case since the key will be string for every value we declared it as String, but the value maynot be always string, take the age value its a number. So we declared value as dynamic.

Example

  void main() {
  Map<String, dynamic> employeeData = {
    "name": "Jimme Hughes",
    "address": "New zealand",
    "phone_number": "+XXXXXXX",
    "photo": "image.png",
    "blood_group": "O -ve",
    "role": "Flutter Developer",
    "department": "Development",
    "age": 34
  };

  print(employeeData);
}
  

Output

This will be be the output if you run the code by yourself.

  {name: Jimme Hughes, address: New zealand, phone_number: +XXXXXXX, photo: image.png, blood_group: O -ve, role: Flutter Developer, department: Development, age: 34}
  

code Try Yourself

Getting values of Dart map

Now we can create and print the value of maps in dart. But we printed the whole map but what if I only needed the name of that employee ?

How to get the values from the dart map?

We will take the same code from above and understand it. Let’s print the name of the employee. To get the value from the map we make use of big brackets [] with key to want to get value from. eg . [’name’].

Example

  
void main() {
  Map<String, dynamic> employeeData = {
    "name": "Jimme Hughes",
    "address": "New zealand",
    "phone_number": "+XXXXXXX",
    "photo": "image.png",
    "blood_group": "O -ve",
    "role": "Flutter Developer",
    "department": "Development",
    "age": 34
  };

  print(employeeData['name']);
}
  

Output

  Jimme Hughes
  

code Try Yourself

Operations on Maps

Since we are learning collection datatypes in dart. Most of the methods and properties are common in all datatypes i.e List, Sets and Map.

Lets take a look at some of the most commonly used methods and properties in dart maps.

Properties and Methods of Dart Map

Here is the list of properties in dart map.

PropertyDescription
lengthReturns the number of key-value pairs in the map.
isEmptyReturns true if the map is empty.
sNotEmptyReturns true if the map is not empty.
keysReturns an iterable object containing the keys of the map.
valuesReturns an iterable object containing the values of the map.

Here is the list of methods in dart map.

MethodDescription
containsKey(key)Returns true if the map contains the specified key.
containsValue(value)Returns true if the map contains the specified value.
remove(key)Removes the key-value pair with the specified key from the map.
addAll(otherMap)Adds all key-value pairs from the otherMap to the map.
clear()Removes all key-value pairs from the map.

Now, let make use of every singe methods and properties. Please read the comments in the code itself.

Example

  void main() {
  Map<String, dynamic> employeeData = {
    "name": "Jimme Hughes",
    "address": "New zealand",
    "phone_number": "+XXXXXXX",
    "photo": "image.png",
    "blood_group": "O -ve",
    "role": "Flutter Developer",
    "department": "Development",
    "age": 34
  };

  /// Properties

  // length
  print("Length:  ${employeeData.length}"); // 8
  // isEmpty
  print("IsEmpty?: ${employeeData.isEmpty}"); // false
  // isNotEmpty
  print("IsNotEmpty: ${employeeData.isNotEmpty}"); // true
  // keys
  print("Keys:  ${employeeData.keys}"); // check output
  print("Values: ${employeeData.values}"); // check output

  /// Methods

  print(employeeData.containsKey("age")); //true
  print(employeeData.containsValue("boyfriend")); // false

  employeeData.addAll({
    "house_no": 12,
  });

  /// adds the house_no: 12
  print("EmployeeData after adding: \n $employeeData");

  employeeData.remove("house_no"); // removed the house_no key-pair

  print("EmployeeData after removing: \n $employeeData");

  employeeData.clear();
  print("EmployeeData after clearing: \n $employeeData");
}
  

Output

  Length:  8
IsEmpty?: false
IsNotEmpty: true
Keys:  (name, address, phone_number, photo, blood_group, role, department, age)
Values: (Jimme Hughes, New zealand, +XXXXXXX, image.png, O -ve, ..., Development, 34)
true
false
EmployeeData after adding: 
 {name: Jimme Hughes, address: New zealand, phone_number: +XXXXXXX, photo: image.png, blood_group: O -ve, role: Flutter Developer, department: Development, age: 34, house_no: 12}
EmployeeData after removing: 
 {name: Jimme Hughes, address: New zealand, phone_number: +XXXXXXX, photo: image.png, blood_group: O -ve, role: Flutter Developer, department: Development, age: 34}
EmployeeData after clearing: 
 {}
  

code Try Yourself

Looping Through Maps:

MethodDescription
forEach()Executes the specified function on each key-value pair in the map.
map()Creates a new map containing the key-value pairs of the original map.

Lets see the eample of each of the above looping methods.

forEach() in dart map

The forEach() method executes the specified function on each key-value pair in the map.

Example

  void main() {
  var map = {'name': 'Tom', 'Id': 'E1001'};
  map.forEach((k, v) => print('${k}: ${v}'));
} 
  

Output

  name: Tom
Id: E1001
  

code Try Yourself

map() in dart map

The map() method creates a new map containing the key-value pairs of the original map.

Example

  void main() {
  var map = {'name': 'Tom', 'Id': 'E1001'};
  var map2 = map.map((k, v) => MapEntry(k, v.toUpperCase()));
  print('Map : ${map}');
  print('New Map : ${map2}');
}
  

Output

  Map : {name: Tom, Id: E1001}
New Map : {name: TOM, Id: E1001}
  

code Try Yourself

Dont’t forget to make the best with the practice.

Quiz

You can test your understanding with the questions we prepared, it will take less than 4 minutes.