Decisions With if and else
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 18 of 34.
if runs code only when something is true. else runs other code when it is not:
if (_count < 10) {
_count++;
} else {
print('Full');
}What goes in the parentheses is a comparison, which is a bool: true or false.
a == b: a equals b (two equals signs; one is for giving a variable a value)a != b: a does not equal ba < banda > b: less than, greater thana <= banda >= b: less than or equal, greater than or equal
Watch the edge: with 8 glasses, _glasses < 8 is false, but _glasses <= 8 is still true and lets a ninth glass through.
Inside the State class, context is there in every method, not only in build, so a method can show a SnackBar too.
Challenge
EasyEight glasses of water a day is enough. Change _drink so that it adds a glass only while there are fewer than 8. Otherwise it shows a SnackBar that says That is enough for today.
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> {
int _glasses = 0;
void _drink() {
setState(() {
_glasses++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Water')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Glasses today: $_glasses', style: const TextStyle(fontSize: 24)),
const SizedBox(height: 16),
ElevatedButton(onPressed: _drink, child: const Text('Drink a glass')),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
Practice on your own: Online Flutter compiler