Menu
CoddyTech

Máy tính tiền boa: Đặt lại

Thuộc phần Tạo tính tương tác trong hành trình Flutter của Coddy. Bài học 34 trên 34.

Chi tiết cuối cùng là nút Reset để bắt đầu lại: trường trống, tiền boa 10%, 1 người.

Các con số nằm trong State, nên setState có thể đặt chúng về giá trị ban đầu. Trường này hơi phức tạp: nó giữ văn bản riêng, và đặt _bill thành 0 không làm trống trường. Bạn sẽ thấy 40 trong trường, trong khi ứng dụng xử lý giá trị 0. Để làm trống trường, bạn cần một controller, như trong bài Đọc trường bằng controller:

final TextEditingController _billController = TextEditingController();

void _reset() {
  _billController.clear();
  setState(() {
    _bill = 0;
    // và cả tiền boa lẫn số người
  });
}

Trường vẫn giữ onChanged: controller chỉ dùng để _reset có thể xóa nội dung trường. Nhớ giải phóng controller.

challenge icon

Thử thách

Dễ
  • Gán cho trường một TextEditingController có tên _billController, rồi gọi dispose.
  • Ở cuối, thêm một TextButton có nhãn Reset để làm trống trường và đặt lại hóa đơn về 0, tiền boa về 10 và số người về 1.

Tự làm thử

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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Tạo tính tương tác

Tự luyện tập: Trình biên dịch Flutter online