Map is a Data structure, used to store a collection of key and value pairs.

  • Stores Collections of Key and Value pairs.
  • Keys does not duplicate elements, It updates the key and value pair, if the key exists.
  • Dynamic Collection of pairs in size.
  • Keys and Values can contain null values.
  • Keys supported types are Primitive Types(String, int, double, float, boolean),Enum, Class objects.
  • Values supported types are Primitive Types(String, int, double, float, boolean), Enum, Class objects, Map, List, and Functions.

Create a Map Object

You can create map objects, and assign values in multiple ways.

  • use Map Literals You can create a map, and initialize a map with key and value pairs enclosed in {}.
var employee = {'id': '1', 'name': 'abc','salary':6000};

Advantages, You can create an inline variable declaration and assignments

  • Map Constructor

The Map() constructor is used to create an empty map. You can initialize a value using square brackets with assignment syntax map[key]=value

var employee = Map();
employee['id'] = 1;
employee['name'] = 'abc';
employee['salary'] = 6000;
  • use Map.from() function

Map.from() creates a new map from an existing map. Syntax: Map<K, V> Map.from(Map other).

Takes Map as input and returns new Map.

var employee = {'id': '1', 'name': 'abc','salary':6000};
var newMap = Map.from(employee)

Mutation of the original map does not change the new map value.

  • use Map.of function

Map.of() introduced in Dart 2.3 version, Create a new map from an existing map. Syntax: Map<K, V> Map.from(Map other).

Takes Map as input and returns new Map.

  var employee = {'id': '1', 'name': 'abc','salary':6000};
  var newMap = Map.of(employee)
  • Use SplayTreeMap class if you want key elements to be in sorted order, use the SplayTreeMap class.
var employee = SplayTreeMap<String, String>();
employee['id'] = 1;
employee['name'] = 'abc';
employee['salary'] = 6000;

This is another way of creating a Sorted map by keys.

How to access value for a given key in Map

You can access the value using a given key with square bracket syntax.

Syntax: Map[key] Returns value, if key found, else returns null.

// get value for a given key
  print(employee['name']);

Add values to a map

You can assign the value using a given key with a square bracket and assignment syntax.

Syntax: Map[key]=value Update the value, if the key is found, else, create a new key and value pair.

  employee['salary'] = 5000;

Iterate Keys and value pairs

You can iterate map objects in multiple.

One way using forEach function.

It iterates each entity pair and calls a callback function. A pair is an object that contains a key and value.

  myMap.forEach((key, value) {
    print('$key - $value');
  });