Maps in Dart : Learn All Map Operations

Home » Dart » Maps in Dart : Learn All Map Operations

Maps in the Dart programming language are a non-skippable feature because they are used in many areas, such as Flutter app development. Therefore, it’s super essential to learn map operations and their usage. Let’s Learn more about Maps in Dart.

Maps in Dart : Learn All Map Operations

What are maps in Dart?

Maps are a very useful data structure that can be beneficial when you need to organize and store data as key-value pairs.

How to create a Map in Dart?

Creating a map in the Dart language is pretty straightforward; just use the Map with data types specified for both keys and values.

To initialize a map in Dart, just use the Map constructor , providing key-value pairs with curly braces({}).

Map<String, int> fruits = {
    "Apple" : 5,
    "Oranges": 10,
    "Pineapples": 89,
    "Kiwi": 7,
    "Strawberry": 13
};

Let’s iterate through the map using a forEach statement.

fruits.forEach((key, value){
    print('$key : $value');
});

Program Example

void main() {

Map<String, int> fruits = {
    "Apple" : 5,
    "Oranges": 10,
    "Pineapples": 89,
    "Kiwi": 7,
    "Strawberry": 13
};

fruits.forEach((key, value){
    print('$key : $value');
});

}

Output:

Apple : 5
Oranges : 10
Pineapples : 89
Kiwi : 7
Strawberry : 13

Accessing Values (Map)

Let’s use keys to access the associated values from the map. For example, if you want to determine how many apples are in the map, you could write it like this:

// accessing values
var no_of_apples = fruits['Apple'];
print("Apple : $no_of_apples");

Adding and Updating Map

Let’s add a new entry to the map, such as:

// adding a new entry
fruits["Olive"] = 9;

Updating

//updating 
fruits['Kiwi'] = 100;

How to remove entries?

Remove an entry with map.remove(‘Oranges’), eliminating the key-value pair for ‘Oranges’.


// Remove an entry 
fruits.remove('Oranges');

Checking for Key Existence

//Checking for key existance 
var check =(fruits.containsKey('Strawberry')) ? 'Strawberry is found' : 'Strawberry is not found';
print(check);

Strawberry is found

Map Length

// Find length of the map
var length = fruits.length;
print("Length: $length");

Let’s clear a map :

// Clearing the map 
fruits.clear();

Iterating through a Map using For Loop


//Iterate through For loop
for(var entry in fruits.entries)
{
   print('${entry.key}: ${entry.value}');
}

Using Map Methods:

Dart offers useful methods, such as keys, values, and length, which allow you to manipulate and gather information from maps.

print(fruits.keys);
print(fruits.values);
print(fruits.length);

Output:

(Apple, Pineapples, Kiwi, Strawberry, Olive)
(5, 89, 100, 13, 9)
5

Handling Null Values in Dart

You can avoid null pointer exceptions by using ?? to provide a default value if the key is not available in the map. In this example, the ‘android‘ map doesn’t contain a ‘Jelly Bean‘ key, so it will take the default value of 4.1.

void main() {

Map<String, double> android = {
    "Cupcake" : 1.0,
    "Donut" : 1.1,
    "Honeycomb": 3.0,
    "KitKat": 4.4,
    "Pie": 9.0

};

// Handling null value 
var os = android['Jelly Bean'] ?? 4.1;  
print(os);
 
}
4.1

How do you update a map conditionally in Dart?

Consider the following book’s map:

Map<String, String> books = {
  
  "Deep Work" : "Cal Newport",
  "Wonder" : "R. J. Palacio",
  
};

Update the entry :

books.update("Deep Work", (value) => value.toUpperCase(), ifAbsent: () => 'No Author');

books.forEach((key, value){
 print("Book: $key , Author: $value");
});

Book: Deep Work , Author: CAL NEWPORT
Book: Wonder , Author: R. J. Palacio

Checking if Empty

if(books.isEmpty)
{
    print('${books.keys} is empty');
}
else{
     print('${books.keys} is not empty');
}

Copying a map

// copying a map 

var copiedBook = Map.from(books);

Check Map Equality with HashCode


var checks = books.hashCode == android.hashCode;
print(checks);

Convert JSON String to a Dart Map

Open Dart pad and write the following program: (You can also use the Dart compiler for compiling and executing the program)

import 'dart:convert';

void main() {
String data = '{"name": "Nikki", "age": 80, "city": "NYC"}';


  // Convert JSON String to Map

  Map<String, dynamic> myData = json.decode(data);

  // print 
  print(myData);


  myData.forEach(
   (key, value){
    print("$key : $value");
   });



}
{name: Nikki, age: 80, city: NYC}
name : Nikki
age : 80
city : NYC

Learn more about : Dart JSON Parsing

Dart maps provide robust features for efficiently organizing data, making them indispensable in a variety of programming scenarios.

You may also like...