Dart Maps

Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times. The Map representation is quite similar to the Python Dictionary. The Map can be declared by using curly braces {} ,and each key-value pair is separated by the commas(,). The value of the key can be accessed by using a square bracket([]).

Declaring a Dart Map

Dart Map can be defined in two methods.

  • Using Map Literal
  • Using Map Constructor

The syntax of declaring Dart Map is given below.

Using Map Literals

To declare a Map using map literal, the key-value pairs are enclosed within the curly braces "{}" and separated by the commas. The syntax is given below.

Syntax -

  • var map_name = {key1:value1, key2:value2 [.......,key_n: value_n]}  

Example - 1:

void main() {   

  var student = {'name':'Ali','age':'23'};   

  print(student);   

}  

Output:

{name: Tom, age: 23}

 

Example - 2: Adding value at runtime

void main() {   

  var student = {'name':' tom', 'age':23};   

  student['course'] = 'B.tech';   

  print(student);   

}  

Output:

{name: tom, age: 23, course: B.tech}

 

Explanation -

In the above example, we declared a Map of a student name. We added the value at runtime by using a square bracket and passed the new key as a course associated with its value.

Using Map Constructor

To declare the Dart Map using map constructor can be done in two ways. First, declare a map using map() constructor. Second, initialise the map. The syntax is given below.

Syntax -

  • var map_name = new map()  

After that, initialise the values.

  • map_name[key] = value  

Example - 1: Map constructor

void main() {   

  var student = new Map();   

  student['name'] = 'Ali';   

  student['age'] = 33;   

  student['course'] = 'B.tech';   

  student['Branch'] = 'Computer Science';  

  print(student);   

}  

Output:

{name: Ali, age: 33, course: B.tech, Branch: Computer Science}


Advertisements