I can use Code A to define a color in Color.kt file which is generated by Android Studio wizard automatically, it's OK.
I hope to define a color based MaterialTheme.colors
, but Code B return the following error.
@Composable invocations can only happen from the context of a @Composable function
At present, I have to use Code C, it's not very good, is there a better way?
Code A
val IconColor = Color(0xFF2E7D32)
Code B
val IconColor = MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
Code C
@Composable
fun IconColor(): Color {
return MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
}
CodePudding user response:
You are getting that because MaterialTheme.colors
the getter of this field is using @compsable
scope, So I have found 2 ways you can declare your variable in Colors.kt
in the way you want.
1:
val IconColor1: @Composable () -> Color = { MaterialTheme.colors.onSurface.copy(alpha = 0.76f) }
2:
val IconColor2: Color @Composable get() = MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
And I hope this was helpful