Home > Mobile >  Flutter: checkbox and its state in the Form
Flutter: checkbox and its state in the Form

Time:11-08

I am new to flutter (and programming). I don't understand why my code is not working properly, meaning I don't understand why the value and the representation are not changing. I'd appreciate any advice.

The code:

Widget build(BuildContext context) {
   bool isChecked = false;

<Page and Form code>

Row(
  children: [
    Checkbox(
      checkColor: Colors.white,
      activeColor: Colors.red,
      visualDensity: VisualDensity.compact,
      value: isChecked,
      onChanged: (value) {
        setState(() {
          isChecked = !isChecked;
          //state.didChange(value);
          print(isChecked);
        });
                   
    const Text(
      'I would like to receive newsletter and promo.',
      softWrap: true,
    ),
   ],
 ),

CodePudding user response:

You are declaring the variable isChecked within the build method, when you call setState you tell the widget to run the build method again, so isChecked gets assigned to be false again.

To solve this, simply make the isChecked variable a class variable:

From this:

class _MyState extends State<MyWidget> {
...
  @override
  Widget build(BuildContext) {
    bool isChecked = false;
    ...
  }
}

to this:

class _MyState extends State<MyWidget> {
...
  bool isChecked = false;

  @override
  Widget build(BuildContext) {
    ...
  }
}
  • Related