Notes: 12. Create & Populate Maps
Dart’s Map documentation: https://api.dart.dev/stable/2.14.4/dart-core/Map-class.html
You’re ready to learn about another extremely useful collection type in Dart: maps.
A map is an unordered collection of pairs, where each pair is composed of a key and a value. They’re useful when you want to look up values by means of an identifier.
For example, here we have a map where the keys are names of animals, and the values are images of animal icons.
Keys in maps must be unique. The same key can’t appear twice in a maps - so we couldn’t have two entries for Cat for example.
How is this different from an list? With a list, you can only fetch a value by its index. The index must be an integer, and all indexes must be sequential. With a map, the keys can be of any type and in no particular order. Let’s try using maps in Dart.
To get started, open a new instance of DartPad at Dartpad.dev. You can create an empty map, almost like you can create an empty list. Whereas a list uses brackets, the map uses braces.
var emptyMap = {};
Now we can create a map, defining the type of the objects that it will contain.
var anotherMap = Map<String, int>();
We use generic syntax to define
In this case, the key is a string and the value is a integer. That the long form of creating maps. The key is the string and the value is the integer. I’ll fill in this dictionary to store some characters and the type of pet they carry around. I’m using emoji here, with the Control-Command-Space keyboard on the Mac, but that can be hard to type so you don’t have to. It’s just for fun.
var namesAndPets = { 'Ron': '🐀 Rat', 'Rincewind': '🛄 Luggage', 'Thor': '🔨 Hammer', 'Goku': '☁️ Flying Nimbus' };
Now try printing out the whole dictionary just to see what that looks like in the console.
print(namesAndPets)
It looks exactly like the declaration of the dictionary keys and values! I’ll add myself, Brian, in here, and I’ll add my pet dog, Cosmos!
namesAndPets['🐶 Cosmos'] = 'Brian';
Notice that we used a subscript to assign a new value. We can use this same syntax for updating a value as well.
namesAndPets['Ron'] = '🦉 Owl';
Now let’s print it out.
print(namesAndPets)
And run the program. Look at that! We have our new addition and update. But what about reading from maps or even iterating over them? I’m glad you asked because we will be taking care of that in the next episode.