Dart Map

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 ([]).

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:-

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:-

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 –

Now, lets initialize the map as follows –

Example:-

Output:-

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.

In this tutorial we have learn about the Dart Map and its application with practical example. I hope you will like this tutorial.