https://kotlinlang.org logo
#compose
Title
# compose
c

Colton Idle

11/30/2021, 3:04 PM
Is there any chance to write this
Copy code
style = MaterialTheme.typography.h1,
but have the "h1" be a variable. like val myStyle = "h1" then have
Copy code
style = MaterialTheme.typography.+myStyle
a

Albert Chang

11/30/2021, 3:15 PM
You can create an extension function yourself similar to the fromToken() in M3.
👍 3
c

Colton Idle

11/30/2021, 3:18 PM
Hm. Trying to do this for colors for example and I can't because it says my function has to be a composable?
Copy code
fun getColorFromString(color: String): Color {
  when (color) {
    "color1" -> { MyTheme.colors.color1 }
  }
}
eh. I guess that's actually a different question entirely. I will use the fromToken solution for Type and try to come up with something else for color. thanks Albert
c

Chris Sinco [G]

11/30/2021, 6:09 PM
Hmm are you trying to extend MaterialTheme to have more color keys besides the ones included?
c

Colton Idle

11/30/2021, 6:48 PM
In this case I was just trying to convert from a string representation of a color (coming from a server) and converting that into a color from my theme.
c

Chris Sinco [G]

11/30/2021, 6:59 PM
I see - are the colors from the server raw hex values?
c

Colton Idle

11/30/2021, 7:19 PM
Nope. They are strings, that match in terms of names with our design system which is why it would be cool to somehow do
Copy code
MyTheme.colors.+"color1"
a

Albert Chang

12/01/2021, 12:19 AM
You should create an extension function on
Colors
(or your custom colors class):
Copy code
fun Colors.fromToken(token: ColorKey): Color = when (token) {
    ColorKey.Primary -> primary
    ColorKey.Secondary -> secondary
    ...
}
1
2 Views