Menu
CoddyTech

在 Map 中查找

本课属于 Coddy Flutter 学习旅程的“列表和屏幕”单元。第 17 课,共 33 课。

Map 用来存储键值对:你可以通过 键 查找对应的 值,就像字典中的单词和释义。这里,游戏商店中的每件物品都有一个价格:

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

prices['Sword']   // 120
prices['Axe']     // null:没有 Axe

Map<String, int> 表示键是字符串,值是 int。用方括号中的键查找值。如果映射中没有这个键,就会得到 null。

使用 prices['Bow'] = 150; 添加一个键值对,也可以直接把它写入映射。prices.keys 包含所有键,顺序与添加顺序一致,可用于 for 循环。

challenge icon

挑战

简单

商店列出了商品,但没有显示价格。显示价格,并再上架一件商品:

  • 在每一行末尾显示商品的价格,例如 120 coins,从 prices 中查找
  • 在映射中添加一把售价为 150 coins 的 Bow

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

列表和屏幕中的所有课

自己练习: Flutter 在线编译器