Map — Key-Value Pairs & JSON
Map: Key-Value Pairs & JSON
A Map is an unordered collection of key-value pairs. Keys must be unique, but values can be duplicated. Maps are highly versatile and are the primary data structure used to represent JSON payloads in web APIs.
Declaring Maps
You can declare a Map using curly braces {} or the Map class constructor.
dartvoid main() { // Using Map Literal syntax var ages = { 'Alice': 25, 'Bob': 30, 'Charlie': 35, }; // Inferred as Map<String, int> // Explicit type declaration Map<String, String> capitals = { 'India': 'New Delhi', 'USA': 'Washington D.C.', }; // Empty Map declaration var emptyMap = <String, int>{}; Map<int, String> statusCodes = Map(); }
Map Operations (CRUD)
1. Create & Update
To add a new key-value pair or update an existing value, use the square bracket index operator [].
dartvoid main() { var scores = {'Math': 90}; scores['Science'] = 95; // Create new key scores['Math'] = 92; // Update existing key print(scores); // {Math: 92, Science: 95} }
2. Read
Access a value by passing its key to the bracket operator. If the key doesn't exist, it returns null.
dartvoid main() { var capitals = {'India': 'New Delhi'}; print(capitals['India']); // New Delhi print(capitals['France']); // null // Checking key existence if (capitals.containsKey('France')) { print("Found France!"); } }
3. Delete
Use the remove() method to delete a key-value pair.
dartvoid main() { var user = {'id': 1, 'name': 'John', 'role': 'Admin'}; user.remove('role'); print(user); // {id: 1, name: John} }
Iterating Over Maps
You can iterate over a map using forEach(), a for-in loop with keys, values, or entries.
dartvoid main() { var currency = {'USD': 'Dollar', 'EUR': 'Euro', 'INR': 'Rupee'}; // Method 1: Using forEach currency.forEach((code, name) { print("$code stands for $name"); }); // Method 2: Using for-in over entries for (var entry in currency.entries) { print("${entry.key} is the code for ${entry.value}"); } }
Maps and JSON
JSON (JavaScript Object Notation) maps directly to Dart's Map<String, dynamic> type. When you fetch data from an API, you parse the raw JSON string into a Dart Map to access properties.
dartimport 'dart:convert'; void main() { // A raw JSON string from a server String jsonString = '{"name": "Alice", "id": 101, "isActive": true}'; // Decode JSON string to Map Map<String, dynamic> userMap = jsonDecode(jsonString); print("User Name: ${userMap['name']}"); // Alice print("User ID: ${userMap['id']}"); // 101 }
Summary
- A Map stores data as key-value associations.
- Keys must be unique; lookup by key is extremely fast (O(1)).
- JSON payloads are represented as
Map<String, dynamic>in Dart. - Use
jsonDecode()fromdart:convertto convert JSON strings into Dart Maps.