Home > Enterprise >  Conflicting 'on' color for a given background error in jetpack compose
Conflicting 'on' color for a given background error in jetpack compose

Time:10-21

I'm making a theme for my app with jetpack compose and I have this:

@Composable
fun MyTheme(content: @Composable () -> Unit) {

    val colors = lightColors(
        primary = CustomColors.Custom1,
        primaryVariant = CustomColors.Custom2,
        onPrimary = Color.White,
        background = Color.White,
        secondary = CustomColors.Custom2
        )
    MaterialTheme(colors = colors, content = content)

}

object CustomColors{

    val Custom1 = Color(0xEF119335)
    val Custom2= Color(0xAA892335)

}

The problem is that when I add secondary = CustomColors.Custom2, I get an error in onPrimary = Color.White. The error is this:

Conflicting 'on' color for a given background error

CodePudding user response:

Error description from Compose source code

Background colors with the same value should have the same 'on' color

In the Material color system background colors have a corresponding 'on' color which is used for the content color inside a component. For example, a button colored primary will have onPrimary text. Because of this, it is important that there is only one possible onColor for a given color value, otherwise there is no way to know which 'on' color should be used inside a component. To fix this either use the same 'on' color for identical background colors, or use a different background color for each 'on' color.

In your case, you have both primaryVariant and secondary set to CustomColors.Custom2, this means corresponding background colors should be the same too.

Default onSecondary color is Color.Black, and for onPrimary you've specified Color.White, that's why the compiler in unhappy.

You can solve this problem by specifying onSecondary = Color.White or by choosing different colors for primaryVariant and secondary.

If after this explanation you still wanna use these exact colors, you can silent this warning with @SuppressLint("ConflictingOnColor"): but some system or Material elements may not look good.

  • Related