Map in Dart/Flutter
In general, a map is an object that associates keys and values. Both keys and values can be any type of object. Each key occurs only once, but you can use the same value multiple times. Dart support for maps is provided by map literals and the Map type.
Initialize a Map with values
The examples show you how to:
- initialize Map in simple way using { } (curly braces).
- create a Map with all key/value pairs of other Map using from(),for() constructor.
- create a new Map from the given keys and values using
fromIterables()
. - create Map in which keys and values are computed using
fromIterable()
- create a ‘const’ Map using unmodifiable() constructor.
Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
print(map1);
// not specify key-value type
Map map2 = {'zero': 0, 'I': 'one', 10: 'X'};
print(map2);
var map3 = {'zero': 0, 'I': 'one', 10: 'X'};
print(map3);
Output:
{zero: 0, one: 1, two: 2}
{zero: 0, I: one, 10: X}
{zero: 0, I: one, 10: X}
Remember that when we use Map
or var
, the type will always be LinkedHashMap
.
Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
Map map2 = Map.from(map1);
print(map2);
Map map3 = Map.of(map1);
print(map3);
To initialize some values in map3
while using Map.of()
to create a copy of map1
, you can follow these steps:
Map<String, dynamic> map1 = {'key1': 'value1', 'key2': 'value2'};
Map<String, dynamic> map3 = Map.of(map1);
// Initialize values in map3
map3['key3'] = 'value3';
map3['key4'] = 'value4';
print(map3);
// output
{key1: value1, key2: value2, key3: value3, key4: value4};
Create a new Map from the given keys and values using fromIterables().
List<String> letters = ['I', 'V', 'X'];
List<int> numbers = [1, 5, 10];
Map<String, int> map = Map.fromIterables(letters, numbers);
print(map);
Output:
{I: 1, V: 5, X: 10}
Create a new Map from the given keys and values using fromIterable().
List<int> numbers = [1, 2, 3];
Map<String, int> map = Map.fromIterable(
numbers,
key: (k) => 'double ' + k.toString(),
value: (v) => v * 2);
print(map);
Output:
{double 1: 2, double 2: 4, double 3: 6}
Create a ‘const’ Map using unmodifiable() constructor.
Map map = Map.unmodifiable({1: 'one', 2: 'two'});
print(map);
// {1: one, 2: two}
map[3] = 'three';
If you try to modify/add object to the unmodifiable Map, it will throw an error.
Unhandled exception:
Unsupported operation: Cannot modify unmodifiable map
Add item to a Map
There are 2 way to add an item (key-value pair) to a Map:
- using square brackets
[]
- calling
putIfAbsent()
method
Map map = {1: 'one', 2: 'two'};
map[3] = 'three';
print(map);
map.putIfAbsent(4, () => 'four');
print(map);
var threeValue = map.putIfAbsent(3, () => 'THREE');
print(map);
print(threeValue); // the value associated to key, if there is one
Output:
{1: one, 2: two, 3: three}
{1: one, 2: two, 3: three}
{1: one, 2: two, 3: three, 4: four}
three
You can add all key/value pairs of another Map to current Map using addAll()
method.
Map update value by key
The examples show you how to update a Map value using:
- square brackets
[]
update()
methodupdate()
method withifAbsent
to add a new object/entry if the inputkey
is absent
Map map = {1: 'one', 2: 'two'};
map[1] = 'ONE';
print(map);map.update(2, (v) {
print('old value before update: ' + v);
return 'TWO';
});
print(map);map.update(3, (v) => 'THREE', ifAbsent: () => 'addedThree');
print(map);
Output:
{1: ONE, 2: two}
old value before update: two
{1: ONE, 2: TWO}
{1: ONE, 2: TWO, 3: addedThree}
Map map = {1: 'one', 2: 'two'};
map.addAll({3: 'three', 4: 'four', 5: 'five'});
print(map);
Output:
{1: one, 2: two, 3: three, 4: four, 5: five}
Map update value by key
The examples show you how to update a Map value using:
- square brackets
[]
update()
methodupdate()
method withifAbsent
to add a new object/entry if the inputkey
is absent
Map map = {1: 'one', 2: 'two'};
Map map = {1: 'one', 2: 'two'};
map[1] = 'ONE';
print(map);
map.update(2, (v) {
print('old value before update: ' + v);
return 'TWO';
});
print(map);
map.update(3, (v) => 'THREE', ifAbsent: () => 'addedThree');
print(map);
Output:
{1: ONE, 2: two}
old value before update: two
{1: ONE, 2: TWO}
{1: ONE, 2: TWO, 3: addedThree}
Access items from Map
The examples show you way to:
- find the number of key/value pairs using
.length
getter. - check if a Map is empty or not using
.isEmpty
or.isNotEmpty
. - get all keys or values with
keys
&values
property. - get value of specified key in a Map or operator
[]
.
Map map = {1: 'one', 2: 'two'};
print(map.length); // 2
print(map.isEmpty); // false
print(map.isNotEmpty); // true
print(map.keys); // (1, 2)
print(map.values); // (one, two)
print(map[2]); // two
print(map[3]); // null
Remove objects from Map
The examples show you how to:
- remove key-value pair by
key
usingremove()
method. - remove all entries with condition using
removeWhere()
method. - remove all entries from a Map using
clear()
method.
Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'};
Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'};
map.remove(2);
print(map);
map.removeWhere((k, v) => v.startsWith('f'));
print(map);
map.clear();
print(map);
Output:
{1: one, 3: three, 4: four, 5: five}
{1: one, 3: three}
{}
Sort a Map
The example shows you how to sort a Map by values using Map fromEntries()
method and List sort()
method.
Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'};
var sortedMap = Map.fromEntries(
map.entries.toList()
..sort((e1, e2) => e1.value.compareTo(e2.value)));
print(sortedMap);
Output:
{5: five, 4: four, 1: one, 3: three, 2: two}
Map get key by value
Dart Map supports getting value by key, how about the opposite?
We can get key by a specified value using keys
property and List firstWhere()
method.
Map map = {1: 'one', 2: 'two', 3: 'three'};
var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
print(key);
// 2
In conclusion, this tutorial provides a comprehensive overview of working with maps in Dart/Flutter. Maps are essential for associating keys and values in your code, and Dart offers various methods to initialize, add, update, access, remove, and sort map data. Understanding these fundamental map operations is crucial for efficient data manipulation in your Dart and Flutter applications.
For more https://bit.ly/3UoJFYa
Happy Coding!
See you again.