简体   繁体   中英

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

     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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM