简体   繁体   English

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

[英]Jetpack Compose: Update composable when list changes

I've got a composable on a Screen which shows a list of Track items (favourites):我在屏幕上有一个可组合的,它显示了跟踪项目(收藏夹)的列表:

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

On click events, I am updating my favourites list (add/remove item).在点击事件上,我正在更新我的收藏夹列表(添加/删除项目)。 How can I make my composable reflect these changes immediately (like to re-draw itself or something similar)?我怎样才能让我的可组合立即反映这些变化(比如重新绘制自己或类似的东西)? So far, it only works when I first switch to another screen.到目前为止,它仅在我第一次切换到另一个屏幕时才有效。

Thanks for your inputs!感谢您的投入!

You need to use a MutableStateList<T> so that Compose can automatically recompose when the state changes.您需要使用MutableStateList<T>以便 Compose 可以在 state 更改时自动重新组合。

From 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.注意:在 Compose 中使用可变对象(例如ArrayList<T>mutableListOf()作为 state 将导致您的用户在您的应用中看到不正确或陈旧的数据。

In your code use在您的代码中使用

val favourites by mutableStateListOf<Track>()

instead of代替

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

Just removing state = rememberLazyListState() from the lazyColumnFor params list should work in your case.只需从lazyColumnFor参数列表中删除state = rememberLazyListState()就应该适用于您的情况。

According to the doc if we use rememberLazyListState() then:-根据文档,如果我们使用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.对提供的初始值的更改不会导致 state 被重新创建或以任何方式更改(如果已创建)。

After doing so, normally updating the list should work fine.这样做之后,通常更新列表应该可以正常工作。 Also its a good practice to expose an immutable list ( list ) instead of a mutableList to the composable.将不可变列表( list )而不是mutableList给可组合对象也是一种好习惯。

For example use:-例如使用:-

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

then add/remove/update the list by using:-然后使用以下add/remove/update列表:-

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

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

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