I am coding a dark and light theme. And I want to use custom textTheme inside themeDatas. I created the textthemes but not with my own variable names. How to create TextStyle with my own variable names.
ThemeData darkTheme = ThemeData(
textTheme: myTextTheme
);
final myTextTheme = TextTheme(
displayLarge: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
displayMedium: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
bodyLarge: TextStyle(fontSize: 16.0),
);
For example I want to create appBarText, xText, myText and etc intead of displayLarge, displayMedium and etc.
2
Answers
You can create your own variable names for the
TextStyle
objects in yourTextTheme
by defining them explicitly as follows:Then, you can use this
myTextTheme
in yourThemeData
as follows:Now, you can use
appBarText
,xText
,myText
, and other variable names that you have defined in yourTextTheme
for yourTextStyle
objects throughout your application.As long as you use Flutter’s built-in
TextTheme
, you cannot pass custom parameters inside of it.However, there are a few options for you to choose when dealing with this issue.
The most common and convenient approach is to supply the text styles for an element at the respective element’s theme. This way, the styles will be applied by Flutter automatically.
For example, for
AppBar
the respective theme would beAppBarTheme
:The second approach is to use custom theme extensions. This is a more flexible way, than the first one, but you will need to apply the styles manually. This approach is useful when designing custom widgets with their styles. Here is a decent guide on extending themes: Medium.