简体   繁体   English

Flutter 开关在 Modalbottomsheet 中不起作用

[英]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. Modalbottomsheet 出现但不会更新更改/状态。 Does anyone know a solution?有谁知道解决方案?

Use StatefulBuilder to update UI inside showModalBottomSheet .使用StatefulBuilder更新showModalBottomSheet内的 UI。 Second issue is you need to use a bool variable to hold value.第二个问题是您需要使用 bool 变量来保存值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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