skip to Main Content

I’m trying the new SegmentedButton widget:

SegmentedButton<int>(
  onSelectionChanged: (i) {},
  showSelectedIcon: false,
  style: ButtonStyle(
    backgroundColor: MaterialStatePropertyAll(Theme.of(context).primaryColor),
    iconColor: MaterialStateProperty.all(Colors.white),
  ),
  segments: const <ButtonSegment<int>>[
    ButtonSegment<int>(
      value: 12,
      icon: Icon(FlutterRemix.thumb_up_fill),
      enabled: true,
    ),
    ButtonSegment<int>(
      value: 20,
      icon: Icon(FlutterRemix.thumb_down_fill),
    ),
  ],
  selected: {12},
),

This code shows the two segmented buttons like this:

SegmentedButton

How can I customize the color od the selected and unselected buttons, when I set:

backgroundColor: MaterialStatePropertyAll(Theme.of(context).primaryColor),

It does set the background color for both selected and selected.

Thank you!

2

Answers


  1. According to my test, it only works if I remove backgroundColor and add other code:

    class SegmentedButtonTest extends StatefulWidget {
      const SegmentedButtonTest({super.key});
    
      @override
      State<SegmentedButtonTest> createState() => _SegmentedButtonTestState();
    }
    
    class _SegmentedButtonTestState extends State<SegmentedButtonTest> {
      int selected = 12;
    
      @override
      Widget build(BuildContext context) {
        return SegmentedButton<int>(
          onSelectionChanged: (Set<int> i) {
            setState(() {
              selected = i.first;
            });
          },
          showSelectedIcon: false,
          style: ButtonStyle(
            iconColor: MaterialStateProperty.all(Colors.white),
          ),
          segments: const <ButtonSegment<int>>[
            ButtonSegment<int>(
              value: 12,
              icon: Icon(FlutterRemix.thumb_up_fill),
              enabled: true,
            ),
            ButtonSegment<int>(
              value: 20,
              icon: Icon(FlutterRemix.thumb_down_fill),
            ),
          ],
          selected: {selected},
        );
      }
    }
    
    Login or Signup to reply.
  2. You can control this with Material States:

    backgroundColor: MaterialStateProperty.resolveWith<Color>(
       (Set<MaterialState> states) {
          if (states.contains(MaterialState.selected)){
            return Colors.green;
          }
          return Colors.red;
        },
     ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search