Hello, I am trying to make an enum with references...
# compose
g
Hello, I am trying to make an enum with references to Colors from my theme!
Copy code
enum class Hierarchy(
    backgroundColor: Color,
    contentColor: Color,
    pressedBackgroundColor: Color,
    pressedContentColor: Color,
    disabledBackgroundColor: Color,
    disabledContentColor: Color,
    border: BorderStroke? = null,
) {

    Primary(
        backgroundColor = MyTheme.colors.accentDefault,
        contentColor = MyTheme.colors.contentInverse,
        disabledBackgroundColor = MyTheme.colors.accentDisabled,
        disabledContentColor = MyTheme.colors.contentInverse)
}
But as the enum is not a Composable I am hit with an error
@Composable invocations can only happen from the context of a @Composable function
. Is there a workaround this error?
l
Where is the composable you are calling? Is it
colors
?
You could check how Compose MaterialTheme
Color
class is implemented, I think you might be better served with a class and some global variables
g
Yes I think so too, thanks
c
You could also create a variable in your themes to hold a reference to your materialColors as a lambda. I'm testing it out currently and like the ease of the use. I'm still testing performance to see but so far it's not bad. For example:
val primary = @Composable { MaterialTheme.colors.primary }
And then you can use it like
color = primary()
👍 2
g
Interesting, I’ll have a look thanks
a
I think you can also use
@Composable
annotated getters like
Copy code
val primary
    @Composable
    get() = MaterialTheme.colors.primary
Don't have an access to ide right now, didn't test.