チップ計算機:人数
CoddyのFlutterジャーニー「アプリをインタラクティブにする」セクションの一部。レッスン 32/34。
請求額は複数人で分担することがよくあります。「カウンターの増減」で作ったカウンターのように、人数とマイナス・プラスの2つのアイコンボタンを含む行を追加しましょう。
支払う人は常に少なくとも1人いるため、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人増えます。マイナスボタンを押すと1人減り、人数が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オンラインコンパイラ