Dart Collections: Dart Map

Dart Collections: Dart Map

ยท

1 min read

In Dart, a Map is a collection that allows you to associate keys with values. Think of it like a real-world dictionary where you look up a word (key) to find its definition (value). In Dart, keys and values can be of any type.

Here's a simple explanation of how to use a Map in Dart:

void main() {
  // Creating a Map
  Map<String, int> ages = {
    'Alice': 25,
    'Bob': 30,
    'Charlie': 22,
  };

  // Accessing values using keys
  print("Alice's age: ${ages['Alice']}");  // Output: Alice's age: 25

  // Adding a new key-value pair
  ages['David'] = 28;

  // Updating the value for an existing key
  ages['Alice'] = 26;

  // Removing a key-value pair
  ages.remove('Bob');

  // Iterating through the Map
  ages.forEach((key, value) {
    print("$key's age: $value");
  });
}

In this example:

  • We create a Map named ages where keys are String (names) and values are int (ages).

  • We access values using keys, update values, add new key-value pairs, and remove a key-value pair.

  • We use forEach to iterate through the Map and print each key-value pair.

In Dart, Map provides a powerful way to organize and retrieve data using keys. Keys are unique within a Map, and they help you efficiently look up associated values.

ย