Compose 更新列表中的元素
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Compose 更新列表中的元素相关的知识,希望对你有一定的参考价值。
第一步确定是 mutableStateListOf
var newData = remember
mutableStateListOf<HaiveCheckBox>()
第二部 常规的 更新所在元素是不生效的。
但是删除和新增是生效的
正确写法:
newData
.find it.isChecked
?.let
val tempData = it
//获取索引位置
val index = newData.indexOf(tempData)
newData.removeAt(index)
newData.add(index,tempData.copy(isChecked = false))
newData
.find it == newData[index]
?.let
val tempData = it
//获取索引位置
val index = newData.indexOf(tempData)
newData.removeAt(index)
newData.add(index,tempData.copy(isChecked = true))
错误示例 :
也是我们以往写法比较多的一种。
newData.forEach
it.isChecked = false
newData[index].isChecked = true
上面的可以抽取共用方法
fun <T> SnapshotStateList<T>.updateElement(
predicate: (T) -> Boolean, transform: (T) -> T
)
this.find(predicate)?.let
val tempData = it
val index = this.indexOf(tempData)
this.removeAt(index)
this.add(index, transform(it))
更新就变成了
newData.updateElement(predicate = it.isChecked, transform =
it.copy(isChecked = false)
)
newData.updateElement(predicate = it == newData[index], transform =
it.copy(isChecked = true)
)
以上是关于Compose 更新列表中的元素的主要内容,如果未能解决你的问题,请参考以下文章