I'm trying to get a value from LiveData with observeAsState in jetpack compose, but I get a weird error

Type 'State<List?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate

Code

@Composable
fun UserScreen(userViewModel:UserViewModel){
    val items: List<User> by userViewModel.fetchUserList.observeAsState()
    UserList(userList = items)
}

enter image description here

ViewModel

class UserViewModel: ViewModel() {

    private val dataSource = UserDataSource()
    val fetchUserList = liveData {
        emit(dataSource.dummyUserList)
    }
}

推荐答案

如果出现未定义observeAsState或getValue的编译器错误,请确保有以下导入:

import androidx.compose.runtime.getValue

import androidx.compose.runtime.livedata.observeAsState

这些信息来自"Using State in Jetpack Compose"代码库中的第4步.

Kotlin相关问答推荐

使用Jackson反序列化HTML列表时出现MismatchedInputResponse

如何在 Big Data 中使用Inc过滤器?

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

Kotlin—从列表中枚举属性计算不同值的数量

在Mapstruct中重用@映射定义

循环中的每个元素都应填充行中可用的所有可用空间

正则表达式 FindAll 不打印结果 Kotlin

Kotlin 和 Java 字符串拆分与正则表达式的区别

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

Mockito 的 argThat 在 Kotlin 中返回 null

空对象引用上的 TransitionSet ArrayList.size()

在kotlin中初始化类变量的正确位置是什么

android Room 将 Null 作为非 Null 类型返回

如何在Kotlin中使方法param可变?

Dagger +Kotlin 不注入

Lint 错误:可疑的相等判断:在 Object DiffUtilEquals 中未实现 equals()

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

旋转 kotlin 数组

从 java 活动 *.java 启动 kotlin 活动 *.kt?

Kotlin反射不可用