Leonardo Salazar
Leonardo Salazar

Reputation: 111

How to get the primary color's text color (onPrimary)?

I'm setting my theme this way:

theme: ThemeData(
  primaryColor: themeModel.primaryColor,
  ...
),

Yes, is dynamic.

The problem is: if the user set, let's say, indigo[100], some items (like the bottomAppBar) has light icons over that light color (so bad visibility).

I thought the items adapt their text color to the given color property but it doesn't seem to work that way.

So, I have to set that property manually. But I can't find the Theme property for text color on primary color (named onPrimary in material documentation).

What I found is Theme.of(context).colorScheme.onPrimary but it doesn't seem to work well. It's always returning the same color.

I know I can just get the contrast color for the primary color and set it like this:

theme: ThemeData.from(
  colorScheme: ColorScheme(
    primary: themeModel.primaryColor
    onPrimary: themeModel.onPrimaryColor
    ...
  )
)

But I'm sure Flutter is intelligent enough to autogenerate those properties if you don't pass them... isn't it?

Another thing that I found is Theme.of(context).primaryIconTheme.color. That property is returning the color I'm looking for. But as its name states, it's supposed to be applied only to icons, not text, even when they would probably return the same black variant.


What I would like to know

Is it the way it's supposed to work? Should I write myself the onPrimary property? Is it OK for code quality to use the primaryIconTheme.color for text colors? Or am I missing something?

Upvotes: 1

Views: 2836

Answers (1)

Federick Jonathan
Federick Jonathan

Reputation: 2864

The default ThemeData is ThemeData.light() which primaryColor and accentColor are set to Colors.blue, Card and Scaffold background are set to Colors.white. There are 3 types of textTheme :

  1. textTheme - Text with a color that contrasts with the card and canvas colors. Basically the theme that is used automatically to all Text widget that is a direct child of Scaffold body or Card. (in this case, Colors.black to contrast Colors.white)
  2. primaryTextTheme - A text theme that contrasts with the primary color. Used automatically to all TextWidget that is a direct child of Widgets that use primaryColor, for example AppBar. (Colors.white to contrast Colors.blue)
  3. accentTextTheme - A text theme that contrasts with the accent color. Used automatically to all TextWidget that is a direct child of Widgets that use accentColor, for example FloatingActionButton. (Colors.white to contrast Colors.blue)

If you change the primaryColor to Colors.white, the primaryTextTheme.color doesn't automatically change value to contrast that.

ThemeData(
  primaryColor: Colors.white,
  primaryTextTheme: Theme.of(context).primaryTextTheme.apply(
    bodyColor: Colors.black,
    displayColor: Colors.black,
  )
)

Hope this helps you in any way.

Upvotes: 2

Related Questions