Show and Hide a Widget
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 20 of 34.
To show a widget only sometimes, put an if in front of it, right inside the list of children:
Column(
children: [
const Text('Question'),
if (_showHint) const Text('A hint'),
],
)When _showHint is false, the hint is not hidden: it is not in the list at all, and the widgets after it move up to fill the space. When it is true, the hint is there. This if has no braces and no else: it is the list version of if, like the for you used to build a list of widgets.
A button that shows and hides something usually flips a bool with ! and changes its own label with ? :.
Challenge
EasyThe answer Paris is always on the screen. Show it only when _showAnswer is true. The button already flips _showAnswer; make its label say Show answer when the answer is hidden and Hide answer when it is shown.
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 _showAnswer = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Quiz')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('What is the capital of France?', style: TextStyle(fontSize: 20)),
const Text('Paris', style: TextStyle(fontSize: 32)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
setState(() {
_showAnswer = !_showAnswer;
});
},
child: const Text('Show answer'),
),
],
),
),
);
}
}
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