Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch in bottomsheet not changing status on Flutter

I have some problem using a switch inside a bottomsheet. When I tap on it, it doesn't change it's status. Only for the first time, the state changes correctly.

This is the simple code I'm using:

  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;
                    });
                  },
                )
              );
            });
          }
        )
      )
    );
  }

Can anyone please help me?

like image 663
AldoB Avatar asked Oct 18 '18 21:10

AldoB


1 Answers

You need to put the switch in its own StatefulWidget and use a callback to return the value to your main class. A bottom sheet uses a different context so calling setState in your example above doesn't work.

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);
            });
          }),
    );
  }
}
like image 60
Albert Lardizabal Avatar answered Nov 14 '22 00:11

Albert Lardizabal