简体   繁体   English

LazyColumn - Items 关键参数用途?

[英]LazyColumn - Items Key parameter purpose?

Can someone explain me what's the main purpose of the 'key' parameter inside items/itemsIndexed function of LazyListScope?有人能解释一下 LazyListScope 的 items/itemsIndexed function 中“key”参数的主要用途是什么吗? What do we get or don't get if we specify that parameter?如果我们指定该参数,我们会得到什么或不会得到什么? I'm not sure that I understand the official docs related to this parameter:我不确定我是否理解与此参数相关的官方文档:

key - a factory of stable and unique keys representing the item. key - 代表项目的稳定且唯一的密钥工厂。 Using the same key for multiple items in the list is not allowed.不允许对列表中的多个项目使用相同的键。 Type of the key should be saveable via Bundle on Android. If null is passed the position in the list will represent the key.密钥的类型应该可以通过 Android 上的 Bundle 保存。如果 null 被传递,列表中的 position 将代表密钥。 When you specify the key the scroll position will be maintained based on the key, which means if you add/remove items before the current visible item the item with the given key will be kept as the first visible one.当您指定键时,滚动 position 将根据键进行维护,这意味着如果您在当前可见项目之前添加/删除项目,则具有给定键的项目将保留为第一个可见项目。

I think the best answer is provided by the official doc :我认为最好的答案是由 官方文档提供的:

By default, each item's state is keyed against the position of the item in the list.默认情况下,每个项目的state都是针对列表中项目的 position键入的。 However, this can cause issues if the data set changes, since items which change position effectively lose any remembered state. If you imagine the scenario of LazyRow within a LazyColumn , if the row changes item position, the user would then lose their scroll position within the row.但是,如果数据集发生变化,这可能会导致问题,因为更改 position 的项目实际上会丢失任何记住的 state。如果您想象LazyRow中的LazyColumn场景,如果行更改项目 position,则用户将在其中丢失滚动条 position该行。

To combat this, you can provide a stable and unique key for each item, providing a block to the key parameter.为了解决这个问题,您可以为每个项目提供一个稳定且唯一的密钥,为key参数提供一个块。 Providing a stable key enables item state to be consistent across data-set changes :提供稳定的密钥可以使项目 state 在数据集更改之间保持一致

@Composable
fun MessageList(messages: List<Message>) {
    LazyColumn {
        items(
            items = messages,
            key = { message ->
                // Return a stable + unique key for the item
                message.id
            }
        ) { message ->
            MessageRow(message)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM