In Jetpack Compose lazy lists and grids, what do the key and contentType parameters of items() do, and what breaks without a key?
answer
- position is the default identity
- state follows the key
- must fit in a Bundle
- reuse only between same types
- itemKey for paged items
basics
~20 sWithout a key, a lazy item's state and the scroll anchor follow its position, so an insert or a re-sort attaches state to the wrong product. A unique, Bundle-saveable key ties them to the item; contentType limits reuse to like items.
solid answer
~50 sBy default each lazy item is identified by its index. When the data changes (a product inserted at the top, a re-sort), remembered and saved state such as an expanded card or a nested `LazyRow` scroll stays at the old position, and the scroll position stays at an index while the content under it shifts. Passing `key = { it.id }` to `items()` makes the key the identity: state moves with the item, the scroll position is kept on the first visible item's key, and `Modifier.animateItem()` (Compose 1.7 and later) can animate moves. The key must be unique and, on Android, a type a `Bundle` can hold. `contentType = { it.type }` tells Compose which items share a structure, so a composition is reused only between items of the same type. With Paging, `lazyPagingItems.itemKey { it.id }` and `itemContentType` give placeholders their own keys.
code
kotlin · 18 lines@Composable
fun ProductFeed(pager: Pager<Int, Product>) {
val products = pager.flow.collectAsLazyPagingItems()
LazyColumn {
items(
count = products.itemCount,
key = products.itemKey { it.id },
contentType = products.itemContentType { "product" },
) { index ->
val product = products[index]
if (product != null) {
ProductRow(product, Modifier.animateItem())
} else {
ProductRowPlaceholder()
}
}
}
}go deeper
Recall that items() takes a key lambda, that it should return the item's id, and that keys keep state with the right row when data changes.
Explain position as default identity, the Bundle-saveable rule, scroll position kept by key, animateItem needing keys, and contentType limiting reuse to like items.
Diagnose rows that show another product's state after a sort, crashes from duplicate or non-saveable keys, and paged lists that need itemKey and itemContentType for placeholders.
Decide which list conventions a team enforces, such as ids as keys everywhere and contentType on mixed feeds, and how review and lint rules make them stick.
## Identity in a lazy list A lazy layout keeps per-item state: values from `remember` and `rememberSaveable`, a nested `LazyRow`'s scroll position, a focused field, a running animation. It needs to know which item that state belongs to. **By default, an item's identity is its position** in the list or grid. Position works while the data never moves. In a shopping app it moves all the time: - a new product is inserted at the top of the grid; - the user re-sorts by price; - an item is removed from the cart list. With position as identity, the remembered state stays at index 3 while a different product now sits there. An expanded "details" panel opens on the wrong card; a category row's horizontal scroll jumps to another category. ## What `key` changes Every lazy DSL call accepts a **`key`**: `item(key = ...)`, `items(list, key = { it.id })`, `items(count, key = { index -> ... })`. With a key: 1. **State follows the item.** Remembered and saved state is stored per key, so when a product moves from index 3 to index 0 its state moves with it. 2. **The scroll position is kept by key.** The list stores the first visible item's key as well as its index. If items are added or removed before it, that item stays the first visible one even though its index changed. `LazyListState.requestScrollToItem` can override this for one measure pass. 3. **Item animations work.** `Modifier.animateItem()` animates appearance, disappearance and reordering, and it needs keys to find each item's new position. The rules on the key itself: - **Unique.** Using the same key for two items is not allowed. When two items with the same key are composed at the same time, the app crashes with an `IllegalArgumentException` saying the key was used multiple times. - **Stable.** Derive it from the data's identity (a product id), never from the index or a random value. - **Saveable in a `Bundle` on Android.** Item state is saved through the saveable-state machinery, so the key type must be one a `Bundle` can store: primitives, `String`, enums, `Parcelable`. A plain data class used as a key fails with "Type of the key ... is not supported. On Android you can only use types which can be stored inside the Bundle." ## What `contentType` changes Lazy layouts **reuse compositions**: when a row scrolls out, its composition can be reused for a row scrolling in, which is cheaper than building one from scratch. Reuse pays off only between items of similar structure. **`contentType`** (available since Compose 1.2) declares each item's type: ```kotlin LazyColumn { items( items = feed, key = { it.id }, contentType = { it.kind }, // e.g. Banner, ProductCard, Divider ) { entry -> FeedEntry(entry) } } ``` Compose then reuses compositions **only between items of the same type**, so it never composes a promo banner on top of what was a product card. `null` is a valid type, and all items with a `null` type count as compatible, which is the default. A list with one kind of row needs no `contentType`; a mixed list benefits from it. | Parameter | Answers the question | Missing it means | |---|---|---| | `key` | Which item is this? | state and scroll anchor follow positions | | `contentType` | What shape is this? | reuse may pair unlike items | ## Keys with Paging `collectAsLazyPagingItems()` turns a `Flow<PagingData<T>>` into `LazyPagingItems<T>`. When placeholders are enabled, an index may hold `null` while its page loads, so `key = { items[it]!!.id }` would crash or trigger loads. Paging Compose provides helpers instead: - **`lazyPagingItems.itemKey { it.id }`** returns a key factory that uses your key for loaded items and a placeholder key for `null` ones. It reads with `peek`, which does not trigger page loads. - **`lazyPagingItems.itemContentType { it.kind }`** gives placeholders their own content type. - Read the item in the row with **`lazyPagingItems[index]`**: that `get` notifies Paging of the access and triggers loading, whereas `peek` does not. ## Common mistakes - Using the index as the key, which restores the default behaviour under another name. - Passing a whole model object or a non-saveable data class as the key. - Deriving keys that collide, such as a product id shared by two size variants shown as separate rows. - Adding `animateItem()` without keys and expecting reorder animations. How a feed should diff by stable id as a cross-platform design is covered in the mobile system design material; these parameters are how Compose implements it.
- Why can't you pass the whole Product data class as the key in a Compose lazy list on Android?Item state is saved through Compose's saveable-state holder, which on Android stores it in a `Bundle`. The key must therefore be a type a `Bundle` can hold: a primitive, `String`, enum or `Parcelable`. A plain data class fails with an `IllegalArgumentException` saying the key type is not supported. Use the product's id instead.
- A Compose list keyed by id still loses a row's expanded state after the user scrolls far away and back. Why?The flag is held in `remember`, which is dropped when the row leaves composition. A lazy list saves each row's `rememberSaveable` state per item key when the row is disposed and restores it when the row returns. Hold the flag in `rememberSaveable`, or in the screen's state keyed by product id.
- When does contentType make no measurable difference in a Compose lazy list?When every item has the same structure, such as a list of identical product rows. All items then share the default `null` type and reuse is already between like items. It matters in mixed feeds, where banners, cards and dividers would otherwise be reused for one another.
Coats on numbered hooks: if staff hang coats by hook number and someone squeezes a new coat onto hook 1, every ticket now points at the wrong coat. Name tags (keys) let each coat be found wherever it moved.
- Keys only matter for animations, so a list without animations needs none
- The item's index makes a perfectly good key
- Any object can be a key, including a non-Parcelable data class
- contentType changes how items look or which composable renders them
- Duplicate keys are tolerated; Compose just picks one of the items
Assumes Compose 1.12 foundation; Modifier.animateItem() replaced the experimental animateItemPlacement() in Compose 1.7, and contentType has existed since 1.2.