1
votes

Initially the flutter switch widget has the value false. After I swipe, the switch is true. But if I swipe again, the onChange method is not triggered.

I use setState() to change the value of the switch as onChanged method. I tried to hand the BuildContext over, but no success.

    bool value = false;

    void _setValue(bool value) {
        print('before: ' + this.value.toString());
        setState(() => this.value = value);
        print('after: ' + this.value.toString());
    }

    Widget _getSwitch() {
       return Switch(
              value: this.value,
              onChanged: _setValue,
       );
    }

expected result:

Initially false, and switch to true.

I/flutter (20662): before: false

I/flutter (20662): after: true

switch to false

I/flutter (20662): before: true

I/flutter (20662): after: false

switch to true

I/flutter (20662): before: false

I/flutter (20662): after: true

actual result:

Initially false, and now I switch to true.

I/flutter (20662): before: false

I/flutter (20662): after: true

So far so great!

Now I switch to false... Nothing happened. => no onChanged call

Now I switch to true and this is the output:

I/flutter (20662): before: true

I/flutter (20662): after: true

Makes no sense!?

1

1 Answers

0
votes

I created an object

   Switch switch2;

   @override
  void initState() {
    super.initState();
    switch2 = _getSwitch();
  }

Then I tried to build() the switch, instead I just call the method _getSwitch in build() directly.