Tick a Checkbox
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 28 of 34.
A Checkbox works like a Switch: a value: to draw, and an onChanged that you answer with setState.
Checkbox(
value: _agreed,
onChanged: (bool? value) {
setState(() {
_agreed = value ?? false;
});
},
)One difference: its value is a bool?, a bool or null. A checkbox can have a third, empty state, which you will not use here. Since _agreed is a plain bool, turn a possible null into false with ??, as you did with int.tryParse.
A checkbox is often the thing that lets a button be pressed: tick "I agree" and Continue stops being grey.
Challenge
Easy- Make the checkbox tick and untick: store its value in
_agreed. - Grey out
Continueuntil the box is ticked.
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 _agreed = false;
void _continue() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Welcome!')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Rules')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(
value: _agreed,
onChanged: (bool? value) {},
),
const Text('I agree to the rules'),
],
),
const SizedBox(height: 16),
ElevatedButton(onPressed: _continue, child: const Text('Continue')),
],
),
),
);
}
}
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