LazyColumn和可变列表-如何更新? [英] LazyColumn and mutable list - how to update?
本文介绍了LazyColumn和可变列表-如何更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Jetpack Compose的新手,我花了几个小时来了解如何让LazyColumn更新我更新的列表。我读到更新LazyColumn需要一个不可变的列表,但我似乎无法使其工作。
代码如下:
@Composable
fun CreateList() {
var myList : List<DailyItem> by remember { mutableStateOf(listOf())}
myList = getDailyItemList() // Returns a List<DailyItem> with latest values and uses mutable list internally
// Function to refresh the list
val onUpdateClick = {
// Do something that updates the list
...
// Get the updated list to trigger a recompose
myList = getDailyItemList()
}
// Create the lazy column
...
}
我尝试了几种方法,要么在点击更新按钮时列表永远不会更新,要么只更新第一个项目,而不更新列表中的其他项目。我看了文档,里面写着这个,但我不明白:
不使用不可观察的可变对象,我们建议您使用 可观察的数据持有者,如State<;List&>和不可变的 Listof()。
如何更新列表以更新LazyColumn?
推荐答案
使用SnapshotStateList
,列表是可变的。任何修改(添加、删除、清除...)将在LazyColumn
中触发更新。
类似于mutableListOf()
(对于MutableList
),有mutableStateListOf()
创建SnapshotStateList
。
扩展函数swapList()
只是将clear()
和addAll()
调用组合在一起,将旧列表替换为新列表。
fun <T> SnapshotStateList<T>.swapList(newList: List<T>){
clear()
addAll(newList)
}
@Composable
fun CreateList() {
val myList = remember { mutableStateListOf<DailyItem>() }
myList.swapList(getDailyItemList()) // Returns a List<DailyItem> with latest values and uses mutable list internally
// Function to refresh the list
val onUpdateClick = {
// Do something that updates the list
...
// Get the updated list to trigger a recompose
myList.swapList(getDailyItemList())
}
// Create the lazy column
...
}
这篇关于LazyColumn和可变列表-如何更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文