In this tutorial, we are going to learn two ways to create and design a checkbox in a flutter. We will also learn how to create a custom checkbox in a flutter with an example. We will first design the checkbox widget in a flutter as a checkbox() and then we will create a CheckboxListView in a flutter as a CheckboxListTile().
Flutter Checkbox doesn’t allow the use of text as a title or label so for that we either have to create a CheckboxListTile or create our own Custom Checkbox which you can create from the code below.
By Creating a CheckboxListTile we have to make a checkbox on the right side so, that we have an option as discussed in the video.
Variables
bool? _checkBox = false;
bool? _listTileCheckBox = false;
Types of Checkboxes
// 1. CheckBox
Checkbox(
value: _checkBox,
checkColor: Colors.white,
activeColor: Colors.deepPurple,
tristate: true,
onChanged: (val) {
setState(() {
_checkBox = val;
});
},
),
//2. CheckBoxListTile
CheckboxListTile(
value: _listTileCheckBox,
checkColor: Colors.white,
activeColor: Colors.deepPurple,
tristate: true,
title: Text("Top Product"),
onChanged: (val) {
setState(() {
_listTileCheckBox = val;
});
},
controlAffinity: ListTileControlAffinity.leading, //Leading Checkbox Icon
),
Custom Checkbox in Flutter
To create a custom checkbox in flutter we will use multiple Widgets and also we will create our own custom widget that will return us the Checkbox.
Custom Checkbox Call
//Custom CheckBox WIdget created with love COdingwithTEA
//Call it from your design screen
MyCheckBox(listTileCheckBox: _listTileCheckBox,),
Custom Checkboxe using Row and Stateful Class
class MyCheckBox extends StatefulWidget {
MyCheckBox({Key? key, required this.listTileCheckBox}) : super(key: key);
bool? listTileCheckBox; //To access this variable we use widget. in state class below
@override
State<MyCheckBox> createState() => _MyCheckBoxState();
}
class _MyCheckBoxState extends State<MyCheckBox> {
@override
Widget build(BuildContext context) {
return Align(
//Use Align so that our Container does not get all width as it happens in ListView
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Colors.deepPurple.shade50,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(
checkColor: Colors.white,
activeColor: Colors.deepPurple,
tristate: true,
value: widget.listTileCheckBox,
onChanged: (val) {
setState(() => widget.listTileCheckBox = val);
},
),
const Padding(
padding: EdgeInsets.only(right: 15.0),
child: Text("Top Product"),
),
],
),
),
);
}
}