Search code examples
flutterdartslider

Flutter - Remove default padding in Slider


I am wondering how I can remove the default padding in Flutter Slider

Current output is like this, default padding of Slider is clearly visible

enter image description here

Here's my code::

                    Positioned(
                      child: Align(
                        alignment: Alignment.bottomLeft,
                        child: SliderTheme(
                            data: SliderTheme.of(context).copyWith(
                              trackHeight: 2.0,
                              thumbColor: Colors.transparent,
                              thumbShape: RoundSliderThumbShape(enabledThumbRadius: 0.0),
                            ),
                            child: Container(
                                width: 380.0,
                                height: 20.0,
                                padding: EdgeInsets.all(0.0),
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.blueAccent)
                                ),
                                child: Slider(
                                  value: 50,
                                  min: 1,
                                  max: 100,
                                  divisions: 100,
                                  activeColor: colors.primaryRed,
                                  inactiveColor: Colors.white,
                                  onChanged: (double newValue) {
                                    print(newValue);
                                  },
                                )
                            )
                        ),
                      ),
                    )

Solution

  • you can fix it with custom trackShape like this:

    add this line to SliderTheme data:

    SliderTheme(
      data: SliderThemeData(
        // here
        trackShape: CustomTrackShape(),
      ),
      child: Slider(
        ```
      ),
    ),
    

    then inside CustomTrackShape() you must write this code:

    class CustomTrackShape extends RoundedRectSliderTrackShape {
      @override
      Rect getPreferredRect({
        required RenderBox parentBox,
        Offset offset = Offset.zero,
        required SliderThemeData sliderTheme,
        bool isEnabled = false,
        bool isDiscrete = false,
      }) {
        final trackHeight = sliderTheme.trackHeight;
        final trackLeft = offset.dx;
        final trackTop = offset.dy + (parentBox.size.height - trackHeight!) / 2;
        final trackWidth = parentBox.size.width;
        return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
      }
    }
    

    enter image description here