onChangeEnd is not fired properly with Flutter Slider

Viewed 614

I am having an issue, I am trying to get the end value of a slider, but for some reason, the onChangeEnd is fired 2 times, when user moves the slider, it's fired with the initial position, and fired when the user finished with the latest position. I need to handle a function when the change is ended, but as its fired 2 times, I just need to use the second one, I need a way to evade the first one. I think it could be something regarding with the setState function, but if I remove it, the slider will not be moved.

The code is the following:

Slider(
  value: _place.value,
  min: 0.0,
  max: 10.0,
  divisions: 10,
  onChangeStart: (double value) {
    print('Start value is ' + value.toString());
  },
  onChangeEnd: (double value) {
    print('Finish value is ' + value.toString());
  },
  onChanged: (double value) {
    if (vm.isRatingPlace) {
      setState(() {
        _place.value = value;
      });
    }
  },
  activeColor: HeatMapColors.getOnFireColor(_place.value),
  inactiveColor: Colors.black45,
));

With those print that I have there, when I try to move the slider from position 0, I get this:

Start value is 0.0

Finish value is 0.0

Start value is 0.0

Finish value is 6.0 - I need just this one in the onChangeEnd event

1 Answers

I had the same issue. I added a bool variable to manage the pushing state. The onChangeEnd needs a small delay

bool isPushed=false;

Slider(
  value: _place.value,
  min: 0.0,
  max: 10.0,
  divisions: 10,
  onChangeStart: (double value) {
    isPushed=true;   // now the button is  pushing
    print('Start value is ' + value.toString());
  },
  onChangeEnd: (double value) {
    isPushed=false;  now the button is not pushing but it is not true
    Future.delayed(const Duration(milliseconds: 200), () {  
        if (!isPushed) {    // check if button is pushed after some millis
           print('Finish value is ' + value.toString());

      }
     });
  },
  onChanged: (double value) {
    if (vm.isRatingPlace) {
      setState(() {
        _place.value = value;
      });
    }
  },
  activeColor: HeatMapColors.getOnFireColor(_place.value),
  inactiveColor: Colors.black45,
));
Related