在底页中切换不会更改 Flutter 上的状态

Switch in bottomsheet not changing status on Flutter

我在使用底页内的开关时遇到了一些问题。 当我点击它时,它不会改变它的状态。只是第一次,状态正确改变。

这是我使用的简单代码:

  bool _switchValue = false;

  @override
  Widget build(BuildContext context)
  {
    return new Scaffold(
      body: Center(
        child: RaisedButton(
          child: const Text('SHOW BOTTOM SHEET'),
          onPressed: () {
            showModalBottomSheet<void>(context: context, builder: (BuildContext context) {
              return Container(
                child: CupertinoSwitch(
                  value: _switchValue,
                  onChanged: (bool value) {
                    setState(() {
                      _switchValue = value;
                    });
                  },
                )
              );
            });
          }
        )
      )
    );
  }

谁能帮帮我?

您需要将开关放在它自己的 StatefulWidget 中,并使用回调 return 将值传给您的主 class。底部 sheet 使用不同的上下文,因此在上面的示例中调用 setState 不起作用。

class _MyHomePageState extends State<MyHomePage> {
  bool _switchValue = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RaisedButton(
            child: const Text('SHOW BOTTOM SHEET'),
            onPressed: () {
              showModalBottomSheet<void>(
                context: context,
                builder: (BuildContext context) {
                  return BottomSheetSwitch(
                    switchValue: _switchValue,
                    valueChanged: (value) {
                      _switchValue = value;
                    },
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

class BottomSheetSwitch extends StatefulWidget {
  BottomSheetSwitch({@required this.switchValue, @required this.valueChanged});

  final bool switchValue;
  final ValueChanged valueChanged;

  @override
  _BottomSheetSwitch createState() => _BottomSheetSwitch();
}

class _BottomSheetSwitch extends State<BottomSheetSwitch> {
  bool _switchValue;

  @override
  void initState() {
    _switchValue = widget.switchValue;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: CupertinoSwitch(
          value: _switchValue,
          onChanged: (bool value) {
            setState(() {
              _switchValue = value;
              widget.valueChanged(value);
            });
          }),
    );
  }
}

使用StatefulBuilder改变BottomSheet

中开关的状态
    showModalBottomSheet(
     context: context, builder: (BuildContext context) {  
      return Container(  
       child: StatefulBuilder(  
        builder: (BuildContext context, StateSetter stateSetter) {  
         return CupertinoSwitch(  
           value: _switchValue,  
           onChanged: (val) {  
             stateSetter(() => _switchValue = val); 
           },);  
         },  
       ),  
      )  
   });