Home > database >  how to control selected and unselected background color for the SegmentedButton widget
how to control selected and unselected background color for the SegmentedButton widget

Time:01-31

I'm trying the new 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!

CodePudding user response:

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},
    );
  }
}

CodePudding user response:

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;
    },
 ),
  • Related