Dart Maps Explained: Unlock the Power of Key-Value Pairs

Dart Maps

Imagine a special locker room at your school. That special locker room is what we call a Map in Dart.

1. The Super Special Locker (Key-Value Pairs) in Dart Maps

In a regular List (or toy box), you find things by counting: “First item,” “Second item,” “Third item.”

In Dart Maps, you find things by Name Tag. Each locker has two important parts that stick together like best friends:

  • The Key (The Name Tag): This is the unique name on the outside of the locker. It must be unique—no two lockers can have the exact same name tag!
  • The Value (The Treasure Inside): This is the special thing stored inside the locker, like a favorite toy or a snack.

We put these pairs together using a colon (:).

Key (The Name Tag)Value (The Treasure Inside)
'red'1
'blue'2
'green'3

2. Making the Map (Creating a Map)

To make this special locker room in Dart, we use curly braces {} and put the Name Tag and the Treasure together:

var colors = {
  'red': 1,
  'blue': 2,
  'green': 3
};

This tells Dart: “When I ask for the locker named ‘red’, give me the number 1!”

3. Finding the Treasure (Accessing Values)

The best part of a Map is finding the treasure super fast! You don’t have to count. You just yell out the Name Tag:

The Trick: You use the Map’s name, and then the Key in square brackets [].

var colors = {'red': 1, 'blue': 2, 'green': 3};

// I want the treasure from the 'blue' locker!
print(colors['blue']); // Output: 2

// I want the treasure from the 'red' locker!
print(colors['red']);  // Output: 1

4. Changing the Locker Room (Modifying a Map)

You can always change what’s in the Map!

What you want to doDart Code
Add a New Locker: Use a new Name Tag and give it a new Treasure.colors['yellow'] = 4;
Change a Treasure: Use an old Name Tag and give it a new Treasure.colors['red'] = 100; (Now ‘red’ holds 100 instead of 1)
Remove a Locker: Take out a Name Tag and its Treasure.colors.remove('green');

In short:

A Map in Dart is a collection where everything is saved as a pair: a Key (the unique label, like a name) and a Value (the item being stored). This lets you look up the item you want quickly and easily, without having to count.

The following video further illustrates how to work with Maps in Dart: Maps In Dart – Learn Dart Programming 5.

Leave a Reply

Your email address will not be published. Required fields are marked *