Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Switch - onChanged Not Changing

When using the following Switch widget, the isOn value always returns true and never changes.

The Switch only moves position on a swipe too, a tap won't move it. How to resolve?

bool isInstructionView = false;

Switch(
    value: isInstructionView,
    onChanged: (bool isOn) {
      setState(() {
        isInstructionView = isOn;
        print(isInstructionView);
      });
    },
    activeColor: Colors.blue,
    inactiveTrackColor: Colors.grey,
    inactiveThumbColor: Colors.grey,
)

Update: For extra clarity, onChanged always returns isOn as true. Why would this be?

like image 530
Josh Kahane Avatar asked Sep 07 '18 12:09

Josh Kahane


4 Answers

class Tab_b extends StatefulWidget {

bool isInstructionView = false;
@override
State<StatefulWidget> createState() => new _TabsPageState();
}

class _TabsPageState extends State<Tab_b>{

@override
Widget build(BuildContext context) {

return Scaffold(
    appBar: new AppBar(
    title: new Text("add data"),
),
body: new Container(
  child:  Switch(
    value: widget.isInstructionView,
    onChanged: (bool isOn) {
      print(isOn);
      setState(() {
        widget.isInstructionView = isOn;
        print(widget.isInstructionView);
      });
    },
    activeColor: Colors.blue,
    inactiveTrackColor: Colors.grey,
    inactiveThumbColor: Colors.grey,
  ),
),
);
}
like image 31
Zulfiqar Avatar answered Nov 13 '22 20:11

Zulfiqar


You just need to make sure to declare the bool for the switch toggle outside Widget build to make it global and acessible for SetState method. No need to initstate and etc.

    class ExampleClass extends StatefulWidget {
     @override
     _ExampleClassState createState() => _ExampleClassState();
    }

    class _ExampleClassState extends State<ExampleClass> {

     bool isInstructionView = false;

     @override
     Widget build(BuildContext context) {

      return Container(
       child:  Switch(
       value: isInstructionView,
       onChanged: (isOn) {

         setState(() {
           isInstructionView = isOn
         });

         print(isInstructionView);

        },
        ...
      ),
     );
    }
   }
like image 130
Shukry Shahril Avatar answered Nov 13 '22 20:11

Shukry Shahril


I added additional code chunks according to @Zulfiqar 's answer. I didn't test this code but I m using similar codes in my project. if you want to save it and use in another class or if you want to show latest state for everytime you load you can save the state in a global variable and call it when you load the class. hope it will help..

class Tab_b extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => new _TabsPageState();
}

class _TabsPageState extends State<Tab_b>{
  bool isInstructionView;
  @override
  void initState() {
    isInstructionView = Global.shared.isInstructionView;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("add data"),
      ),
      body: new Container(
        child:  Switch(
          value: isInstructionView,
          onChanged: (bool isOn) {
            print(isOn);
            setState(() {
             isInstructionView = isOn;
             Global.shared.isInstructionView = isOn;
             isOn =!isOn;
              print(isInstructionView);
            });
          },
          activeColor: Colors.blue,
          inactiveTrackColor: Colors.grey,
          inactiveThumbColor: Colors.grey,
        ),
      ),
    );
  }
}
class Global{
  static final shared =Global();
  bool isInstructionView = false;
}
like image 6
Bilal Şimşek Avatar answered Nov 13 '22 20:11

Bilal Şimşek


Here Is my code for toggle button

class ToggleButtonScreen extends StatefulWidget {
 @override
 _ToggleButtonScreenState createState() => _ToggleButtonScreenState();
}

class _ToggleButtonScreenState extends State<ToggleButtonScreen> {
 bool _value = false;

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: SafeArea(
       child: Center(
         child: Container(
           decoration: BoxDecoration(
             image: DecorationImage(
               image: _value ? AssetImage("images/cnw.png") : AssetImage("images/cnw.png"),
               fit: BoxFit.cover,
             ),
           ),
           child: Padding(
             padding: EdgeInsets.all(AppDimens.EDGE_REGULAR),
             child: Column(
               children: [
                // _customSwitchButton(),
                 _normalToggleButton(),
               ],
             ),
           ),
         ),
       ),
     ),
   );
 }

Widget _normalToggleButton () {
   return Container(
     child: Transform.scale(
       scale: 2.0,
       child: Switch(
         activeColor : Colors.greenAccent,
         inactiveThumbColor: Colors.redAccent,
         value: _value,
           activeThumbImage: AssetImage("images/cnw.png"),
           inactiveThumbImage : AssetImage("images/simple_interest.png"),
           onChanged: (bool value){
            setState(() {
              _value = value;
            });
           },
       ),
     ),
   );
}
}
like image 3
tipu sultan Avatar answered Nov 13 '22 20:11

tipu sultan