Working with Maps
This guide explores practical map operations through real-world examples including phone directories and user profiles.Basic Map Operations: Phone Directory
Let’s create a phone directory using a map:Searching for Contacts
Check if a contact exists before accessing it:Adding Contacts Dynamically
You can add new entries to a map after creation:Iterating Through Maps
Use theforEach() method to iterate through all key-value pairs:
The
forEach() method takes a function with two parameters: the key and the value.Maps with Dynamic Values
Maps can store different types of values using thedynamic type:
Accessing Different Types
Iterating Dynamic Maps
UseforEach() with dynamic maps just like regular maps:
Complete Examples
Example 1: Phone Directory
Example 2: User Profile
Common Map Operations
Iteration Methods Comparison
Method 1: forEach()
Best for simple iteration:Method 2: for-in with keys
When you need more control:Method 3: entries
When you need both key and value as objects:Use Cases for Different Map Types
String to String
Phone directories, translations, configuration settings
String to int
Ages, scores, quantities, IDs
String to dynamic
User profiles, JSON-like data, flexible configurations
int to String
Error codes to messages, ID to name mappings
Type Safety Considerations
Strongly Typed Maps (Recommended)
Dynamic Maps (Use with Caution)
Practical Patterns
Pattern 1: Safe Access with Default Value
Pattern 2: Conditional Update
Pattern 3: Bulk Operations
Pattern 4: Filter and Transform
Best Practices
- Use appropriate types: Choose
Map<String, int>overMap<String, dynamic>when possible - Check before access: Always use
containsKey()or null-aware operators - Use forEach() for iteration: It’s more concise and readable than manual loops
- Meaningful keys: Use descriptive key names that represent the data
- Handle null values: Maps return null for non-existent keys, so handle this appropriately
Remember: Map keys must be unique, but values can repeat. If you add an existing key, it will update the value, not create a duplicate.