Search code examples
flutterdartflutter-layoutflutter-animation

Slider becomes laggy once there are divisions


This is how a Slider's animation normally looks like:

Normal Behaviour

This is how a Slider looks when I try to add the value label:

Laggy Behaviour



This is the sample code:
          Slider(
              value: sliderValue,
              activeColor: color,
              min: 0.0,
              max: 100.0,
              divisions: 2000,    //TO COMMENT
              label: sliderValue.toStringAsFixed(2),    //TO COMMENT
              onChanged: (value) {
                setState(() {
                  sliderValue = value;
                });
              }),

In this code, if I comment out the marked //TO COMMENT lines which are the divisions and label properties, the `label goes away as expected, and the animation is smooth again.

I assume this is due to divisions, and any amount of it, even just 100 does not change the lag in any way.

Additionally, it seems that the label property does not work on its own. It needs the divisions property to also be set so that the value label can be displayed.

What is the workaround so that I can achieve a Slider with the smoothness shown in the first image, but have the default value label or what looks the same?


Solution

  • If you take a look on source code, you can find _positionAnimationDuration which is responsible to animate the slider

    enter image description here

    Change it to

    static const Duration _positionAnimationDuration = Duration.zero;
    

    Changing on source-code will affect on others project, instead create a local dart file, paste the full slider code and make changes.

    Let say we have created customSlider.dart file . Make sure to replace some(./xyz.dart) top imports with import 'package:flutter/cupertino.dart'; or material on our customSlider.dart. Then replace _positionAnimationDuration.

    To use this, import the file

    import 'customSlider.dart' as my_slider;
    ...
    //use case 
    my_slider.Slider(....)