Jetpack Compose:列表更改时更新可组合项

Jetpack Compose: Update composable when list changes

我在屏幕上有一个可组合项,它显示了曲目项目(收藏夹)列表:

var favourites: MutableList<Track> by mutableStateOf(mutableListOf())
@ExperimentalFoundationApi
@Composable
private fun ResultList(model: FreezerModel) {
    with(model) {
        if (favourites.isEmpty()) NoDataMessage("No favourites yet")
        else {
            LazyColumn(state = rememberLazyListState()) {
                items(favourites) {
                    TrackCard(it, model)
                }
            }
        }
    }
}

关于点击事件,我正在更新我的收藏夹列表(add/remove 项)。我怎样才能让我的可组合项立即反映这些变化(比如 re-draw 本身或类似的东西)?到目前为止,它只在我第一次切换到另一个屏幕时有效。

感谢您的意见!

你需要使用一个MutableStateList<T>,这样Compose才能在状态改变时自动重组。

来自official doc

Caution: Using mutable objects such as ArrayList<T> or mutableListOf() as state in Compose will cause your users to see incorrect or stale data in your app.

在您的代码中使用

val favourites by mutableStateListOf<Track>()

而不是

var favourites: MutableList<Track> by mutableStateOf(mutableListOf())

只需从 lazyColumnFor 参数列表中删除 state = rememberLazyListState() 即可满足您的情况。

根据文档,如果我们使用 rememberLazyListState() 那么 :-

Changes to the provided initial values will not result in the state being recreated or changed in any way if it has already been created.

这样做之后,通常更新列表应该可以正常工作。将不可变列表 ( list ) 而不是 mutableList 公开给可组合项也是一个好习惯。

例如使用:-

var favourites by mutableStateOf(listOf<FavoriteItem>())

然后 add/remove/update 使用 :-

的列表
favourites = favourites + newList // add 
favourites = favourites.toMutableList().also { it.remove(item) } // remove