In this tutorial you will learn about the Dart Map and its application with practical example.
Dart Map
The Map is an object that is used to represents a set of values as key-value pairs. In Map, both keys and values can be of any type of object, it is not necessary that the keys and values both of the same type.. In Map, each key can only occurs once, but the same value can be used multiple times. In Map, each of the value is associated with a unique key, and this key is used to accessed corresponding Map value. The Map can be defined by using curly braces ({ }) and values can be assigned and accessed using square braces ([]).
1 |
var weekDays = {'Day1': 'Mon', 'Day2': 'Tue', 'Day3': 'Wed', 'Day4': 'Thu'}; |
Declaring Map In Dart
In Dart, Maps can be declared in following two ways –
- Using Map Literals
- Using a Map constructor
Declaring Map using Map Literals
In Dart, we can declare a map with a map literal as following –
Syntax:-
1 |
var <map_name> = {key1:value1, key2:value2,..., key_n:value_n} |
Here, a map literal is a list of key-value pairs, separated by commas, surrounded by a pair of curly braces ({ }). A key-value pair is a combination of a key and a value separate by a colon(:).
Example:-
1 |
var weekDays = {'mon': 'Monday', 'tue': 'Tuesday', 'wed': 'Wednesday', 'thu': 'Thursday', 'fri': 'Friday', 'sat': 'Saturday', 'sun': 'Sunday'}; |
Declaring/Initialize Map using Map Constructor
In Dart, we can declare/initialize a map with a map constructor as following –
Syntax :-
Declare an empty map as follows –
1 |
var <map_name> = new Map(); |
Now, lets initialize the map as follows –
1 |
map_name[key] = value; |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
void main() { var weekDays = new Map(); weekDays['mon'] = "Monday"; weekDays['tue'] = "Tuesday"; weekDays['wed'] = "Wednesday"; weekDays['thu'] = "Thursday"; weekDays['fri'] = "Friday"; weekDays['sat'] = "Saturday"; weekDays['sun'] = "Sunday"; print(weekDays); } |
Output:-
1 |
{mon: Monday, tue: Tuesday, wed: Wednesday, thu: Thursday, fri: Friday, sat: Saturday, sun: Sunday} |
Map Properties
Below is a list of properties supported by Dart Map.
Property | Description |
---|---|
Keys |
Returns an iterable object representing all keys in respective map object |
Values |
Returns an iterable object representing all values in respective map object |
Length |
Returns the size of the Map |
isEmpty |
Returns true if the Map is an empty Map |
isNotEmpty |
Returns true if the Map has at least one item. |
Map Methods
Below is a list of commonly used methods supported by Dart Map.
Method | Description |
---|---|
addAll() |
Adds all key-value pairs to this map. |
clear() |
Removes all key-value pairs from the map. |
remove() |
Removes key and its associated value, if present, from the map. |
forEach() |
Iterate through and applies function to each key-value pair of the map. |