×

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type.

Every key can occur only once, while the values can be used multiple times.

                   var maps1 = { 1 : ‘one’, 2 : ‘two’, 3 : ‘three’ };

.length is used to get the number of key-value pairs in the map.

It is simple to add a new key-value pair to an existing map just like JavaScript,

                   Maps1[ 4 ] = ‘four’ ;

If you look for a key that isn’t in a map, then it returns null.

Methods of declaring a Dart Map

  1. Using Map literal
  2. Using Map constructor

Using Map Literals

In this method, the key - value pairs are enclosed within the curly braces ‘{  }’, separated by the commas.

Syntax :

var map_name = {key1 : val1, key2 : val2, key3 : val3, ….., keyn : valn} ;

Example :

Consider the following code in Dart to understand the maps implementation using map literals,

void main( )
{
    // declare and define a map named maps1
    var maps1 = { 1 : 'one' , 2 : 'two' , 3 : 'three' } ;
    
    // prints the values of map
    print ( maps1 ) ;
  
    // add new key-value pair to a map
    maps1[ 4 ] = 'four' ;
    print( maps1 ) ;
  
    // prints the length of map
    print( maps1.length ) ;
  
    // trying to print the value of key that exists
    print( maps1[ 3 ] ) ;
  
    // trying to print the value of key that doesn't exist
    print( maps1[ 5 ] ) ;
    
}

Output :

{1: one, 2: two, 3: three}
{1: one, 2: two, 3: three, 4: four}
4
three
null

Using Map( ) constructor

In this method, a map is declared using the map( ) constructor and then initialized with some values.

Syntax :

var map_name = new map(  ) ;  // declaring a map using a map( ) constructor
map_name[ key ] = value ; // initializing the keys with value

Example :

Consider the following code in Dart to understand the maps implementation using Map( ) constructor,

// using map constructor
void main( )
{
// declaring a map using a map( ) constructor
var maps1 = new Map( ) ;
// initializing keys with values
maps1[ 1 ] = 'one' ;
maps1[ 2 ] = 'two' ;
maps1[ 3 ] = 'three' ;
  
print( maps1 ) ;
}

Output :

{1: one, 2: two, 3: three}

Maps Properties

In order to use map properties in the code, one must include dart : core package library that has a class named Map containing the properties.

Here is the list of some of the most used properties :

PropertiesExplanation
KeysIt is used to get all the keys as an iterable object.
valuesIt is used to get a value against the key as an iterable object in a map.
LengthCalculates the number of key-value pairs in a map and returns the same.
isEmptyChecks if there are any key-value pairs in the map and accordingly returns true or false.
isNotEmptyChecks if there is at least one key-value pair in a map and accordingly returns true or false.

Consider the following code that lists all the properties of a Map.

Program

// using map constructor
void main( )
{
  // declaring a map using a map( ) constructor
  var maps1 = new Map( ) ;
  
  // initializing keys with values
  maps1[ 1 ] = 'one' ;
  maps1[ 2 ] = 'two' ;
  maps1[ 3 ] = 'three' ;
  
  print( maps1 );
  
  // using property keys. It prints all the keys of the given map
  print( "\n The keys of the map are : ${ maps1.keys } " ) ;
  
  // using property values. It prints all the values of the given map
  print( "\n The values of the map are : ${ maps1.values } " ) ;
  
  // using property length. It prints the number of key – value pairs in the map
  print( "\n The length of the map is : ${ maps1.length } \n " ) ;
  
  /// using property isEmpty. It returns true or false depending upon the 
  /// availability of key-value pair in the map
  print( maps1.isEmpty ) ;
  print( " \n " ) ;
  /// using property isNotEmpty. It returns true or false depending upon the 
  /// availability of key - value pair in the map
  print( maps1.isNotEmpty ) ;
}

Output

{1: one, 2: two, 3: three}
 The keys of the map are : (1, 2, 3) 
 The values of the map are : (one, two, three) 
 The length of the map is : 3 
 false
  
 true

Maps Functions

1. addAll( )

The addAll( ) function is used to add multiple key – value pairs to the list separated by a comma and enclosed within angular brackets ( < > ).

Implementation = Map.addAll( Map < Key, Value > other ) ;

Here, other denotes a key – value pair that returns a void type.

Program

void main( ) 
{   
  // assigning values to map 
  Map student = { 'name' : 'Yukta', 'Language' : 'Dart' } ;  
  
  // printing values of the map using string interpolation
  print( 'Map Values : ${ student }' ) ;   
     
  // using addAll( ) function to add the entire set of keys - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
}  

Output :

Map Values : {name: Yukta, Language: Dart}
Map after adding  keys - values : {name: Yukta, Language: Dart, Age: 19, College: IIT - D}

2. clear( )

The clear(  ) function is used to remove all key – value pairs from the map.

Implementation = Map.clear( ) ;

Program

void main( ) 
{   
  // assigning values to the map student
  Map student = { 'name' : 'Yukta', 'Language' : 'Dart' } ;  
  
  // printing values of the map using string interpolation
  print( ' Map Values : ${ student } ' ) ;   
     
  // using addAll( ) function to add the entire set of keys - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of the map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
  // using clear( ) function to clear the entire map
  student.clear( ) ;
  
  // printing the values of the map after clearing it
  print( ' Map after clearing  keys - values : ${ student } ' ) ;   
}

Output :

Map Values : {name: Yukta, Language: Dart} 
Map after adding  keys - values : {name: Yukta, Language: Dart, Age: 19, College: IIT - D} 
Map after clearing  keys - values : {}

As you can see clearly, nothing gets printed after clearing the map. This is because the clear( ) function cleared all the key - value pairs in the map.

3. remove ( )

The remove ( ) function is used to remove a single key and its associated value in the map.

Implementation = Map.remove( Object key ) ;

Here, Key refers to the specific entry to be deleted. It returns the value associated with that key.

Program

void main( ) 
{   
  // assigning values to the map student
  Map student = { 'name' : 'Yukta ', 'Language' : 'Dart' } ;  
  
  // printing values of map using string interpolation
  print( ' Map Values : ${ student } ' ) ;   
     
  // using addAll( ) function to add the entire set of key - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of the map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
  // using remove( ) function to remove the ‘ College ’ key from the map
  student.remove( 'College' );
  
  // printing the values of the map after removing the key ‘ College ’
  print( ' Map after removing College key : ${ student } ' ) ;   
}

Output:

Map Values : {name: Yukta , Language: Dart} 
Map after adding  keys - values : {name: Yukta , Language: Dart, Age: 19, College: IIT - D} 
Map after removing College key : {name: Yukta , Language: Dart, Age: 19}

4. forEach( )

The forEach( ) function is used to iterate over the entries of a map.

Implementation = Map.forEach( void f ( K key, V value) ) ;

Here, f (K key, V value) applies f to each key-value pair of the map. Calling f must not add or remove keys from the map


Related Topics

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Lexical Scope and Closure

Lexical Scope : Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to...

2 minutes read.

Dart Static Members

Static Members in Dart Static members are the members of the class declared using the 'static' keyword. the static members have the following characteristics :  All the objects of the class having...

3 minutes read.

Dart Method Overriding

Before understanding method overriding, it is important to clear the concept of polymorphism. Polymorphism is derived from two Greek words 'Poly' which means many and 'morphs' which means many forms....

5 minutes read.

Dart Generators

Synchronous Generator Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate...

5 minutes read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Dart Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 minutes read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart Sets

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart Concurrency

Dart concurrency allows us to run multiple or multiple components of a system at once. It issues several commands at once. Dart provides Isolates as a tool for performing compliance...

2 minutes read.