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

我的未来我决定 提交于 2020-12-08 07:27:55

问题


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)
}

ViewModel

class UserViewModel: ViewModel() {

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

回答1:


If you get a compiler error that observeAsState or getValue are not defined make sure you have the following imports:

import androidx.compose.runtime.getValue

import androidx.compose.runtime.livedata.observeAsState

This information is from Step #4 in the "Using State in Jetpack Compose" codelab.




回答2:


I think type of items must be nullable since you observing LiveData:

val items: List<User>? by userViewModel.fetchUserList.observeAsState()


来源:https://stackoverflow.com/questions/63875411/type-statelistuser-has-no-method-getvaluenothing-kproperty-and-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!