1

How do I customize the Material 3 Switch?

enter image description here

enter image description here

As you can see, I already did customize most of the switch to red, the only thing missing here is the "border", for some reason it is set to white and I cannot see a param where I can modify to red.

I also read the Flutter documentation of the Switch class: https://api.flutter.dev/flutter/material/Switch-class.html but 2 examples are using Material 2 and the only Material 3 example doesn't not modify the default border.

This is the current widget configuration:

Switch(
  // focusColor: Colors.blue,
  trackColor: MaterialStateProperty.resolveWith(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        return Colors.red;
      }
      return Colors.red.withOpacity(.1);
    },
  ),
  overlayColor: MaterialStateProperty.resolveWith(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.disabled)) {
        return Colors.red;
      }
      return Colors.white.withOpacity(.1);
    },
  ),
  // hoverColor: Colors.green,
  thumbColor: MaterialStateProperty.resolveWith(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        return HSLColor.fromColor(Colors.red)
            .withLightness(0.2)
            .toColor();
      }
      return Colors.red;
    },
  ),
  splashRadius: 24,
  // inactiveTrackColor: Colors.pink,
  // activeTrackColor: Colors.green,
  thumbIcon: MaterialStateProperty.resolveWith(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.selected)) {
        return const Icon(Icons.check, color: Colors.red);
      }
      return null;
    },
  ),
  // activeColor: Colors.lime,
  // inactiveThumbColor: Colors.orange,
  value: _value,
  onChanged: (bool value) => setState(() => _value = !_value),
)

The commented params are the ones I've already tried.

I did a DartPad where you can see the demo: https://dartpad.dev/?id=6c4ab5c547f7b7a5a0821d7dc9962485.

Alex Rintt
  • 1,618
  • 1
  • 11
  • 18

1 Answers1

5

Change your theme to

theme: ThemeData.dark(
        useMaterial3: true,
      ).copyWith(
        colorScheme:
            Theme.of(context).colorScheme.copyWith(outline: Colors.red),
        scaffoldBackgroundColor: Colors.black,
      ),

Output enter image description here

Rahul
  • 3,529
  • 1
  • 5
  • 19
  • here is the corresponding line in flutter-sdk https://github.com/flutter/flutter/blob/75fac6ae4df117755bafea420dbbae766b58a67c/packages/flutter/lib/src/material/switch.dart#L1655 – Rahul Feb 21 '23 at 22:55