3

我是 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?

4

2 回答 2

11

使用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
    ...
}
于 2021-06-19T12:49:27.610 回答
0

查看基本思想是让 compose 将列表视为状态。现在,您可以使用 mutableStateOf(initialValue) 来实现,

好了,流程是这样的,。

我们创建一个变量,将其初始化为某事物的可变状态

然后我们将该变量分配给惰性列。不必将其分配给列的 items 参数,但这是我们的用例。否则,在包含惰性列的 Composable 中,您只需键入变量的名称,即使这样也可以工作,因为我们想要的只是 compose 以获取 Composable 正在读取此变量的消息。

回到问题,

我们创建一个变量,比如说val mList: List<Int> by remember { mutableStateOf (listOf()) }

Lazycolumn{
items(items = mList){
Text(it)
}
}

Button(onClick = { mList = mList + listOf(mList.size())})

单击该按钮会向列表中添加一个新数字,该数字会反映在 LazyColumn 的 UI 中。

于 2021-06-19T16:37:00.207 回答