Mac*_*kan 20 android-jetpack-compose
我是 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
...
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几件事,或者是点击更新按钮时列表从未更新,或者仅更新了第一个项目,但列表中的其余项目没有更新。我查看了文档,上面写着这一点,但我不明白:
我们建议您使用可观察的数据持有者,例如 State<List> 和不可变的 listOf(),而不是使用不可观察的可变对象。
如何更新列表以便更新 LazyColumn?
Om *_*mar 26
使用SnapshotStateList,列表是可变的。对列表的任何修改(添加、删除、清除……)都会触发LazyColumn.
与mutableListOf()(for 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
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16082 次 |
| 最近记录: |