如何更新列表状态以在 Compose 中显示更新

How to Update List State to show updates in Compose

我正在尝试创建一个动态更新的列表,它可能会更改几个或多个字段。 updateItems() 的初始更新很好,一切都显示正常, 然而,Jetpack Compose 会忽略 updateOneItem 的连续更新。

// ****ViewModel code
val _itemList: MutableStateFlow<List<Item>> = MutableStateFlow(emptyList())

fun updateItems() {
    viewModelScope.launch {
        _itemList.value = itemRepository.getItems()
    }
}

fun updateOneItem(newVal:Int){
    _itemList.value[_itemList.value.indexOf(item)].weight = newVal
    //this is where I cannot have an update show up in compose no matter what
    _itemList.tryEmit(_itemList.value)
}
// ****continued ViewModel Code

我一直在尝试复制列表,也尝试过 mutableStateListOf,但到目前为止没有任何效果。

Flow 无法知道包含对象的某些可变 属性 何时更改。当您尝试发射它时,它会检查对象的地址 - 它与原来相同 - 并忽略发射。

您可以通过创建列表的副本来强制执行它。

但最干净的方法是使用 mutableStateListOf 并使您的项目成为不可变数据 class,然后您可以通过创建副本轻松更新它。查看 Why is immutability important in functional programming?

它可以看起来像这样:

data class Item(val weight: Int)

private val _itemList = mutableStateListOf<Item>()
val itemList: List<Item> = _itemList

fun updateItems() {
    viewModelScope.launch {
        _itemList.addAll(itemRepository.getItems())
    }
}

fun updateOneItem(newVal:Int){
    val index = _itemList.indexOf(item)
    _itemList[index] = _itemList[index].copy(weight = newVal)
}