我的代码出现了一些 Unresolved 情况, 我的目标是更改“设备”列表中项目的属性(更新 bool 值), 更改应该会导致 View 重组,但这并没有发生, 此外,我可以看到该项目确实随调试器而更改,但它也会导致添加一个附加项目(没有包含更改的旧副本)以显示在我的列表中。
你知道我的新值分配是怎么错的吗?
View 模型
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) }
最佳答案
替换var isConnected
通过val isConnected
.
然后,替换 val devices: MutableList<BtDeviceItemUiModel> = mutableListOf()
通过val devices: List<BtDeviceItemUiModel> = emptyList()
.
IOW,停止在您的状态内部使用可变值。
然后,您可以修改代码以更新您的 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)
}
关于android - _uiState.value = uiState.value.copy() 不会导致重组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73100123/