我的代码出现了一些未解决的情况,
我的目标是更改“设备”列表中项目的属性(更新布尔值),
更改应该会导致视图重组,但这并没有发生,
此外,我可以看到该项目确实随调试器而更改,但它也会导致添加一个附加项目(没有包含更改的旧副本)以显示在我的列表中。
你知道我对新的价值分配有什么错误吗?
视图模型
private val _uiState = mutableStateOf(BTPairingState())
val uiState: State<BTPairingState> get() = _uiState
这就是我编辑列表中项目的方式
if (handlerDeviceResponse.status != null) {
viewModelScope.launch {
uiState.value.devices.find { it.macAddress == handlerDeviceResponse.device.macAddress }?.isConnected = handlerDeviceResponse.status
_uiState.value = uiState.value.copy()
}
}
BT配对状态:
data class BTPairingState (
val devices: MutableList<BtDeviceItemUiModel> = mutableListOf(),
val deviceType: DeviceType = DeviceType.RFID,
)
数据类
data class BtDeviceItemUiModel(
val name: String,
val macAddress : String,
var isConnected: Boolean = false
)
屏幕:
@Destination
@Composable
fun BTPairScreen(
viewModel: BTPairViewModel = hiltViewModel(),
) {
val state = viewModel.uiState
BTPairDevices(state.value.devices) { viewModel.deviceItemClicked(it) }
Replace var isConnected
by val isConnected
.
然后,更换val devices: MutableList<BtDeviceItemUiModel> = mutableListOf()
by val devices: List<BtDeviceItemUiModel> = emptyList()
.
IOW,停止使用可变值inside您所在州的。
然后,您可以修改代码以更新您的MutableState
具有新值,使用类似以下内容:
if (handlerDeviceResponse.status != null) {
val newDevices = uiState.value.devices.map { device ->
if (device.macAddress == handlerDeviceResponse.device.macAddress) {
device.copy(isConnected = handlerDeviceResponse.status)
} else {
it
}
}
_uiState.value = uiState.value.copy(devices = newDevices)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)