![](/img/trans.png)
[英]Do we still need LiveData in Jetpack Compose, or we can just use Compose State?
[英]Jetpack Compose – Which dependency do I need to use to be able to use state delegates?
代码实验室中提供的示例出现编译时错误。
这是视图模型
class VM : ViewModel() {
val isVisible = MutableStateFlow(true).asStateFlow()
}
这就是我想写的:
@Composable
fun Whatever(vm: VM = viewModel()) {
val isVisible by vm.isVisible.collectAsState(true)
// Use is visible here
}
但它会产生以下错误:
类型 'State<TypeVariable(R)>' 没有方法 'getValue(Nothing?, KProperty<*>)' 因此它不能用作委托
这真的很奇怪,因为我可以这样使用它:
@Composable
fun Whatever(vm: VM = viewModel()) {
val isVisible = vm.isVisible.collectAsState(true)
if(isVisible.value) { … }
}
我需要引入什么依赖项才能使委托工作?
这是我的依赖项:和compose_version = 1.0.0-beta01
dependencies {
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation "androidx.activity:activity-compose:1.3.0-alpha03"
implementation "androidx.compose.runtime:runtime:$compose_version"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.foundation:foundation-layout:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.material:material-icons-extended:$compose_version"
implementation "androidx.compose.foundation:foundation:$compose_version"
implementation "androidx.compose.animation:animation:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
implementation "androidx.compose.runtime:runtime:$compose_version"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0'
// Kotlin coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation 'androidx.appcompat:appcompat:1.3.0-beta01'
implementation 'androidx.activity:activity-ktx:1.2.0'
implementation 'androidx.core:core-ktx:1.5.0-beta02'
implementation "androidx.activity:activity-compose:1.3.0-alpha03"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02"
androidTestImplementation 'androidx.test:rules:1.3.0'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation "androidx.compose.ui:ui-test:$compose_version"
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}
如 文档中所述,尝试添加以下导入:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.