Search code examples
fluttercolorsslider

How to set label color for Slider in flutter?


Is it possible to set label color different to active color? I tried a lot of options (see below) but nothing works.

import 'package:flutter/material.dart';

void main() {
  var themeData = ThemeData(
    useMaterial3: true,
  );
  runApp(MaterialApp(
    theme: themeData.copyWith(
        sliderTheme: themeData.sliderTheme.copyWith(
      valueIndicatorColor: themeData.primaryColor,
      disabledActiveTickMarkColor: themeData.primaryColor,
      disabledActiveTrackColor: themeData.primaryColor,
      disabledInactiveTickMarkColor: themeData.primaryColor,
      disabledInactiveTrackColor: themeData.primaryColor,
      disabledSecondaryActiveTrackColor: themeData.primaryColor,
      activeTickMarkColor: themeData.primaryColor,
      activeTrackColor: themeData.primaryColor,
      secondaryActiveTrackColor: themeData.primaryColor,
      inactiveTickMarkColor: themeData.primaryColor,
      inactiveTrackColor: themeData.primaryColor,
    )),
    home: const MyHomePage(),
  ));
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double sliderValue = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Slider(
        value: sliderValue,
        max: 23,
        divisions: 23,
        label: "$sliderValue",
        inactiveColor: Theme.of(context).primaryColor,
        activeColor: Theme.of(context).disabledColor,
        thumbColor: Theme.of(context).primaryColor,
        onChanged: (double value) {
          setState(() {
            sliderValue = value;
          });
        },
      ),
    );
  }
}

Solution

  • you can give label color to slider by using SliderTheme like this

    SliderTheme(
             data: const SliderThemeData(
                     valueIndicatorTextStyle: TextStyle(
                      color: Colors.red, // Change the label color here
                     ),
              ),
          child: Slider(
            value: sliderValue,
            max: 23,
            divisions: 23,
            label: "$sliderValue",
            inactiveColor: Theme.of(context).primaryColor,
            activeColor: Theme.of(context).disabledColor,
            thumbColor: Theme.of(context).primaryColor,
            onChanged: (double value) {
              setState(() {
                sliderValue = value;
              });
            },
          ),
    ),