Jetpack compose AppBarIcon 抱怨“调用@Composable 函数的函数必须用@Composable 标记"; [英] Jetpack compose AppBarIcon complains that "Functions which invoke @Composable functions must be marked with the @Composable"

查看:28
本文介绍了Jetpack compose AppBarIcon 抱怨“调用@Composable 函数的函数必须用@Composable 标记";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jetpack compose AppBarIcon 元素,但出现错误:调用@Composable 函数的函数必须用@Composable 标记"当我在 onclick 上调用可组合函数时.这是代码:

I used jetpack compose AppBarIcon element but I got the error: Functions which invoke @Composable functions must be marked with the @Composable" when I call a composable function on the onclick lamba. This is the code:

class testActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent { AppBarIcon(Image(10, 10) ) {
                composableFunction()
            }
        }
    }
} 

@Composable()
fun composableFunction() {
}

这是一个真正的问题,因为我在运行时遇到了异常

and it is a real problem becaus I got an exception at run-time

这是我想念的某种想法还是真正的错误?

It is somethink I miss or it is a real bug ?

推荐答案

首先要注意 Composable 函数必须 只能 在另一个 Composable 函数中调用.
现在回到你的问题,接受函数的 onClick 参数不是一个可组合的函数.所以在 onClick 中调用 @Composable 函数不是选项,因此会抛出错误 调用@Composable 函数的函数必须用@Composable 标记代码>.
解决此问题的代码.

First thing to note that Composable function must only be called inside another Composable function.
Now back to your question, onClick parameter which accept the function is not a composable function. So calling @Composable function inside a onClick isn't the option and hence throw an error Functions which invoke @Composable functions must be marked with the @Composable.
Code to resolve this issue.

class testActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        var loadView = +state { false }
        Column {
            AppBarIcon(+imageResource(R.drawable.dashboard)) {
                loadView.value = true
            }
            Text("Hey")
            if (loadView.value)
                composableFunction()
        }
    }
  }
}
@Composable()
fun composableFunction() {
    Text("appbar content")
}

onClick 不可组合的原因:所有的 Composable 函数同时被调用以完全组合 UI.而 onClick 在 UI 已经组合之后被调用.所以你需要使用状态来重构 UI 并在 onClick 发生后加载可组合函数.

Reason because onClick is not composable: All Composable function are called at the same time to compose the UI completely.While onClick is called later after the UI is already composed. So you need to use the state to recompose the UI and load composable function after onClick occur.

这篇关于Jetpack compose AppBarIcon 抱怨“调用@Composable 函数的函数必须用@Composable 标记";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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