Reputation: 11
i need segment to have different color for selected & unselected segments
SegmentedButton<String>(
selected: _selectedSegment,
showSelectedIcon: false,
multiSelectionEnabled: false,
segments: [
ButtonSegment(
value: 'pending',
label: Container(
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: _selectedSegment.contains('pending') ? Color(0xff124549) : Colors.grey[200],
),
child: Text('Pending',
style: TextStyle(
color: _selectedSegment.contains('pending') ? Colors.white : Color(0xff124549),
),
),
),
),
ButtonSegment(
value: 'accepted',
label: Container(
//padding: EdgeInsets.all(12),
child: Text('Accepted',style: TextStyle(
color: _selectedSegment.contains('accepted')?Colors.white : Color(0xff124549),),),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: _selectedSegment.contains('accepted') ? Color(0xff124549) : Colors.grey[200],
),
),
),
],
onSelectionChanged: (newselection){
setState(() {
_selectedSegment = newselection;
});
},
),
Upvotes: 1
Views: 499
Reputation: 1
Here is a note: you can use SegmentedButton.styleFrom method for basic interaction like this:
return SegmentedButton<Settings>(
style: SegmentedButton.styleFrom(
backgroundColor: Colors.grey[200],
foregroundColor: Colors.red,
selectedForegroundColor: Colors.white,
selectedBackgroundColor: Colors.green,
side: const BorderSide(
color: Colors.indigo
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
)
),
But you can also use MaterialStateProperty.resolveWith method which allows you to apply styles dynamically based on the button’s current state. This provides far more flexibility and control over styling for different interactions, such as hovering, selecting, or disabling.
return SegmentedButton<Settings>(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color?>((Set<WidgetState> states) {
if (states.contains(WidgetState.selected)) {
return Colors.blue; // background when selected
} else if (states.contains(WidgetState.hovered)) {
return Colors.grey; // background when hovered
}
return Colors.white; // default background
}),
foregroundColor: WidgetStateProperty.resolveWith<Color?>((Set<WidgetState> states) {
return states.contains(WidgetState.selected) ? Colors.white : Colors.black;
}),
),
)
I wrote an article on how to customize Segmented Button in Flutter. Here is my research on this topic on Medium: https://medium.com/@wartelski/mastering-flutters-segmentedbutton-advanced-customization-techniques-8174db1b9f9e I hope it helps.
Upvotes: 0
Reputation: 6131
you can use style Property in SegmentedButton like this:
SegmentedButton<String>(
style: SegmentedButton.styleFrom(
backgroundColor: Colors.grey[200],
foregroundColor: Colors.red,
selectedForegroundColor: Colors.white,
selectedBackgroundColor: Colors.green,
),
// You Code
),
Upvotes: 0