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 AxeMap<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
EasyThe 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 inprices - add a
Bowfor150coins 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),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows4Your Own Classes
A Class for Your DataNamed and Required ParametersFields That Can Be EmptyWidgets From Data With mapFilter a List With whereLook Up in a Map6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler