我正在尝试更新保留为可组合 View 状态的列表,但即使列表的值发生更改,可组合 View 也不会重新组合。
var list = remember {mutableStateOf(getListOfItems())}
ItemListView({ selectedItem ->
list.value = updateList(selectedItem, list.value)
}, list.value)
private fun updateList(selectedItem: String,
itemsList: List<Product>): List<Product> {
for (item in itemsList){
// selected item in the view is updated
item.selected = item.name == selectedItem
}
return itemsList
}
知道为什么可组合项没有更新吗?我注意到使用列表作为状态时会出现问题。
最佳答案
您需要更新 MutableState
的 value
(在您的示例中是一个 List
),以触发重组而不是您设置的值的任何属性到MutableState
。
@Stable
interface MutableState<T> : State<T> {
override var value: T
operator fun component1(): T
operator fun component2(): (T) -> Unit
}
但是还有另一个名为 mutableStateListOf()
的函数,当您添加或删除项目或使用新实例更新现有项目时,它可以触发重组。
val list =remember {
mutableStateListOf< Product>().apply {
addAll(getListOfItems())
}
}
关于android - 在 android Jetpack compose 中使用列表处理状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73118699/