I have some problem using a switch inside a bottomsheet. When I tap on it, it doesn't change it's status. Only for the first time, the state changes correctly.
This is the simple code I'm using:
bool _switchValue = false;
@override
Widget build(BuildContext context)
{
return new Scaffold(
body: Center(
child: RaisedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(context: context, builder: (BuildContext context) {
return Container(
child: CupertinoSwitch(
value: _switchValue,
onChanged: (bool value) {
setState(() {
_switchValue = value;
});
},
)
);
});
}
)
)
);
}
Can anyone please help me?
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);
});
}),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With