In Dart programming, Maps are dictionary-like data types that exist in key-value form (known as lock-key). There is no restriction on the type of data that goes in a map data type. Maps are very flexible and can mutate their size based on the requirements. However, it is important to note that all locks (keys) need to be unique inside a map data type.
We can declare Map in two ways:
- Using Map Literals
- Using Map Constructors
Map Literals:
Map can be declared using map literals as shown below:
Syntax:
// Creating the Map using Map Literals
var map_name = { key1 : value1, key2 : value2, ..., key n : value n }
Example 1:
Creating Map using Map Literals
Dart
void main() {
var gfg = { 'position1' : 'Geek' , 'position2' : 'for' , 'position3' : 'Geeks' };
print(gfg);
print(gfg[ 'position1' ]);
print(gfg[0]);
}
|
Output:
{position1: Geek, position2: for, position3: Geeks}
Geek
null
Example 2:
Dart
void main() {
var gfg = { 'position1' : 'Geek' 'for' 'Geeks' };
print(gfg);
print(gfg[ 'position1' ]);
}
|
Output:
{position1: GeekforGeeks}
GeekforGeeks
You have noticed that different strings get concatenated to one.
Example 3:
Inserting a new value into Map
Dart
void main() {
var gfg = { 'position1' : 'Geeks' 'for' 'Geeks' };
print(gfg);
gfg [ 'position0' ] = 'Welcome to ' ;
print(gfg);
print(gfg[ 'position0' ] + gfg[ 'position1' ]);
}
|
Output:
{position1: GeeksforGeeks}
{position1: GeeksforGeeks, position0: Welcome to }
Welcome to GeeksforGeeks
Map Constructors:
Syntax:
// Creating the Map using Map Constructor
var map_name = new Map();
// Assigning value and key inside Map
map_name [ key ] = value;
Example 1:
Creating Map using Map Constructors
Dart
void main() {
var gfg = new Map();
gfg [0] = 'Geeks' ;
gfg [1] = 'for' ;
gfg [2] = 'Geeks' ;
print(gfg);
print(gfg[0]);
}
|
Output:
{0: Geeks, 1: for, 2: Geeks}
Geeks
Example 2:
Assigning same key to different element
Dart
void main() {
var gfg = new Map();
gfg [0] = 'Geeks' ;
gfg [0] = 'for' ;
gfg [0] = 'Geeks' ;
print(gfg);
print(gfg[0]);
}
|
Output:
{0: Geeks}
Geeks
You have noticed that the other two values were simply ignored.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Mar, 2022
Like Article
Save Article