gpt4 book ai didi

android-jetpack-compose - LazyColumn 和可变列表 - 如何更新?

转载 作者:行者123 更新时间:2023-12-04 16:24:30 34 4
gpt4 key购买 nike

我是 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
...
}
我已经尝试了几件事,要么在点击更新按钮时列表从未更新,要么只更新第一个项目而不更新列表中的其余项目。我查看了文档,上面写着,但我不明白:

Instead of using non-observable mutable objects, we recommend you usean observable data holder such as State<List> and the immutablelistOf().


如何更新列表以便更新 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
...
}

关于android-jetpack-compose - LazyColumn 和可变列表 - 如何更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68046535/

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