skip to Main Content

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


  1. You can create your own variable names for the TextStyle objects in your TextTheme by defining them explicitly as follows:

    final myTextTheme = TextTheme(
      appBarText: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
      xText: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
      myText: TextStyle(fontSize: 16.0),
    );
    

    Then, you can use this myTextTheme in your ThemeData as follows:

    ThemeData darkTheme = ThemeData(
      textTheme: myTextTheme,
    );
    

    Now, you can use appBarText, xText, myText, and other variable names that you have defined in your TextTheme for your TextStyle objects throughout your application.

    Login or Signup to reply.
  2. 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.

    1. 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 be AppBarTheme:

      final darkTheme = ThemeData(
         textTheme: myTextTheme,
         appBarTheme: myAppBarTheme,
       );
      
       const myTextTheme = TextTheme(
         displayLarge: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
         displayMedium: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
         bodyLarge: TextStyle(fontSize: 16.0),
       );
      
       const myAppBarTheme = AppBarTheme(
         titleTextStyle: TextStyle(fontSize: 36),
       );
      
    2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search