A Map in Dart is an object that associates keys with values. It is very similar to a real-world dictionary (where a word is the "key" and the definition is the "value") or a JSON object. Keys must be unique, but values can be duplicated.
1. Creating Maps
Maps can be declared using literal syntax with curly braces {} or by explicitly defining the types for both the Key and the Value.
Declaration Syntax
1// Type Inference (Map<String, String>)2var capitals = {3 'USA': 'Washington D.C.',4 'France': 'Paris',5 'Japan': 'Tokyo'6};7 8// Explicit Typing (Map<String, int>)9Map<String, int> scores = {10 'Alice': 95,11 'Bob': 88,12 'Charlie': 9213};14 15// Empty Map16var emptyMap = {}; // Dart infers this as Map<dynamic, dynamic>17Map<String, dynamic> userProfile = {};HintThe structure is always key: value. While keys are usually Strings, they can be numbers or other objects.
2. Accessing and Modifying Data
You access values using the subscript operator [] with the key. You can also add new entries or update existing ones using the same operator.
Reading and Writing
1var inventory = {'Apples': 5, 'Oranges': 10};2 3// Reading a value4print(inventory['Apples']); // Output: 55 6// Adding a new item7inventory['Bananas'] = 12;8 9// Updating an existing item10inventory['Apples'] = 3; // Value changes from 5 to 311 12print(inventory); // {Apples: 3, Oranges: 10, Bananas: 12}HintNote: If you assign a value to a key that already exists, it updates the value. If the key does not exist, it adds a new entry.
3. Null Safety in Maps
A critical concept in Dart Maps is that accessing a key returns a "nullable" type. If the key is missing, Dart returns null rather than crashing.
Handling Missing Keys
1var scores = {'Alice': 100};2 3print(scores['Bob']); // Output: null4 5// Handling the null safely6int? bobScore = scores['Bob']; // Must be nullable int?7 8// Using the '!' operator if you are SURE the key exists (Risky)9// int score = scores['Alice']!; 10 11// Best practice: Check if key exists first12if (scores.containsKey('Bob')) {13 print('Bob score is ${scores['Bob']}');14} else {15 print('Bob did not play.');16}HintLooking up a key is one of the most common sources of null values in Dart programming. Always handle the possibility that a key might be missing.
4. Map Properties and Methods
Dart Maps include useful properties to iterate over data or check the map's status.
Useful Methods
1var user = {2 'name': 'Houssam',3 'role': 'Admin',4 'active': true5};6 7print(user.length); // 38print(user.keys); // (name, role, active)9print(user.values); // (Houssam, Admin, true)10print(user.isEmpty); // false11 12// Removing an item13user.remove('role');14print(user); // {name: Houssam, active: true}HintUsing .keys or .values returns an Iterable, which you can loop over easily.
Loot collected
Key takeaways- Maps store data in
key: valuepairs. - Keys must be unique; values can be duplicates.
- Accessing a value:
map[key]. If the key doesn't exist, it returnsnull. - Use
.containsKey(key)to check for existence before accessing data. - The literal
{}creates a Map, not a Set.
Side quests
Practice exercises
Exercise 1: Phonebook
Create a Map called phonebook storing two names (Strings) and phone numbers (Integers).
Reveal solutionHide solution
1Map<String, int> phonebook = {'John': 123456, 'Jane': 987654};Exercise 2: Updating Inventory
Given var stock = {"pens": 5};, write code to add 10 "pencils" and update "pens" to 3.
Reveal solutionHide solution
1stock['pencils'] = 10; stock['pens'] = 3;Exercise 3: Safe Lookup
Write code that prints the value for key "pizza" from a map menu, but prints "Not found" if it is missing.
Reveal solutionHide solution
1var price = menu['pizza'];2if (price != null) print(price); else print('Not found');