我用Jetpack Compose构建了许多项目和组件.我已经阅读了有关StackOverFlow的文档和其他教程、网站和帖子.

我不清楚什么时候我可以在另一个可组合程序中使用可组合程序和可组合函数,尤其是使用LazyColumn.

我有一些组件,在LazyColumn中使用RowColumn.其他时候,我try 创建一个itemsIndexed列表,创建一系列的RowCard,我得到一个@Composable invocations can only happen from the context of a @Composable function的错误.

LazyColumn不被认为是@Composable函数吗?整个LazyColumn都在@Composable函数中.

我对上下文从可组合环境到不可组合环境的变化感到困惑.

有人能解释一下吗?我搞混了什么?

推荐答案

@Composable invocations can only happen from the context of a @Composable function

正如上面所说,您需要从一个带有@Composable注释的函数中调用一个Composable

如果你判断LazyColumn函数签名

@Composable
fun LazyColumn(
    // rest of the params
    content: LazyListScope.() -> Unit
) {

}

你会发现内容不是可组合的.另一方面,items函数使用itemContent作为可组合函数

inline fun <T> LazyListScope.items(
    items: List<T>,
    noinline key: ((item: T) -> Any)? = null,
    noinline contentType: (item: T) -> Any? = { null },
    crossinline itemContent: @Composable LazyItemScope.(item: T) -> Unit
) = items(
    count = items.size,
    key = if (key != null) { index: Int -> key(items[index]) } else null,
    contentType = { index: Int -> contentType(items[index]) }
) {
    itemContent(items[it])
}

因此,您可以调用可组合函数,如Column inside item函数.

items(myItems) { myItem: MyItem ->
    Column{

    }
}

ColumnRowBox等函数的XScope个函数都标有

@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope.() -> Unit
) {
    val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment)
    Layout(
        content = { ColumnScopeInstance.content() },
        measurePolicy = measurePolicy,
        modifier = modifier
    )
}

正因为如此,你可以在ColumnRowBox中再拨打Composable.

Kotlin相关问答推荐

Kotlin -从列表中获取特定过滤器的唯一列表值

合并状态流

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

如何在 Kotlin 中初始化 Short 数组?

TestContainers PostgreSQLContainer 与 Kotlin 单元测试:Not enough information to infer type variable SELF

Kotlin 无法找到或加载主类

@InlineOnly 注释是什么意思?

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Kotlin-Java 互操作不能与可变参数一起使用

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

Dagger2 Qualifier 不适用于 Kotlin?

如何使用Kotlin Dokka记录主构造函数参数

什么是开放式property?为什么我不能将其设置器设为private私有?

如何将map函数应用于Kotlin中的数组并更改其值?

如何在Android Studio 4.1中默认启用Kotlin Android扩展

在 Kotlin 函数上使用 Mokito anyObject() 时,指定为非 null 的参数为 null

具有泛型param的Kotlin抽象类和使用类型param的方法

Android Studio - java.io.IOException:无法生成 v1 签名

从另一个列表创建一个列表

Kotlin Coroutines:等待多个线程完成