DEV Community

Cover image for Snackbars Without Scaffolds (and why you should avoid them)
Aniket Kadam
Aniket Kadam

Posted on

9 3

Snackbars Without Scaffolds (and why you should avoid them)

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.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools