bool and the ? : Operator
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 17 of 34.
Some values are only ever yes or no: is the light on, is the box ticked. Dart's type for them is bool, and its two values are true and false:
bool _isOn = false;The ! in front of a bool flips it, so _isOn = !_isOn; turns true into false and false into true. The lamp's _flip method already does that.
To show one thing or another depending on a bool, use the conditional ? :. It reads as a question: is it on? then this, else that.
Text(_isOn ? 'On' : 'Off')
Icon(Icons.star, color: _isOn ? Colors.red : Colors.black)Before the ? goes something true or false. After it, the value for true, then : and the value for false. It works anywhere a value goes: a text, a color, a size.
Challenge
EasyThe Switch button flips _isOn, but the lamp always looks off. Use ? : so that when _isOn is true the text says The light is on and the bulb is Colors.amber, and otherwise it says The light is off and the bulb is Colors.grey.
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> {
bool _isOn = false;
void _flip() {
setState(() {
_isOn = !_isOn;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Lamp')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.lightbulb, size: 96, color: Colors.grey),
const Text('The light is off'),
const SizedBox(height: 16),
ElevatedButton(onPressed: _flip, child: const Text('Switch')),
],
),
),
);
}
}
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