简体   繁体   English

mutableStateListOf 更改未反映在 UI 中 - Jetpack Compose

[英]mutableStateListOf change not reflecting in UI - Jetpack Compose

in my ViewModel:在我的视图模型中:

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

fun likePost(newPost: Post){
        val index = _itemList.indexOf(newPost)
        _itemList[index] = _itemList[index].copy(isLiked = true)
}

Here my Post data class:这是我的 Post 数据类:

data class Post(
    val id: Int,
    val name: String, 
    val isLiked: Boolean = false,
)

And here my Composable:这里是我的可组合:

val postList = viewModel.itemList

LazyRow(content = {

    items(postList.size) { i ->
        val postItem = postList[i]
        PostItem(
            name = postItem.name,
            isLiked = postItem.isLiked,
            likePost = { viewModel.likePost(postItem)}
        )

    }
}) 

The change does not update in the UI instantly, I first have to scroll the updated item out of the screen so it recomposes or switch to another Screen and go back to see the change.更改不会立即在 UI 中更新,我首先必须将更新的项目滚动到屏幕之外,以便它重新组合或切换到另一个屏幕并返回查看更改。

You are returning a List<> effectively and not MutableStateList from your ViewModel.您正在从 ViewModel 有效地返回List<>而不是MutableStateList

If you want the list to not be mutable from the view, I happen to use MutableStateFlow<List<>> and return StateFlow<List<>> .如果您希望列表在视图中不可变,我碰巧使用MutableStateFlow<List<>>并返回StateFlow<List<>> You could also just convert it to a list in your composable.您也可以将其转换为可组合文件中的列表。

Edit:编辑:

//backing cached list, or could be data source like database
private val deviceList = mutableListOf<Device>()

private val _deviceListState = MutableStateFlow<List<Device>>(emptyList())
val deviceListState: StateFlow<List<BluetoothDevice>> = _deviceListState


//manipulate and publish
fun doSomething() {
    _deviceListState.value = deviceList.filter ...
}

In your UI在您的用户界面中

val deviceListState = viewModel.deviceListState.collectAsState().value

For some reason it doesn't like updating, it will add and delete and update instantly.由于某种原因它不喜欢更新,它会立即添加和删除和更新。 You have to do it this way when updating for our to update the state.您必须在更新时这样做才能更新状态。

fun likePost(newPost: Post){
     val index = _itemList.indexOf(newPost)
     _itemList[index] = _itemList[index].copy()
    _itemList[index].isLiked = true

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM