Tip Calculator: The Tip
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 31 of 34.
Next, the tip. A Slider from 0 to 30 percent in steps of 5 picks it, and the app shows how much money that is.
Keep the percent in the State as a double starting at 10. The tip amount is not something you store: it follows from the bill and the percent, so work it out at the top of build, as a final:
final double tip = _bill * _tipPercent / 100;Every setState, from the field or from the slider, builds the screen again, and tip is worked out again with the new values.
Challenge
Easy- Under the bill, show
Tip: 10%and aSliderfrom0to30with6divisions, starting at 10. - Under the slider, show
Tip amount: 4.00for a bill of 40, with two decimals.
Try it yourself
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;
@override
Widget build(BuildContext context) {
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)}'),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
5Decisions
bool and the ? : OperatorDecisions With if and elseAnd, Or and Not in DartShow and Hide a WidgetGrey Out a Button8Project: Tip Calculator
Tip Calculator: The BillTip Calculator: The TipPractice on your own: Online Flutter compiler