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,
),
],
),
),
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?
CodePudding user response:
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