Android Jetpack合成中数据类的更新策略

ss2ws0br  于 2023-01-07  发布在  Android
关注(0)|答案(3)|浏览(125)

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

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

structuralEqualityPolicy()是可组合组件的更新策略,定义如下:
如果MutableState的值在结构上(==)相等,则将其视为等效的策略。
如果属性计数器更改为:counterState.counter++应更新可组合,但这不起作用。
我使用合成版本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()
}
xbp102n0

xbp102n01#

我会试试这个:

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

希望能成功安娜

azpvetkf

azpvetkf2#

因为组合体在MutableState<CounterState>上观察

val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }

当我们执行counterState.counter++时,state变量永远不会改变,即对象的地址是相同的。
假设我们这样做

counterState.value = CounterState()

这将触发状态更改。

suzh9iv8

suzh9iv83#

要触发一个新的组合,您的mutableState值应该被更新。在您的例子中,您只更新了值的内容,而组合无法知道它何时被更新。您可以简单地尝试以下操作:

Button(onClick = {
    counterState = counterState.copy(counter = counterState.counter + 1)
}) { ...

相关问题