My setup:
class Start_Page extends StatefulWidget {
@override
StartPageState createState() => StartPageState();
}
class StartPageState extends State<Start_Page> {
@override
Widget build(BuildContext context){
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return Scaffold(
body: Container(
child: ElevatedButton(
style: ButtonStyle(),
onPressed: () {
createUserModalBottomSheet(context);
},
child: Text("Start"),
)
)
);
}
}
void createUserModalBottomSheet(context){
showModalBottomSheet(context: context, builder: (BuildContext bc) {
return Container(
child: Switch(value: true, onChanged: (value) => {value = !value}, activeColor:
Colors.grey)
);
}
}
The Problem is that the switch won't change his value. The Modalbottomsheet appears but won't update changes/states. Does anyone know a solution?
CodePudding user response:
Use StatefulBuilder
to update UI inside showModalBottomSheet
. Second issue is you need to use a bool variable to hold value.
class StartPageState extends State<Start_Page> {
bool switchValue = false;
///......
void createUserModalBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return StatefulBuilder(
builder: (context, setStateSB) => Container(
child: Switch(
value: switchValue,
onChanged: (value) {
setState(() {
// update parent UI
switchValue = value;
});
setStateSB(() {
// update inner dialog
switchValue = value;
});
},
activeColor: Colors.grey),
),
);
});
}
@override
Widget build(BuildContext context) {
.........