@composable调用只能在@composable函数的上下文中发生 [英] @composable invocations can only happen from the context of an @composable function

查看:205
本文介绍了@composable调用只能在@composable函数的上下文中发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击工具栏上的动作时显示一条吐司消息,但出现此错误

I'm trying to show a toast message when clicking on a toolbar action, but I got this error

@composable调用只能在以下情况下发生:@composable函数

@composable invocations can only happen from the context of an @composable function

代码:

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

推荐答案

onClick 参数不接受可组合函数.删除 showMessage 中的 @Composable 批注.
使用类似的东西:

The onClick parameter doesn't accept a composable function. Remove the @Composable annotation in the showMessage.
Use something like:

@Composable
fun Toolbar() {

    val context = ContextAmbient.current

    TopAppBar(title = {},
            actions = {
        IconButton(onClick = {
            showMessage(context, message = "test")
        }){}
    })
}

fun showMessage(context: Context, message:String){
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}

这篇关于@composable调用只能在@composable函数的上下文中发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆