Menu
CoddyTech

小费计算器:重置

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

最后一步是添加一个“重置”按钮,从头开始:清空输入框,小费为 10%,人数为 1。

这些数字都在 State 中,因此 setState 可以将它们恢复到原来的值。输入框比较棘手:它会保留自己的文本,把 _bill 设为 0 并不会清空输入框。你会看到输入框中显示 40,但应用使用的值是 0。要清空输入框,需要使用控制器,就像“使用控制器读取输入框”中那样:

final TextEditingController _billController = TextEditingController();

void _reset() {
  _billController.clear();
  setState(() {
    _bill = 0;
    // 还有小费和人数
  });
}

输入框仍然保留它的 onChanged:控制器的作用只是让 _reset 能够清空输入框。记得释放它。

challenge icon

挑战

简单
  • 为该字段指定一个名为 TextEditingController 的控制器 _billController,并释放它。
  • 在底部添加一个标有 Reset 的 TextButton,清空字段,并将账单金额重置为 0、小费重置为 10、人数重置为 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;
  int _people = 1;

  @override
  Widget build(BuildContext context) {
    final double tip = _bill * _tipPercent / 100;
    final double each = (_bill + tip) / _people;
    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)}'),
            const SizedBox(height: 24),
            Row(
              children: [
                Text('People: $_people', style: const TextStyle(fontSize: 20)),
                const SizedBox(width: 16),
                IconButton(
                  icon: const Icon(Icons.remove),
                  onPressed: _people > 1
                      ? () {
                          setState(() {
                            _people--;
                          });
                        }
                      : null,
                ),
                IconButton(
                  icon: const Icon(Icons.add),
                  onPressed: () {
                    setState(() {
                      _people++;
                    });
                  },
                ),
              ],
            ),
            const SizedBox(height: 24),
            Text(
              'Each person pays \$${each.toStringAsFixed(2)}',
              style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

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

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

自己练习: Flutter 在线编译器