팁 계산기: 1인당 금액
Coddy Flutter 여정의 앱에 상호작용 추가하기 섹션에 포함된 레슨. 34개 중 33번째.
이제 앱의 답, 즉 각 사람이 얼마를 내는지 알아봅시다. 이는 나머지 내용에서 이어지므로 tip 뒤에 build의 맨 위에 final을 하나 더 추가합니다:
final double each = (_bill + tip) / _people;괄호가 중요합니다. Dart는 수학 시간에 배우는 것처럼 더하기보다 나누기를 먼저 하므로, _bill + tip / _people이라고 하면 팁만 나누게 됩니다.
금액 앞에 달러 기호를 붙이고, Dart 문자열에서 $는 변수를 시작합니다. 기호 자체를 표시하려면 앞에 백슬래시를 붙이세요: \$. 그런 다음 실제 ${...}가 이어집니다:
Text('Each person pays \$${each.toStringAsFixed(2)}')챌린지
쉬움build의 맨 위에서 각 사람이 낼 금액을 계산하세요. 청구 금액에 팁을 더한 뒤 사람 수로 나눕니다.- 맨 아래에
28크기와 굵은 글꼴로 표시하세요. 청구 금액이 40이고 팁이 10%이며 사람이 1명일 때는Each person pays $44.00입니다.
직접 해보기
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;
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++;
});
},
),
],
),
],
),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
앱에 상호작용 추가하기의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러