チップ計算機:リセット
CoddyのFlutterジャーニー「アプリをインタラクティブにする」セクションの一部。レッスン 34/34。
最後の仕上げは、最初からやり直すためのResetボタンです。入力欄は空、チップは10%、人数は1人に戻します。
数値は State にあるので、setStateで元に戻せます。やっかいなのは入力欄です。入力欄は独自にテキストを保持しており、_billを0に設定しても空にはなりません。アプリが0を使っているのに、入力欄には40が表示されることになります。入力欄を空にするには、「コントローラーを使った入力欄の読み取り」のように、コントローラーが必要です。
final TextEditingController _billController = TextEditingController();
void _reset() {
_billController.clear();
setState(() {
_bill = 0;
// チップと人数も
});
}入力欄のonChangedはそのままです。コントローラーは_resetから入力欄を空にするためだけに使います。忘れずに破棄しましょう。
チャレンジ
簡単- フィールドに
_billControllerという名前のTextEditingControllerを設定し、破棄してください。 - 一番下に
ResetというラベルのTextButtonを追加し、フィールドを空にして、請求額を0、チップを10、人数を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;
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),
),
],
),
),
);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
アプリをインタラクティブにするのすべてのレッスン
自分で練習してみよう: Flutterオンラインコンパイラ