팁 계산기: 인원
Coddy Flutter 여정의 앱에 상호작용 추가하기 섹션에 포함된 레슨. 34개 중 32번째.
계산서는 여러 사람이 나누어 내는 경우가 많습니다. A Counter Up and Down에서 만든 카운터처럼, 사람 수와 빼기 및 더하기 아이콘 버튼 두 개가 있는 행을 추가하세요.
비용을 내는 사람은 항상 최소 한 명이므로, 1명일 때 빼기 버튼은 회색으로 비활성화됩니다. IconButton은 onPressed: null을 사용해 다른 버튼과 같은 방식으로 비활성화됩니다. 함수가 짧다면 ? : 안에 바로 작성할 수 있습니다.
onPressed: _people > 1
? () {
setState(() {
_people--;
});
}
: null,행에 SizedBox(width: 16)을 넣으면 버튼과 텍스트 사이에 약간의 간격이 생깁니다.
챌린지
쉬움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)}'),
],
),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
앱에 상호작용 추가하기의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러