Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In Dart programming, a Map is a dictionary-like data type that exists in the form of key values (called lock keys). There are no restrictions on data types in map data types. Maps are flexible enough to change their size on demand. However, it is important to note that all locks (keys) must be unique within the Map data type.

We can declare maps in two ways:

  1. Using the map
  2. Use the map constructor

Map Literals:

You can declare a map using Map literals, as follows:

Syntax: // Create a map using map text var map_name = {key1: value1, key2: value2,... , key n : value n }Copy the code

Example 1:

Create a map using the Map text

void main() {
// Creating Map using is literals
var gfg = {'position1' : 'Geek'.'position2' : 'for'.'position3' : 'Geeks'};
​
// Printing Its content
print(gfg);
​
// Printing Specific Content
// Key is defined
print(gfg['position1']);
​
// Key is not defined
print(gfg[0]);
}
​
Copy the code

Example 2

void main() {
// Creating Map using is literals
var gfg = {'position1' : 'Geek' 'for' 'Geeks'};
​
// Printing Its content
print(gfg);
​
// Printing Specific Content
// Key is defined
print(gfg['position1']);
}
​
Copy the code

Example 3:

Inserts a new value into the Map

void main() {
// Creating Map
var gfg = {'position1' : 'Geeks' 'for' 'Geeks'};
​
// Printing Its content before insetion
print(gfg);
​
// Inserting a new value in Map
gfg ['position0'] = 'Welcome to ';
​
// Printing Its content after insertion
print(gfg);
​
// Printing Specific Content
// Keys is defined
print(gfg['position0'] + gfg['position1']);
}
​
Copy the code

Map constructor:

Syntax:// Create a Map using Map Constructor
var map_name = new Map(a);// Assign values and keys in the MapMap name [key] =Copy the code

Example 1:

Use the map constructor to create a map

void main() {
// Creating Map using Constructors
var gfg = new Map(a);// Inserting values into Map
gfg [0] = 'Geeks';
gfg [1] = 'for';
gfg [2] = 'Geeks';
​
// Printing Its content
print(gfg);
​
// Printing Specific Content
// Key is defined
print(gfg[0]);
}
​
Copy the code

Example 2:

Assign the same key to different elements

void main() {
// Creating Map using Constructors
var gfg = new Map(a);// Inserting values into Map
gfg [0] = 'Geeks';
gfg [0] = 'for';
gfg [0] = 'Geeks';
​
// Printing Its content
print(gfg);
​
// Printing Specific Content
// Key is defined
print(gfg[0]);
}
​
Copy the code