Issue
I want to show snackbar with a button onclick in Jetpack Compose
I tried this
Button(onClick = {
Snackbar(action = {}) {
Text("hello")
}
}
But AS said "@Composable invocations can only happen from the context of a @Composable function"
Shall you give me a nice program.
I wish it can run in Button.onclick()
Solution
You'll need two things:
SnackbarHostState
- which will manage the state of yourSnackbar
(you would usually get that from theScaffoldState
)CoroutineScope
- which will be responsible forshowing
yourSnackbar
@Composable
fun SnackbarDemo() {
val scaffoldState = rememberScaffoldState() // this contains the `SnackbarHostState`
val coroutineScope = rememberCoroutineScope()
Scaffold(
modifier = Modifier,
scaffoldState = scaffoldState // attaching `scaffoldState` to the `Scaffold`
) {
Button(
onClick = {
coroutineScope.launch { // using the `coroutineScope` to `launch` showing the snackbar
// taking the `snackbarHostState` from the attached `scaffoldState`
val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
message = "This is your message",
actionLabel = "Do something."
)
when (snackbarResult) {
Dismissed -> Log.d("SnackbarDemo", "Dismissed")
ActionPerformed -> Log.d("SnackbarDemo", "Snackbar's button clicked")
}
}
}
) {
Text(text = "A button that shows a Snackbar")
}
}
}
Answered By - Bartek Lipinski
Answer Checked By - David Marino (JavaFixing Volunteer)