T D Nguyen
T D Nguyen

Reputation: 7613

Apply Dark/Light theme locally Android Compose

My app designer uses ONE color scheme for the whole app that some elements are appears to be dark theme and in some other place, light theme.

What I want is to apply the dark theme on screen1 and light theme on screen2. I am looking for something like this:

CompositionLocalProvider(Theme provides myLightTheme) {
     Screen1()       
}

CompositionLocalProvider(Theme provides myDarkTheme) {
     Screen2()       
}

Is that possible? Thanks

Upvotes: 1

Views: 1207

Answers (1)

Philio
Philio

Reputation: 4185

Typically you would define dark and light themes separately:

private val LightColors = lightColorScheme(...)
private val DarkColors = darkColorScheme(...)

Then define a custom theme wrapper that uses isSystemInDarkTheme() to auto switch based on system settings:

val LocalUseDarkTheme = compositionLocalOf { false }

@Composable
fun MyTheme(useDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {

    val colors = if (!useDarkTheme) {
        LightColors
    } else {
        DarkColors
    }

    CompositionLocalProvider(LocalUseDarkTheme provides useDarkTheme) {
        MaterialTheme(
            colorScheme = colors,
            content = content
        )
    }
}

So you could then just set useDarkTheme as required:

MyTheme(useDarkTheme = true) { ... }

Upvotes: 2

Related Questions