Menu
CoddyTech

チップ計算機:一人当たり

CoddyのFlutterジャーニー「アプリをインタラクティブにする」セクションの一部。レッスン 33/34。

ここで、アプリの目的である、各人が支払う金額を求めます。これはほかのすべてから導けるので、tipの後、buildの先頭にもう1つfinalを追加します。

final double each = (_bill + tip) / _people;

括弧は重要です。Dartでは算数の授業と同じように、足し算より先に割り算をするため、_bill + tip / _peopleだとチップだけが分割されてしまいます。

金額にはドル記号を付けます。Dartの文字列では、$は変数の始まりを表します。記号そのものを表示するには、その前にバックスラッシュを付けます。つまり\$です。その後に実際の${...}が続きます。

Text('Each person pays \$${each.toStringAsFixed(2)}')
challenge icon

チャレンジ

簡単
  • 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++;
                    });
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

アプリをインタラクティブにするのすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ