Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Snackbar in Material Design 3 using Scaffold

Decided to try out Material Design 3 in my new Jetpack Compose project. Everything was cozy until I needed to show a Snackbar when I hit a wall.

In MD2 this was super-easy and you would show the snackbar in a Scaffold done with the SnackbarHostState.showSnackbar() function inside a Coroutine scope. I observed you only needed to import androidx.compose.material.rememberScaffoldState from Material Library.

import androidx.compose.material.rememberScaffoldState


@Composable
fun MyScreenInMaterial2() {
    val scaffoldState = rememberScaffoldState()
}

When I try the same in MD3 the rememberScaffoldState() function is not being resolved. enter image description here

For those who have dived in MD3 world how do you show a Snackbar in a Scaffold? I have checked the docs and online resources but I haven't come across a solution.

like image 520
Tonnie Avatar asked Nov 26 '25 17:11

Tonnie


1 Answers

Here you have an example from the official documentation.

val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
    snackbarHost = { SnackbarHost(snackbarHostState) },
    floatingActionButton = {
        var clickCount by remember { mutableStateOf(0) }
        ExtendedFloatingActionButton(
            onClick = {
                // show snackbar as a suspend function
                scope.launch {
                    snackbarHostState.showSnackbar(
                        "Snackbar # ${++clickCount}"
                    )
                }
            }
        ) { Text("Show snackbar") }
    },
    content = { innerPadding ->
        Text(
            text = "Body content",
            modifier = Modifier.padding(innerPadding).fillMaxSize().wrapContentSize()
        )
    }
)
like image 116
Damian Petla Avatar answered Nov 28 '25 06:11

Damian Petla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!