Flutter checkbox state change

Viewed 4139

I'm trying to understand how a checkbox works in flutter and not able to understand how the value of isChecked changes from false to true in the below code.

i.e where did we specify that isChecked= true?

bool isChecked = false;

Checkbox(  
  value: isChecked,   
  onChanged: (bool value) {  
    setState(() {  
      isChecked = value;   
      print(isChecked)     // How did value change to true at this point?
    });  
  },  
),  

3 Answers

Lets try to understand the code one by one:

bool isChecked = false;
Checkbox(  
  value: isChecked,   
  onChanged: (bool value) {  
    setState(() {  
      isChecked = value;   
      print(isChecked)     // How did value change to true at this point?
    });  
  },  
),  

You declared a boolean on top and it started with a value of false. Next, you've made a Checkbox. The value of the checkbox is your boolean's value. This is why its value is false at first, a Checkbox with a value of false will have no checkmark. Once you click on your Checkbox, onChanged gets called/triggered. The onChanged:(bool value) passed will be equal to !isChecked. It is going to invert the value of the current value of Checkbox. Now that the value of the checkbox became the opposite of (isChecked) <- current value is false so (bool value) <- value became true, calling setState will tell all the widgets to rebuild. Now that you've changed the value in setState, the CheckBox's value will be true, thus getting checked.

it should be a statefulWidget

class _MyAppState extends State<MyApp> {
 bool isChecked = false; // here
@override
Widget build(BuildContext context) {
  return ...;
 }
}

A checkbox is a type of input component which holds the Boolean value. It is a GUI element that allows the user to choose multiple options from several selections. Here, a user can answer only in yes or no value. A marked/checked checkbox means yes, and an unmarked/unchecked checkbox means no value. Typically, we can see the checkboxes on the screen as a square box with white space or a tick mark. A label or caption corresponding to each checkbox described the meaning of the checkboxes.

In this article, we are going to learn how to use checkboxes in Flutter. In Flutter, we can have two types of checkboxes: a compact version of the Checkbox named "checkbox" and the "CheckboxListTile" checkbox, which comes with a header and subtitle. Checkbox:

value   It is used whether the checkbox is checked or not.
onChanged   It will be called when the value is changed.
Tristate    It is false, by default. Its value can also be true, false, or null.
activeColor It specified the color of the selected checkbox.
checkColor  It specified the color of the check icon when they are selected.
materialTapTargetSize   It is used to configure the size of the tap target.a
Related