I’m trying to add a property to TextTheme that I can modify in my ThemeData. I’ve declared the following extension
extension CustomStyles on TextTheme{
TextStyle get disabledText => const TextStyle(color: Color(0xff999999));
}
which I can apply to a textField using
child: (_isEnabled)
? Text("Undo", style: Theme.of(context).textTheme.bodyMedium)
: Text("Undo", style: Theme.of(context).textTheme.disabledText)
However, when I try and access it in the ThemeData (declared in the same dart file as the extension)
theme: ThemeData (
textTheme: TextTheme(
bodyMedium: TextStyle(
color: (_isDark) ? Colors.white : Colors.black,
fontSize: _textSize
),
disabledText: TextStyle(
fontSize: _textSize
),
),
),
The compiler gives me the error
The named parameter 'disabledText' isn't defined
Any thoughts on how I might define it so I can have both the color and size defined by the theme?
=== Update ===
So, after Dhafin’s comment I’ve got around this at the moment by declaring a static variable with the color and using the following
Text(item.text,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: MyAppState.disabledText))
but the question still remains. There has to be a more elegant way of declaring a central disabled theme that can be accessed anywhere
2
Answers
Having read around a bit more I came across this article on Medium which lead me to this solution
Which can be applied to my textField as follows
Yes, Compiler is right.
You have only defined a getter method on the
TextTheme
class.This getter method is not an instance attribute (data member) that can be passed in the constructor of the class being extended by extension method.
That’s why extension method called ‘extension method’ not extension property or extension generally.
So, for your problem: Provide all of the visual properties of that
TextStyle
on the extension.and you can access it throught:
Theme.of(context).textTheme.disabledText
And, if you wanna dynamically display that disabledText with various font sizes:
For more info about extension method here
Hope it helps you.