类型 'State<List<User>?>' 没有方法 'getValue(Nothing?, KProperty<*>)' 因此它不能作为委托

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

我试图在 Jetpack Compose 中使用 observeAsState 从 LiveData 获取值,但我收到一个奇怪的错误

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

我认为项目的类型必须可以为空,因为您观察了 LiveData:

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

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

import androidx.compose.runtime.getValue

import androidx.compose.runtime.livedata.observeAsState

此信息来自“Using State in Jetpack Compose”代码实验室中的第 4 步。

要修复错误,请添加以下导入:

// 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.*

将变量用作 var 个变量的 property delegate you should provide getValue operator function for read-only val variables and getValue and setValue 函数。

要详细了解 属性 委托和状态如何在 Jetpack Compose 中组合,请观看 Use remember to create internal state in a composable documentation section. There's also an explanation in Thinking in Compose 视频。

就我而言,在 compose 应用程序中正是缺少导入导致了错误

import androidx.compose.getValue

尽管是进口货,我还是遇到了这个问题!花了一点时间,但后来我意识到我的问题在哪里,无论你观察到什么,变量都需要是 val 而不是 var:

在我的例子中是
var background: Int by currentBackgroundColor.observeAsState(0)

应该是:
val background: Int by currentBackgroundColor.observeAsState(0)

您需要导入

import androidx.compose.runtime.getValue

这将导入这个函数,基本上是 by

inline operator fun <T> State<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value

您可以使用:import androidx.compose.runtime.*


必要的导入是:

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

添加依赖项解决了我的问题:

implementation "androidx.compose.runtime:runtime:$compose_version"

感谢

对我来说 manually/explicitly 导入以下两个 api 解决了这个编译问题,

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

这是参考, https://developer.android.com/jetpack/compose/state#state-in-composables