【问题标题】:Error message: '@Composable invocations can only happen from the context of a @Composable function' when trying to use 'let'错误消息:“@Composable 调用只能在 @Composable 函数的上下文中发生”尝试使用“let”时
【发布时间】:2021-12-15 05:12:41
【问题描述】:

我在 compose 中尝试了范围函数,但有些东西让我感到困惑。 我在位置 1 遇到错误:'@Composable 调用只能在 @Composable 函数的上下文中发生',但我不知道为什么。

@Composable
fun scope_test() {
    val isOk: Boolean? = false
    Column() {
        isOk?.let {
            Text(text = "That's it!")
        } ?: {
            Text(text = "Nothing!") // place 1: error
        }
        isOk?.let {
            Text(text = "That's it!")
        } ?: run { Text(text = "Nothing!") }

        isOk?.let {
            Text(text = "That's it!")
        } ?: Text(text = "Nothing!")
    }
}

【问题讨论】:

    标签: android kotlin android-jetpack-compose


    【解决方案1】:

    看起来 Kotlin 中的代码块并不能自行执行。即使在该块中您使用标准 Kotlin 语句,Android Studio 也会将它们灰显,就像它们是多余的(它们不执行)。您需要像在第二个示例中那样调用run 函数。

    Here 是来自 Kotlin 论坛的类似问题,我发现它很有帮助。

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多