All lessons

Maps

8 min · Dart

Store values under named keys instead of numbered positions.

Dart · Maps0/5 cleared

Enemy 1 of 5

Key-value pairs with {}

A List is great when position and order matter, but sometimes you want to look a value up by a meaningful name rather than remembering "the score is at position 1." A Map is Dart's key-value collection type, letting you pair each value with a key you choose rather than an automatic numeric index.

You write a Map with curly braces and colons between each key and value: {'name': 'Ada', 'score': 10}. Like var-inferred lists, var player = {'name': 'Ada', 'score': 10}; actually creates a Map<String, Object> (or a more specific type Dart infers from the values) — Dart is still tracking real types behind the scenes even though you didn't spell them out.

You retrieve a value with square brackets and the key: player['name']. If you look up a key that doesn't exist, Dart returns null rather than throwing an error immediately, which is worth knowing since a typo in a key name can silently produce null instead of an obvious crash.

You
Pincer Crab

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada