I'm trying to build a custom Elevated Button component : (here is a simplified version)
ElevatedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.disabled)) return Colors.green;
if (states.contains(MaterialState.pressed)) return Colors.yellow;
return Colors.green;
}),
),
child: const Text(
'Text Color needs to be foreground Color',
style: TextStyle(
color: Colors.red,
),
),
)
for the needs of my App I need to provide a predefined TextStyle
which will have a color
-> but I need this TextStyle
color
to be overridden within my Button by the foregroundColor
Currently Text
takes the foregroundColor
only if I don't provide a color inside TextStyle
-> I need foregroundColor
to always override my TextStyle color
CodePudding user response:
If you want to override the text style of your button, you can set the textStyle
of ButtonStyle
:
ElevatedButton(
style: ButtonStyle(
textStyle: MaterialStateProperty.resolveWith((states) {
late final Color color;
if (states.contains(MaterialState.disabled)) color = Colors.green;
if (states.contains(MaterialState.pressed)) color = Colors.yellow;
else color = Colors.green;
return TextStyle(color: color);
}),
),
child: const Text(
'Text Color needs to be foreground Color',
),
)
You can also reuse the foreground color of the current button style and set the text style with it:
final theme = Theme.of(context);
ElevatedButton(
style: ButtonStyle(
textStyle: MaterialStateProperty.resolveWith((states) {
late final Color color;
if (states.contains(MaterialState.disabled)) color = Colors.green;
if (states.contains(MaterialState.pressed)) color = Colors.yellow;
else color = Colors.green;
return TextStyle(color: theme.elevatedButtonTheme.style!.foregroundColor!.resolve(states));
}),
),
child: const Text(
'Text Color needs to be foreground Color',
),
)
CodePudding user response:
Interestingly enough Valentin's approach didn't work for me, resolving ButtonStyle(textStyle:
with MaterialStateProperty
failed to change my button text color
But what I realized thanks to his answer is that :
As long you define your TextStyle
inside ButtonStyle()
rather than inside your Text()
widget
-> foregroundColor
will always override your TextStyle
color
Which means that if I write this :
ElevatedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color?>(
(states) {
if (states.contains(MaterialState.pressed)) return Colors.yellow;
return Colors.green;
},
),
textStyle: MaterialStateProperty.all(
const TextStyle(
color: Colors.red,
),
),
),
onPressed: () {},
child: const Text(
'Text is now Green & Yellow on Press !',
),
);
My Text
color
will take foregroundColor