Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Switch doesn't work in Modalbottomsheet

My setup:

class Start_Page extends StatefulWidget {
   @override
   StartPageState createState() => StartPageState();
}

class StartPageState extends State<Start_Page> {
   @override
   Widget build(BuildContext context){
     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?

like image 865
pekka058 Avatar asked Apr 29 '26 13:04

pekka058


1 Answers

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) {
   .........
like image 55
Yeasin Sheikh Avatar answered May 01 '26 09:05

Yeasin Sheikh