androidkotlinandroid-jetpackandroid-jetpack-compose

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


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

Solution

  • 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.