键入“状态<列表<用户>?>"没有方法"getValue(Nothing ?, KProperty< *>))",因此它不能充当委托 [英] Type 'State<List<User>?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
问题描述
我正在尝试在jetpack中使用observeAsState从LiveData中获取一个值,但出现一个奇怪的错误
I'm trying to get a value from LiveData with observeAsState in jetpack compose, but I get a weird error
键入状态<列表?>"没有方法'getValue(Nothing ?, KProperty< *>)),因此它不能充当代理人
Type 'State<List?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
代码
@Composable
fun UserScreen(userViewModel:UserViewModel){
val items: List<User> by userViewModel.fetchUserList.observeAsState()
UserList(userList = items)
}
class UserViewModel: ViewModel() {
private val dataSource = UserDataSource()
val fetchUserList = liveData {
emit(dataSource.dummyUserList)
}
}
推荐答案
如果遇到未定义observeAsState或getValue的编译器错误,请确保您具有以下导入:
If you get a compiler error that observeAsState or getValue are not defined make sure you have the following imports:
导入androidx.compose.runtime.getValue
import androidx.compose.runtime.getValue
导入androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.livedata.observeAsState
该信息来自步骤4中的"Jetpack Compose中的使用状态".代码实验室.
This information is from Step #4 in the "Using State in Jetpack Compose" codelab.
这篇关于键入“状态<列表<用户>?>"没有方法"getValue(Nothing ?, KProperty< *>))",因此它不能充当委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!