pekka058
pekka058

Reputation: 33

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?

Upvotes: 3

Views: 294

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

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) {
   .........

Upvotes: 3

Related Questions