How to add extra colors into MaterialTheme in Android Jetpack Compose?

Just a small change to Valeriy Katkov’s answer

In some versions of the android studio, the following code will not work

@Composable
val Colors.myExtraColor: Color
    get() = if (isLight) Color.Red else Color.Green

@Composable
fun ExtraColorExample() {
    Text(
        text = "test",
        color = MaterialTheme.colors.myExtraColor // <-- the newly added color
    )
}

It will show an error

This annotation is not applicable to target ‘top-level property
without backing field or delegate’

To fix this either write it like this

@get:Composable
val Colors.myExtraColor: Color
    get() = if (isLight) Color.Red else Color.Green

Or

val Colors.myExtraColor: Color
    @Composable
    get() = if (isLight) Color.Red else Color.Green

The version I found this error in

Android Studio Arctic Fox | 2020.3.1 Canary 12
Build #AI-203.7148.57.2031.7226969, built on March 23, 2021
Runtime version: 11.0.8+10-b944.6842174 amd64
VM: OpenJDK 64-Bit Server VM by N/A
Windows 10 10.0

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)