Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 280
SNM Avatar asked Sep 13 '20 20:09

SNM


4 Answers

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.

like image 167
Eric Cen Avatar answered Nov 18 '22 07:11

Eric Cen


To fix the error add the following imports:

// for a 'val' variable
import androidx.compose.runtime.getValue

// for a `var` variable also add
import androidx.compose.runtime.setValue

// or just
import androidx.compose.runtime.*

To use a variable as a property delegate you should provide getValue operator function for read-only val variables and getValue and setValue functions for var variables.

To read more about how property delegates and state are combined in jetpack compose see Use remember to create internal state in a composable documentation section. There's also an explanation in Thinking in Compose video.

like image 28
Valeriy Katkov Avatar answered Nov 18 '22 05:11

Valeriy Katkov


You could use: import androidx.compose.runtime.*


Necessary imports are:

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf

var value by remember { mutableStateOf("") }
like image 28
Braian Coronel Avatar answered Nov 18 '22 05:11

Braian Coronel


For me manually/explicitly importing both the below apis worked to resolve this compilation issue,

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

Here is the reference, https://developer.android.com/jetpack/compose/state#state-in-composables

like image 20
Karthik H Avatar answered Nov 18 '22 06:11

Karthik H