【问题标题】:LazyColumn and mutable list - how to update?LazyColumn 和可变列表 - 如何更新?
【发布时间】:2021-06-19 11:55:53
【问题描述】:

我是 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 和不可变的 listOf().

如何更新列表以便更新 LazyColumn?

【问题讨论】:

    标签: android-jetpack-compose


    【解决方案1】:

    使用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
        ...
    }
    

    【讨论】:

    • 谢谢!!像魅力一样工作!
    • 我试过这样做,但对我没有用。我的代码在这里:pastebin.com/RfsRf8bf
    • @KaranAhuja 您正在更新项目的内容,而不是项目本身。 MutableStateList 不会知道项目中的内容是否发生变化。检查这个stackoverflow.com/questions/69718059/…如果您需要更多,请考虑为它创建一个新问题。
    • @OmKumar 感谢您的评论。这正是我想要的。我还检查了您提到的另一个问题。这正是我的问题。谢谢兄弟。
    【解决方案2】:

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

    好了,流程是这样的,

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

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

    回到问题,

    我们创建一个变量,比如val mList: List&lt;Int&gt; by remember { mutableStateOf (listOf()) }

    Lazycolumn{
    items(items = mList){
    Text(it)
    }
    }
    
    Button(onClick = { mList = mList + listOf(mList.size())})
    

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

    【讨论】:

    • 感谢您提供额外信息。当我对这个概念不熟悉时,请欣赏它!
    • 其实这是正确的做法。阅读文档!这很简单。检查任何官方示例应用程序。这是用法
    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 2023-02-05
    • 2023-01-15
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多