gpt4 book ai didi

android - Jetpack 撰写 : Update composable when list changes

转载 作者:行者123 更新时间:2023-12-04 14:44:04 26 4
gpt4 key购买 nike

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

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)
}
}
}
}
}
在点击事件上,我正在更新我的收藏夹列表(添加/删除项目)。我怎样才能让我的可组合立即反射(reflect)这些变化(比如重新绘制自己或类似的东西)?到目前为止,它仅在我第一次切换到另一个屏幕时才有效。
感谢您的投入!

最佳答案

您需要使用 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())

关于android - Jetpack 撰写 : Update composable when list changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67252538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com