skip to Main Content

I try to make an app theme for the text style. I get from the flutter docs this example.

MaterialApp(
  title: appName,
  theme: ThemeData(
    // Define the default brightness and colors.
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],

    // Define the default font family.
    fontFamily: 'Georgia',

    // Define the default `TextTheme`. Use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: const TextTheme(
      displayLarge: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
      titleLarge: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
      bodyMedium: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
    ),
  ),
  home: const MyHomePage(
    title: appName,
  ),
);

and

Container(
  color: Theme.of(context).colorScheme.secondary,
  child: Text(
    'Text with a background color',
    style: Theme.of(context).textTheme.titleLarge,
  ),
),

I want to have the option to add multiple colors for the same text size. For example, the titleLarge can be red or white.

Adding color in the TextTheme->TextStyle only gives the option to add one color.

Is there a way for me to change it later in the Text widget? Maybe a way to override color from Theme.of(context).textTheme.titleLarge?

2

Answers


  1. You can override at the usage place with copyWith as following

    Theme.of(context).textTheme.titleLarge!.copyWith(color: Colors.white)
    
    Login or Signup to reply.
  2. You can copy the theme, then give individual text styles like this

    Theme.of(context).textTheme.apply(bodyColor: Colors.white).titleLarge
    

    or you can also use copyWith using conditional ? like this

    Theme.of(context).textTheme.titleLarge?.copyWith(color: Colors.white)
    

    or null check ! like this

    Theme.of(context).textTheme.titleLarge!.copyWith(color: Colors.white)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search