Menu
CoddyTech

Look Up in a Map

Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 17 of 33.

A Map stores pairs: a key you look up, and the value that goes with it, like a word and its meaning in a dictionary. Here each item in a game shop has a price:

Map<String, int> prices = {
  'Sword': 120,
  'Potion': 25,
};

prices['Sword']   // 120
prices['Axe']     // null: there is no Axe

Map<String, int> says the keys are strings and the values are ints. Look a value up with its key in square brackets. A key the map does not have gives null.

Add a pair with prices['Bow'] = 150;, or write it into the map. prices.keys is every key, in the order they were added, ready for a for.

challenge icon

Challenge

Easy

The shop lists its items, but no prices. Show the prices, and stock one more item:

  • show each item's price at the end of its row, such as 120 coins, looked up in prices
  • add a Bow for 150 coins to the map

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final Map<String, int> prices = {
      'Sword': 120,
      'Shield': 90,
      'Potion': 25,
    };
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Shop')),
        body: ListView(
          children: [
            for (String item in prices.keys)
              ListTile(
                title: Text(item),
              ),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lists and Screens

Practice on your own: Online Flutter compiler