Jetpack Compose Getting Light vs Dark Mode from MaterialTheme Using Material 3
Asked Answered
B

2

20

With Jetpack Compose, using Material 2, you can see if a theme is in light mode easily with the following

val light = MaterialTheme.colors.isLight

Using Material 3, I don't see this ability. Is there a way to do this with a Material 3 theme?

Both answered 23/3, 2022 at 17:45 Comment(0)
B
21

Found a solution. Color in Compose has a built in method luminance that returns the relative luminance as a float between 0 and 1. I wrote an extension function for ColorScheme that returns true if the luminance of the background is greater than 0.5.

@Composable
fun ColorScheme.isLight() = this.background.luminance() > 0.5

Using it as:

val isLight = MaterialTheme.colorScheme.isLight()

Now whether the system is in dark mode doesn't matter, only the theme.

Both answered 23/3, 2022 at 22:20 Comment(4)
Is there a special reason to write it as a composable function instead of a property, which would make it easier to migrate old code?Examination
It's not about light/dark color theme really... some apps can have dark color backgrounds in light theme also... bad solution.Tervalent
@Examination because I wanted a composable function.Both
@Tervalent got a better solution then?Both
C
13

In JetpackCompose you can use this method that returns if the light / dark mode is enabled or not

isSystemInDarkTheme()

And then in your code

if (isSystemInDarkTheme()){} \\Dark mode enabled
else {} //Light mode enabled 
Contrapuntal answered 23/3, 2022 at 19:32 Comment(1)
I'm using that as a workaround, but the theme could be light or dark independently of the system, so I was hoping for some method to see that.Both

© 2022 - 2024 — McMap. All rights reserved.