I'm trying to show a toast message when clicking on a toolbar action, but I got this error
@composable invocations can only happen from the context of a @composable function
Code:
@Composable
fun Toolbar() {
TopAppBar(title = { Text(text = "Jetpack Compose") }, navigationIcon = {
IconButton(onClick = {}) {
Icon(Icons.Filled.Menu)
}
}, actions = {
IconButton(onClick = {
showMessage(message = "test")
}) {
Icon(vectorResource(id = R.drawable.ic_baseline_save_24))
}
})
}
@Preview
@Composable
fun ToolbarPreview(){
Toolbar()
}
@Composable
fun showMessage(message:String){
Toast.makeText(ContextAmbient.current, message, Toast.LENGTH_SHORT).show()
}
The
onClick
parameter doesn't accept a composable function. Remove the@Composable
annotation in theshowMessage
.Use something like: