Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter checkbox state change

Tags:

flutter

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?
    });  
  },  
),  

like image 454
Jag99 Avatar asked Nov 25 '25 10:11

Jag99


1 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.

like image 63
Uni Avatar answered Nov 27 '25 00:11

Uni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!