Checkbox Widget

The Checkbox widget in Flutter is used to represent a two-state selection model, i.e., selected or not selected. It’s a Material Design style checkbox that shows a check mark when selected and an empty box when not selected.

The constructor of Checkbox widget takes several parameters, including:

  • value: A boolean value that determines whether the checkbox is checked or unchecked. This value can be updated using a StatefulWidget.
  • onChanged: A callback function that is called when the checkbox value changes. The new value is passed to this function as a parameter.
  • activeColor: The color of the checkbox when it is checked.
  • checkColor: The color of the check mark when the checkbox is checked.
  • visualDensity: Defines the compactness of the checkbox, which affects the size and spacing of its elements.

Here’s an example of using the Checkbox widget:

bool _isChecked = false;

Checkbox(
  value: _isChecked,
  onChanged: (bool newValue) {
    setState(() {
      _isChecked = newValue;
    });
  },
  activeColor: Colors.blue,
  checkColor: Colors.white,
)

In this example, the _isChecked boolean variable is used to determine the initial value and store the updated value of the checkbox. The onChanged function is used to update this variable when the checkbox value changes. The activeColor and checkColor parameters are used to customize the appearance of the checkbox.

Examples with different constructors

  1. Checkbox: The most basic constructor that creates a simple checkbox widget.
Checkbox(
  value: true,
  onChanged: (bool value) {},
)
  1. CheckboxListTile: A constructor that creates a ListTile with a checkbox. It’s useful when you need to add additional text or a subtitle to the checkbox.
CheckboxListTile(
  title: Text('Checkbox'),
  subtitle: Text('This is a checkbox'),
  value: true,
  onChanged: (bool value) {},
)
  1. CheckboxButton: A constructor that creates a checkbox with a text label that can be positioned to the left or right of the checkbox.
CheckboxButton(
  text: 'Checkbox',
  value: true,
  onChanged: (bool value) {},
)

Overall, the Checkbox widget provides a simple and effective way to add checkboxes to your app’s UI.