簡體   English   中英

如果屬性發生更改,項目不會更新(Jetpack Compose)

[英]Item is not updating if an attribute is changed (Jetpack Compose)

我正在繪制設備列表

@Composable
fun DeviceListScreen(){
  val model: DeviceListViewModel = hiltViewModel()

  val myDevices: List<MyDevice> by model.myDevices.observeAsState(emptyList())
  for(device in myDevices)
    Device(device)
}

在 model 我有一個 livedata

private val items: List<MyDevice> = ArrayList()
private val _myDevices = MutableLiveData<List<MyDevice>> (emptyList())
val myDevices: LiveData<List<MyDevice>> = _myDevices

我更改項目的內容然后更新實時數據

items[0].signal = 54
_myDevices.value = items

但是數據不會在 ui 中更新。 我猜這是因為指向列表的指針沒有改變,列表中的項目數也沒有改變,因此 compose 不會更新這些數據。

2022 年 12 月 8 日更新

我剛剛遇到了和你一樣的問題。 我已經成功解決了它,所以我為您的問題調整的以下解決方案也應該可以正常工作:

fun updateSignal(idOfSelectedDevice: Int) {
  _myDevices.value = myDevices.value?.map { device ->
    if (device.id == idOfSelectedDevice) device.copy(
        signal = <YOUR_DESIRED_VALUE>
    ) else device
  }
}

您可以嘗試將items包裝在自己的數據 class 中:

data class ItemsList(val devices: List<MyDevice> = ArrayList())

然后將項目更改為private val items: ItemsList = ItemsList()

Since you are using your own data class for items , you can then access the copy function which copies an existing object into a new object and should therefore trigger the update of the liveData object:

_myDevices.value = _myDevices.value?.copy(items = items.devices.apply { 
    this[0].signal = 54
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM