Skip to main content

Command Palette

Search for a command to run...

Dart Collections: Dart Map

Published
2 min read
Dart Collections: Dart Map
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, a Map is a collection of key-value pairs where each key is unique. It is similar to a dictionary in Python or an associative array in other languages. Dart maps are also called hash maps or dictionaries in other programming languages.

Here's an overview of how to use Dart maps:

Creating a Map:

You can create a map using a map literal or the Map constructor.

// Using map literal
var myMap = {'key1': 'value1', 'key2': 'value2'};

// Using Map constructor
var anotherMap = Map<int, String>();

Adding or Updating Entries:

You can add or update entries in a map by assigning values to keys.

myMap['key3'] = 'value3'; // Adding a new entry
myMap['key1'] = 'updatedValue'; // Updating an existing entry

Accessing Values:

You can access values in a map using their keys.

print(myMap['key1']); // prints: updatedValue

Removing Entries:

You can remove entries from a map using the remove method.

myMap.remove('key2');

Checking for the Presence of a Key:

You can check if a map contains a specific key using the containsKey method.

if (myMap.containsKey('key1')) {
  print('Key1 exists!');
}

Iterating Over a Map:

You can iterate over the entries of a map using a for-in loop.

for (var key in myMap.keys) {
  print('Key: $key, Value: ${myMap[key]}');
}

Map Properties and Methods:

Dart's Map class provides various properties and methods to work with maps efficiently. Some common ones include:

  • length: Returns the number of key-value pairs in the map.

  • isEmpty: Returns true if the map is empty.

  • isNotEmpty: Returns true if the map is not empty.

  • clear(): Removes all key-value pairs from the map.

  • forEach: Executes a function on each key-value pair in the map.

Dart maps are versatile data structures that offer efficient storage and retrieval of key-value pairs. They are commonly used in scenarios where associations between keys and values are needed, such as databases, configuration settings, and more.