15

Can someone explain me what's the main purpose of the 'key' parameter inside items/itemsIndexed function of LazyListScope? 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. 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. 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.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Stefan
  • 2,829
  • 5
  • 20
  • 44

2 Answers2

27

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. 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.

To combat this, you can provide a stable and unique key for each item, providing a block to the key parameter. Providing a stable key enables item state to be consistent across data-set changes:

@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)
        }
    }
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • What do they mean by `stable` key? Does this have something to do with [stability in sorting algorithms](https://www.geeksforgeeks.org/stability-in-sorting-algorithms/)? – JHowzer Aug 23 '22 at 18:01
  • That means it doesn't have to be random – jgnt32 Aug 29 '22 at 11:50
  • 1
    @JHowzer I believe this to mean a key that does not change throughout dataset changes. In other words, imagine you add or remove items from the list, remaining list item keys should not change after the operation. – HenriqueMS Jul 08 '23 at 19:00
-1

you can use this way

@Composable
fun A(list: MutableList<Model>) {
    Column {
        LazyColumn {
            items(
                count = list.size,
                key = {
                    list[it].id
                }, itemContent = { index ->
                    Text(text = list[index].text)
                }
            )
        }
    }
}
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78