1

Let's consider the following @Composable functions:

@Composable
fun WelcomeScreen() {
    ...
    ButtonTheme {
        Button(...) {...}
    }
}

@Composable
@Preview
fun MockWelcome() {
    AppTheme {
        WelcomeScreen { }
    }
}

@Composable
@Preview
fun MockDarkWelcome() {
    AppTheme(darkTheme = true) {
        WelcomeScreen { }
    }
}

And theme (note: AppTheme follows the same logic):

@Composable
fun ButtonTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
    MaterialTheme(
        ...
        colors = if (darkTheme) darkButtonColorPalette else lightButtonColorPalette,
    )
}

The preview window will show both WelcomeScreen versions correctly but the dark version will not show the button in the dark theme.
Running the app everything is OK, this it's only a preview "problem".

So, my question is: is this intended behaviour, a bug, or a misconfiguration?

Full code here: https://github.com/GuilhE/JetpackChallenge

GuilhE
  • 11,591
  • 16
  • 75
  • 116
  • Your code should work fine from what I can see. Can you share a reproducible example? – Yannick Mar 02 '21 at 19:47
  • @Yannick updated my question with link – GuilhE Mar 02 '21 at 19:50
  • 2
    My preview shows nothing at all. Previews are still very unreliable (Android Studio is still a canary version). I try to avoid previews and I rather use something like Showkase https://github.com/airbnb/Showkase – Yannick Mar 02 '21 at 20:00

1 Answers1

1

If you join together the previews and screen together you effectively have something like this:

AppTheme(darkTheme = true) {
    ButtonTheme {
        Button(...) {...}
    }
}

So the ButtonTheme will always be used no matter what theme you use in preview - the preview theme is overridden always.

To make the previews work as you want you'd need to abstract ButtonTheme outside of WelcomeScreen so something like this:

@Composable
fun MyApp() {
    ...
    MyTheme {
        WelcomeScreen()
    }
}

@Composable
fun WelcomeScreen() {
    ...
    Button(...) {...}
}

@Composable
@Preview
fun MockWelcome() {
    AppTheme {
        WelcomeScreen { }
    }
}

@Composable
@Preview
fun MockDarkWelcome() {
    AppTheme(darkTheme = true) {
        WelcomeScreen { }
    }
}
enyciaa
  • 1,982
  • 1
  • 14
  • 24