Menu
CoddyTech

팁 계산기: 초기화

Coddy Flutter 여정의 앱에 상호작용 추가하기 섹션에 포함된 레슨. 34개 중 34번째.

마지막으로 필요한 것은 처음부터 다시 시작하는 Reset 버튼입니다. 입력란은 비어 있고, 팁은 10%, 인원수는 1명으로 설정됩니다.

숫자는 State에 있으므로 setState로 원래 값으로 되돌릴 수 있습니다. 입력란은 까다로운 부분입니다. 입력란은 자체 텍스트를 유지하므로 _bill을 0으로 설정해도 입력란이 비워지지 않습니다. 앱에서는 0을 사용하지만 입력란에는 40이 표시되는 상황이 생깁니다. 입력란을 비우려면 Read a Field With a Controller에서처럼 컨트롤러가 필요합니다.

final TextEditingController _billController = TextEditingController();

void _reset() {
  _billController.clear();
  setState(() {
    _bill = 0;
    // 그리고 팁과 인원수도
  });
}

입력란은 onChanged를 그대로 사용합니다. 컨트롤러는 _reset에서 입력란을 비울 수 있도록 두는 것뿐입니다. 컨트롤러를 해제하는 것도 잊지 마세요.

challenge icon

챌린지

쉬움
  • 필드에 _billController라는 이름의 TextEditingController를 지정하고, 이를 해제하세요.
  • 아래쪽에 필드를 비우고 금액을 0, 팁을 10, 인원수를 1로 되돌리는 Reset 레이블의 TextButton을 추가하세요.

직접 해보기

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 컴파일러