Checkbox
Checkbox Widget is useful when you want the user to select one or more pieces of information.
Here we explain how to use the Checkbox Widget provided by Flutter and some examples of its applications.
- Checkbox
Checkbox
is a generic simple checkbox widget.
The field can be deactivated by setting the value of onChange
to null.
Checkbox(value: isChecked,onChanged: (val) {if (val == null) return;setState(() {isChecked = val;});}),Checkbox(value: isChecked,onChanged: null)
- CheckboxListTile
CheckboxListTile
is useful when you want to create a Checkbox with a label.
By using title
, you can label a Checkbox.
As with Checkbox()
, the field can be deactivated by setting the value of onChange
to null.
SizedBox(width: 300,child: CheckboxListTile(title: const Text("IconLabel"),subtitle: const Text("Label with description"),secondary: const Icon(Icons.notifications_none_rounded),value: isChecked,onChanged: (value) {if (value == null) return;setState(() {isChecked = value;});},),),
activeColor
: the background color when value=truehoverColor
: the background color when the cursor is hovering
Checkbox Widget allows you to specify colors in detail by changing values such as
Checkbox(activeColor: Colors.blue,hoverColor: Colors.blue[50],value: isChecked,onChanged: (value) {if (value == null) return;setState(() {isChecked = value;});}),
- FormField
The Checkbox Widget can handle input value validation by using a FormField
.
Note that it must be enclosed in a Form()
and the formKey
must be set.
You can freely create validation by changing the value of validator
.
FormField(autovalidateMode: AutovalidateMode.always,initialValue: false,validator: (value) {if (value != true) {return "You need to accept terms!";}return null;},builder: (FormFieldState<bool> state) {return SizedBox(width: 300,child: CheckboxListTile(title: const Text("Agree Terms of Service"),subtitle: state.hasError? Text(state.errorText!,style: const TextStyle(color: Colors.red),): nullvalue: state.value,onChanged: (val) {state.didChange(val);}),);})
For further information, please refer to the official documentation below.