Compose Preview For Snackbars With Interactive Mode

Previews are one of the main reasons Jetpack Compose is so great for building UI as you get a live representation of your widget along with any variants. I create at least one preview for each component which then feeds into our Showkase catalog for easy reference.

If you’re building a custom component that has transient state such as a Snackbar there are a couple of things you’ll need to do to get the preview working as expected.

Firstly, create an instance of SnackbarHostState and pass it to your custom Snackbar as it creates a container in which the widget is positioned. You can then use rememberCoroutineScope() to allow showSnackbar( ... ) to be called.

@Preview
@Composable
fun PreviewCustomSnackbar() {
    val scope = rememberCoroutineScope()
    val host = SnackbarHostState()

    CustomSnackbar(
        snackbarHostState = host
    )

    scope.launch {
        host.showSnackbar(
            message = "Preview snackbar",
            actionLabel = "RELOAD",
            duration = SnackbarDuration.Indefinite
        )
    }
}

At this point you’ll notice the preview looks partially populated with frames.

Simply click on Start Interactive Mode to bring the preview to life!

I’ve set the duration parameter to Indefinite so that the preview persists, but you can use other values to sample the display period. It’s also clickable and can be dismissed, but you’ll need to Stop Interactive Mode and re-start to get it to appear again.

Dark mode preview in interactive mode showing a lack of contrast

Interactive mode takes the Compose preview in Android Studio to the next level and further streamlines my UI development workflow. Leave a comment if you have any other Compose preview tips.

Leave a comment