androidandroid-jetpack-compose

How to show snackbar with a button onclick in Jetpack Compose


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:

    1. SnackbarHostState - which will manage the state of your Snackbar (you would usually get that from the ScaffoldState)
    2. CoroutineScope - which will be responsible for showing your Snackbar

    @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")
            }
        }
    }
    

    example