Menu
CoddyTech

小费计算器:人数

本课属于 Coddy Flutter 学习旅程的“让应用具有交互性”单元。第 32 课,共 34 课。

账单通常由多人分摊。添加一行,显示人数,并放置两个图标按钮:减号和加号,就像你在“计数器加减”中制作的计数器一样。

始终至少有一个人付款,因此人数为 1 时,减号按钮会变成灰色。IconButton 变灰的方式和其他按钮相同,即使用 onPressed: null。函数很短时,你可以直接把它写在 ? : 里面:

onPressed: _people > 1
    ? () {
        setState(() {
          _people--;
        });
      }
    : null,

在这一行中添加一个 SizedBox(width: 16),让按钮和文字之间留出一点距离。

challenge icon

挑战

简单
  • 使用 int _people = 1; 保存人数。
  • 在小费金额下方,添加一个包含 People: 1 的 Row,以及一个带有 Icons.remove 的 IconButton 和一个带有 Icons.add 的 IconButton。
  • 点击加号增加人数。点击减号减少人数,人数为 1 时减号显示为灰色。

亲手试试

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _bill = 0;
  double _tipPercent = 10;

  @override
  Widget build(BuildContext context) {
    final double tip = _bill * _tipPercent / 100;
    return Scaffold(
      appBar: AppBar(title: const Text('Tip Calculator')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              decoration: const InputDecoration(
                labelText: 'Bill',
                border: OutlineInputBorder(),
              ),
              onChanged: (String value) {
                setState(() {
                  _bill = double.tryParse(value) ?? 0;
                });
              },
            ),
            const SizedBox(height: 8),
            Text('Bill: ${_bill.toStringAsFixed(2)}'),
            const SizedBox(height: 24),
            Text('Tip: ${_tipPercent.round()}%', style: const TextStyle(fontSize: 20)),
            Slider(
              value: _tipPercent,
              min: 0,
              max: 30,
              divisions: 6,
              onChanged: (double value) {
                setState(() {
                  _tipPercent = value;
                });
              },
            ),
            Text('Tip amount: ${tip.toStringAsFixed(2)}'),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

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

让应用具有交互性中的所有课

自己练习: Flutter 在线编译器