[英]Jetpack Compose - mutableStateOf() not updating
I got a ScreenState data class in my ViewModel:我的 ViewModel 中有一个 ScreenState 数据类:
data class ScreenState(
var isLoading: Boolean = true,
val items: List<Posts> = emptyList()
)
and a mutableStateof:和一个可变状态:
private val _homeScreenState = mutableStateOf(ScreenState())
val homeScreenState: State<ScreenState> = _homeScreenState
Updating the isLoading property works fine, the change gets send to my UI:更新 isLoading 属性可以正常工作,更改会发送到我的 UI:
_homeScreenState.value = _homeScreenState.value.copy(isLoading = true)
But updating an item inside my List<Posts>
does not work.但是更新我的
List<Posts>
中的项目不起作用。 Here is how I try to do it:这是我尝试这样做的方法:
val updatedList = homeScreenState.value.items.toMutableList()
val index = updatedList.indexOfFirst { it.id == passedPost.id }
updatedList[index] = updatedList[index].copy(isLiked = true)
_homeScreenState.value = _homeScreenState.value.copy(items = updatedList)
I'm trying to update the isLiked Boolean inside my Post data class and show the change in the UI.我正在尝试更新我的 Post 数据类中的 isLiked Boolean 并在 UI 中显示更改。 I do understand, that this is a normal behaviour and that the mutableStateOf does not update because the ScreenState itself does not update but the item inside the
List<Post>
of the ScreenState.我明白,这是正常行为,mutableStateOf 不会更新,因为 ScreenState 本身不会更新,而是 ScreenState 的
List<Post>
中的项目。
The problem is that I don't know how to trigger the UI to update.问题是我不知道如何触发 UI 更新。
EDIT This is my Post Data Class:编辑这是我的帖子数据类:
data class Post(
val id: Int,
val name: String,
val description: String,
val isLiked: Boolean = false,
)
data class Post(
val id: Int,
val name: String,
val description: String,
val isLiked: MutableState<Boolean> = mutableStateOf(false),
)
or或者
class Post(
val id: Int,
val name: String,
val description: String,
isLiked: Boolean = false,
){
val isLiked by mutableStateOf(isLiked)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.