DEV Community

loading...
Cover image for Snackbars Without Scaffolds (and why you should avoid them)

Snackbars Without Scaffolds (and why you should avoid them)

aniketsmk profile image Aniket Kadam ・1 min read

Considerations

Sometimes you might run into a situation where you need a Snackbar in a layout that can't have a Scaffold.
For instance, if you wanted a modal BottomSheet and a Scaffold, those aren't two things you can easily use together. Mainly because the ModalBottomSheetLayout doesn't have a SnackbarHost and doesn't play nicely with other wrapping layouts.
In this case, you'd have to create and more importantly place your own SnackBarHost.

Placement Methods

Take a look at the Scaffold.kt's code for placing Snackbars, it involves measuring the Snackbar and calculating an avoidance of the Fab button and such.
Perhaps you'd reconsider your layout to see if it's worth this?

Creating it

It's quite simple to create it though!

@Composable
fun SnacksNoScafs() {

    val snackState = remember { SnackbarHostState() }
    val snackScope = rememberCoroutineScope()

    SnackbarHost(hostState = snackState, Modifier)

    fun launchSnackBar() {
        snackScope.launch { snackState.showSnackbar("Sup? Here's some snacks.") }
    }

    Button(::launchSnackBar) {
        Text("Show Snackbar")
    }
}
Enter fullscreen mode Exit fullscreen mode

Without additional placement information the host ends up at the top like so:
Alt Text

Let me know if you end up needing to use these two and how you dealt with the tradeoffs yourself.

This was valid as of Jetpack Compose beta 3.


I'm on the lookout for a Senior Android position with great customer impact, a great team and great compensation. Let me know if you're hiring! Also open to consulting contracts.

Discussion (0)

pic
Editor guide