Lesson 12 · 12 of 20
Maps · Dart
Store key-value pairs in a Dart Map: a café menu with [], ??, remove, containsKey, entries and a count of orders.

A map (Map) links keys to values, between braces: {'coffee': 1.40, 'tea': 1.20}. Map<String, double> says the keys are strings and the values numbers with decimals. You look things up by key: menu['coffee'] gives 1.4 (Dart does not print the trailing zero of a double).
Changing a value and adding a new key look the same: menu['tea'] = 1.30 updates the tea and menu['juice'] = 2.50 adds the juice at the end.
If the key does not exist, menu['cake'] gives `null`, not an error. `??` puts a default value in its place: menu['cake'] ?? 0.0. `remove()` deletes a key with its value, `containsKey()` asks whether it exists, and `keys` and `values` give the keys and the values.
`entries` gives each pair as an object with key and value, and the for-in goes through them. padRight(8) pads the name with spaces up to 8 characters so the prices line up in a column.
A very common use is counting: for each drink ordered, counts[drink] = (counts[drink] ?? 0) + 1 adds one to what was there, or starts from zero the first time. <String, int>{} is an empty map with its types.
Code · main.dart
void main() { // A map links keys to values: {key: value}. Map<String, double> menu = {'coffee': 1.40, 'tea': 1.20, 'toast': 2.10}; print('A coffee costs ${menu['coffee']} euros'); // map[key] = value changes a value or adds a new key. menu['tea'] = 1.30; menu['juice'] = 2.50; print(menu); // A missing key gives null; ?? puts a default in its place. print('Cake: ${menu['cake']}, or rather ${menu['cake'] ?? 0.0}'); // remove deletes a key with its value. menu.remove('toast'); print('Toast? ${menu.containsKey('toast')}. Keys: ${menu.keys.toList()}'); // entries gives each key together with its value. for (var item in menu.entries) { print('${item.key.padRight(8)}${item.value.toStringAsFixed(2)}'); } // Counting with a map: one key per drink. var orders = ['coffee', 'tea', 'coffee', 'juice', 'coffee', 'tea']; var counts = <String, int>{}; for (var drink in orders) { counts[drink] = (counts[drink] ?? 0) + 1; } print('Orders: $counts'); print('Different drinks: ${counts.length}');}Output · dart run main.dart
A coffee costs 1.4 euros
{coffee: 1.4, tea: 1.3, toast: 2.1, juice: 2.5}
Cake: null, or rather 0.0
Toast? false. Keys: [coffee, tea, juice]
coffee 1.40
tea 1.30
juice 2.50
Orders: {coffee: 3, tea: 2, juice: 1}
Different drinks: 3Key points
- A map goes between
{ }withkey: valuepairs. m[key] = valuechanges or adds.- A missing key gives
null;??supplies a default. for (var e in m.entries)goes throughe.keyande.value.containsKeychecks whether the key exists.
Exercise
Add a map with the units sold of each drink and print how much each one took in (units times price) and the total for the day.