Android Jetpack Compose中数据类的更新策略

时间:2020-11-05 14:22:58

标签: android android-jetpack android-jetpack-compose

我尝试使用数据类中的对象,该对象将更新Composable并声明如下:

data class CounterState(var counter: Int = 0)
.....
val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }

structuralEqualityPolicy()是Composable的更新策略,并定义为:

将MutableState的值视为等效的策略 在结构上(==)相等。

如果属性计数器的更改如下:counterState.counter++应该更新Composable,但这不起作用。

我使用撰写版本1.0.0-alpha06

任何想法如何解决该问题?

import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.runtime.*
import androidx.ui.tooling.preview.Preview

data class CounterState(var counter: Int = 0)

@Composable
fun dataClassRemember() {
    val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }
    Column() {
        Button(onClick = {
            counterState.counter++
        }) {
            Text(text = "Increment")
        }
        Text(text = "Counter value is ${counterState.counter}")
    }
}

@Preview("dataClassRemember")
@Composable
fun dataClassRememberPreview() {
    dataClassRemember()
}

1 个答案:

答案 0 :(得分:0)

我会试试这个:

data class CounterState(var counter: Int by remember { mutableStateOf(0)})

希望它有效, 安娜