Switch in bottomsheet not changing status on Flutter
You need to put the switch in its own StatefulWidget
and use a callback to return the value to your main class. A bottom sheet uses a different context so calling setState
in your example above doesn't work.
class _MyHomePageState extends State<MyHomePage> {
bool _switchValue = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return BottomSheetSwitch(
switchValue: _switchValue,
valueChanged: (value) {
_switchValue = value;
},
);
},
);
},
),
),
),
);
}
}
class BottomSheetSwitch extends StatefulWidget {
BottomSheetSwitch({@required this.switchValue, @required this.valueChanged});
final bool switchValue;
final ValueChanged valueChanged;
@override
_BottomSheetSwitch createState() => _BottomSheetSwitch();
}
class _BottomSheetSwitch extends State<BottomSheetSwitch> {
bool _switchValue;
@override
void initState() {
_switchValue = widget.switchValue;
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: CupertinoSwitch(
value: _switchValue,
onChanged: (bool value) {
setState(() {
_switchValue = value;
widget.valueChanged(value);
});
}),
);
}
}
Use StatefulBuilder to change status of switch inside BottomSheet
showModalBottomSheet(
context: context, builder: (BuildContext context) {
return Container(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
return CupertinoSwitch(
value: _switchValue,
onChanged: (val) {
stateSetter(() => _switchValue = val);
},);
},
),
)
});