Dart Map length
Syntax & Examples


Syntax of Map.length

The syntax of Map.length property is:

 int length 

This length property of Map the number of key/value pairs in the map.

Return Type

Map.length returns value of type int.



✐ Examples

1 Get length of non-empty map

In this example,

  1. We create a map named map1 with key/value pairs {'apple': 1, 'banana': 2, 'cherry': 3}.
  2. We then retrieve the length of the map using the length property.
  3. We print the result to standard output.

Dart Program

void main() {
  Map<String, int> map1 = {'apple': 1, 'banana': 2, 'cherry': 3};
  int mapLength = map1.length;
  print('Map length: $mapLength');
}

Output

Map length: 3

2 Get length of empty map

In this example,

  1. We create an empty map named map2.
  2. We then retrieve the length of the map using the length property.
  3. We print the result to standard output.

Dart Program

void main() {
  Map<int, String> map2 = {};
  int mapLength = map2.length;
  print('Map length: $mapLength');
}

Output

Map length: 0

3 Get length of map with single entry

In this example,

  1. We create a map named map3 with a single key/value pair {'name': 'John'}.
  2. We then retrieve the length of the map using the length property.
  3. We print the result to standard output.

Dart Program

void main() {
  Map<String, String> map3 = {'name': 'John'};
  int mapLength = map3.length;
  print('Map length: $mapLength');
}

Output

Map length: 1

Summary

In this Dart tutorial, we learned about length property of Map: the syntax and few working examples with output and detailed explanation for each example.