What is a Checkbox in Flutter?
A checkbox is a UI element that allows the user to toggle a binary state (checked/unchecked). In Flutter, the Checkbox widget provides a simple square box, while CheckboxListTile combines it with a label, making it easier to use in forms and lists. Checkboxes are ideal for accepting terms, selecting multiple options, or any yes/no choice.
Basic Checkbox Widget
The Checkbox widget requires two main parameters: value (bool) and onChanged (callback). When the user taps, onChanged is called with the new value (the opposite of the current value).
Note that onChanged receives a nullable bool. Always provide a fallback (e.g., ?? false).
Using CheckboxListTile for Better UI
CheckboxListTile wraps a checkbox with a title, subtitle, and optional leading/trailing widgets. It handles the layout and provides a larger tap target. It's perfect for lists and forms.
Customizing Checkbox Appearance
You can customize the checkbox's colors, size, and shape:
activeColor: Color when checked.
checkColor: Color of the check mark.
fillColor: Overrides the fill color (MaterialStateProperty).
visualDensity: Adjusts compactness.
shape: Defines the shape of the checkbox (e.g., RoundedRectangleBorder).
Working with Multiple Checkboxes
When you have multiple checkboxes (e.g., a list of options), you typically store each checkbox's state in a list or map. Use CheckboxListTile inside a ListView or Column.
Checkbox in Forms
To use a checkbox in a Form, you can create a custom FormField or simply manage the checkbox state in the widget and read its value during form submission. For validation, you can check the checkbox's value and show an error message manually.
Common Mistakes
- Forgetting to call
setState– The checkbox won't visually update.
- Forgetting to call
- Not handling
nullinonChanged– If you don't handle nullable, you might get a type error.
- Not handling
- Using
Checkboxwithout a label – Users may not understand its purpose; always include a label or tooltip.
- Using
- Not providing a default value – If
valueis null, the checkbox appears indeterminate (dash).
- Not providing a default value – If
- Over‑customizing – Changing the shape too drastically may confuse users.
Best Practices
- Use
CheckboxListTilewhen you need a label; it provides better UX.
- Use
- For multiple checkboxes, store state in a list of booleans or a map.
- In forms, validate checkboxes and show clear error messages.
- Consider using
ToggleButtonsfor a set of mutually exclusive options if appropriate.
- Consider using
Key Takeaways
Checkboxis the basic toggle widget;CheckboxListTileadds a label and larger tap area.
- Use
valueandonChangedto control the state.
- Use
- Customize colors, shapes, and density for styling.
- For multiple checkboxes, store states in a list.
- For forms, validate manually or create a custom
FormField.
- For forms, validate manually or create a custom