I’ve been meaning to document a couple of tips/tricks about Dart hashmaps for some time. It’s things I’m often looking up and/or double checking which would be better to just have on my blog.
First up, I often want to convert a list into a hashmap. You’d think there’d be a function like in some languages like toMap
or something along those lines which would take a lambda function defining the mapping. You will see a method on the Map classes called fromIterable
which does something along those lines but that’s not the easiest way to do it. The easiest way is to do a one line for-each loop initializing the hashmap like follows:
final people = [
Person(id: 1, name: 'Pat'),
Person(id: 2, name: 'Terry'),
Person(id: 3, name: 'Sam'),
];
final peopleMap = {for (final p in people) p.id: p};
print(people);
print(peopleMap);
outputs:
[Person{id: 1, name: Pat}, Person{id: 2, name: Terry}, Person{id: 3, name: Sam}]
{1: Person{id: 1, name: Pat}, 2: Person{id: 2, name: Terry}, 3: Person{id: 3, name: Sam}}
where the Person
class is defined as:
class Person {
final int id;
final String name;
Person({required this.id, required this.name});
@override
String toString() {
return 'Person{id: $id, name: $name}';
}
}
Second up, is the fact that if you use the default hashmap it preserves the insertion order. So this code:
final numbers = <num, String>{};
numbers[1] = 'one';
numbers[2] = 'two';
numbers[3] = 'three';
print(numbers);
will print:
{1: one, 2: two, 3: three}
It’s insertion order not update order though, so if the second entry was updated with a capitalized version it’d still be in the original order. To have it an update be removed and placed at the end you have to remove/insert manually:
numbers[2] = 'Two';
print(numbers);
prints:
{1: one, 2: Two, 3: three}