Maps 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 dynamicMap\<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](/tutorials/dart-tutorials/dart-basics/variables-and-datatypes-in-dart/#string-datatype-in-dart), but the value maynot be always string, take the age value its a number. So we declared value as [dynamic](/tutorials/dart-tutorials/dart-basics/variables-and-datatypes-in-dart/#dynamic-datatype-in-dart). 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}
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 ?
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’].
While passing the key we need to pass we need to consider the datatype as well. Example: If you key is int, pass mapName[3]. If its String, pass mapName[’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
Since we are learning collection datatypes in dart. Most of the methods and properties are common in all datatypes i.e [List](tutorials/dart-tutorials/dart-collections/list-in-dart/), [Sets](/tutorials/dart-tutorials/dart-collections/sets-in-dart/) and [Map](#). Lets take a look at some of the most commonly used methods and properties in dart maps.
Here is the list of properties in dart map. | Property | Description || — | — || length | Returns the number of key-value pairs in the map. || isEmpty | Returns true if the map is empty. || isNotEmpty | Returns true if the map is not empty. || keys | Returns an iterable object containing the keys of the map. || values | Returns an iterable object containing the values of the map. |
| Method | Description || — | — || 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: 8IsEmpty?: falseIsNotEmpty: trueKeys: (name, address, phone_number, photo, blood_group, role, department, age)Values: (Jimme Hughes, New zealand, +XXXXXXX, image.png, O -ve, ..., Development, 34)truefalseEmployeeData 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: {}
| Method | Description || — | — || 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.
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: TomId: E1001
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}
Dont’t forget to make the best with the practice.
You can test your understanding with the questions we prepared, it will take less than 4 minutes.