If you're working with data in Dart (or Flutter), you'll often use maps. Think of a map like a dictionary or a phone book.
What is a Map?
A map holds information as pairs. Each pair has a unique "key" and a "value" linked to that key. To get the value, you just need the key.
Why Use Maps?
Maps are super fast for looking things up. If you have a list and want to find something, you might have to check every item until you find it (this can take O(n) time). But with a map, finding something using its key is usually instant, no matter how big the map is (this takes O(1) time).
Maps win when you need quick access to data based on a specific identifier.
Types of Dart Maps
Dart gives you a few options for maps:
HashMap
- This is the standard map.
- It doesn't keep the items in any specific order.
LinkedHashMap
- Keeps items in the order they were added.
SplayTreeMap
- Keeps items sorted by their keys. The map is based on a self-balancing binary tree.
Creating Maps
Here are simple ways to make maps:
// A simple Map with String keys and String values
var data = {'name': 'John Doe', 'occupation': 'gardener'};
// A map typed with int keys and String values
var data2 = <int, String>{1: 'sky', 2: 'falcon', 3: 'rock'};
Immutable Maps
Sometimes you want a map that cannot be changed after you create it.
You can use external packages for this, like built_collection
.
Find it here: https://pub.dev/packages/built_collection
This package helps create maps you can't accidentally modify.
Convert List to Map
Turning a list into a map is easy too:
// Transform a list into a map
var listResult = Map.fromIterable([
{'key': 'test1', 'value': 0},
{'key': 'test2', 'value': 1},
{'key': 'test3', 'value': 2}
],
key: (item) => item['key'], // Use the 'key' from each item
value: (item) => item['value'] // Use the 'value' from each item
);
// Or using a more modern syntax (from Dart 2.3+)
var modernResult = { for (var item in [
{'key': 'test1', 'value': 0},
{'key': 'test2', 'value': 1},
{'key': 'test3', 'value': 2}
]) item['key']: item['value'] };
// Or simply using .asMap() for lists where the index is the key
var listItems = ['test1', 'test2', 'test3'];
var mapFromList = listItems.asMap(); // {0: 'test1', 1: 'test2', 2: 'test3'}
Common Map Operations
Maps come with helpful built-in tools:
Adding/Updating Data
You can add new key/value pairs or change existing ones:
var details = {'Usrname':'bruce', 'Password':'mypass'};
// Adding a new entry
details['Uid'] = '3802983209A';
// A safer way to add if the key doesn't exist
details.putIfAbsent('AnotherKey', () => 'SomeValue');
Checking for Keys
See if a map contains a specific key:
// Check if map contains a key (fast O(1))
details.containsKey('Usrname'); // Returns true
details.containsKey('Email'); // Returns false
Transforming Maps
Change the values or keys in a map to create a new map:
var transformedMap = details.map((key, value) => MapEntry(key, '$key:$value'));
// transformedMap might look like {'Usrname': 'Usrname:bruce', 'Password': 'Password:mypass', 'Uid': 'Uid:3802983209A'}
Casting Map Types
Change the type of keys or values:
// Assuming details had int keys and int values
// details.cast<int, int>();
Copying Maps
Make a copy of a map:
var copy = {...details}; // Simple way to create a shallow copy
Updating a Value
Change the value for an existing key:
details.update('bruce', (value) => "joker"); // Changes 'bruce' to 'joker'
Maps are powerful tools in Dart. Knowing how to use them effectively makes your code faster and easier to manage!