mvasco
mvasco

Reputation: 5101

Switch widget always returning to off position

I am working on a form where I need to use a switch widget.

Here you have the code for it:

bool isSwitched31 = false;
../
Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      'nuevopaciente31'.tr().toString(),
                      style: TextStyle(fontSize: 18),
                    ),
                    Spacer(),
                    Switch(
                      value: isSwitched31,
                      onChanged: (value) {
                        setState(() {
                          isSwitched31 = value;
                          print(isSwitched31);
                        });
                      },
                      activeTrackColor: Colors.lightGreenAccent,
                      activeColor: Colors.green,
                    ),
                  ],
                ),
              ),

enter image description here

When sliding the switch, the print output tells that the swich is on, but it returns always to off position.

What am I doing wrong?

Upvotes: 0

Views: 141

Answers (1)

José David Ortega
José David Ortega

Reputation: 434

If you declare the variable inside the build method, when the widget is rebuilt 'isSwitched31' will be false again. To fix this you have to declare 'isSwitched31' before the build method

Upvotes: 2

Related Questions