簡體   English   中英

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

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

在我的視圖模型中:

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)
}

這是我的 Post 數據類:

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

這里是我的可組合:

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)}
        )

    }
}) 

更改不會立即在 UI 中更新,我首先必須將更新的項目滾動到屏幕之外,以便它重新組合或切換到另一個屏幕並返回查看更改。

您正在從 ViewModel 有效地返回List<>而不是MutableStateList

如果您希望列表在視圖中不可變,我碰巧使用MutableStateFlow<List<>>並返回StateFlow<List<>> 您也可以將其轉換為可組合文件中的列表。

編輯:

//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 ...
}

在您的用戶界面中

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

由於某種原因它不喜歡更新,它會立即添加和刪除和更新。 您必須在更新時這樣做才能更新狀態。

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