Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 104 ยท Jetpack Compose Fundamentals

Lazy Lists and Grids

Learn LazyColumn, LazyRow and LazyVerticalGrid: items and keys, contentPadding, sticky headers, scroll state, and how lazy layouts compose only visible items.

A Column composes and measures all of its children, even those far off screen. That is fine for a form with ten fields, and a disaster for a feed with ten thousand rows. Compose's answer is the lazy layouts: LazyColumn, LazyRow, LazyVerticalGrid and friends. They only compose and measure the items that are visible (plus a small buffer), so a list of a million entries costs about the same as a list of twenty.

This lesson shows how to build lists and grids, why key matters, how to add padding, headers and scroll control, and how a lazy layout decides what to compose. The real Compose code needs Android and is read-only. The runnable TryIt blocks are plain Kotlin stand-ins that compute which items fall inside a viewport and show why keys keep per-item state attached to the right row. They model the idea; the actual implementation also handles item heights that differ, prefetching and reuse of internal structures.

LazyColumn and items

Instead of calling composables directly, you describe your content in a LazyListScope block. item adds one element and items adds many:

Kotlin
// read-only example: needs Android and Compose
LazyColumn(
    modifier = Modifier.fillMaxSize(),
    contentPadding = PaddingValues(16.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp),
) {
    item {
        Text("Contacts", style = MaterialTheme.typography.headlineSmall)
    }
    items(contacts, key = { it.id }) { contact ->
        ContactRow(contact)
    }
    item {
        Text("${contacts.size} contacts")
    }
}

Two things differ from a Column. The lambda is not composable: it builds a description of the list, and only the inner item lambdas ({ contact -> ContactRow(contact) }) are composable and run on demand. And you must not use forEach inside it: contacts.forEach { ContactRow(it) } would not compile as intended, because those calls are not in a composable context. Use items(...).

Variants:

  • items(list), items(count) { index -> } and itemsIndexed(list) { index, item -> }.
  • LazyRow is the horizontal version, with horizontalArrangement and verticalAlignment.
  • LazyVerticalGrid, LazyHorizontalGrid and the staggered grids for uneven item sizes.

A lazy list needs bounded size in its scrolling direction. Putting a LazyColumn inside a verticalScroll column is an error: it would get infinite height, so nothing could be lazy. Give it a height, weight(1f), or let it fill the screen, and put any surrounding content into the list as items.

Keys: stable identity for rows

By default, Compose identifies an item by its position. If a new contact is inserted at the top, every item below shifts position, and the state that composables remembered for position 2 now sits on a different contact. With a key, identity follows the data:

Kotlin
// read-only example: needs Android and Compose
items(notes, key = { note -> note.id }) { note ->
    NoteRow(note)   // remember { ... } inside is now tied to note.id, not to the index
}

Keys must be unique within the list and stable (the same item always gives the same key). A database id is ideal. Using the item's position or a random value defeats the purpose, and duplicate keys crash the list. Keys also let Compose animate moves (Modifier.animateItem()), keep the scroll position anchored on the item the user was looking at when data is inserted above, and keep rememberSaveable state correct (see rememberSaveable, derivedStateOf and Collections). The key type must be something that can be saved in a Bundle, such as a number, string or Parcelable.

The stand-in below shows the failure and the fix. The row for "Linus" is expanded. State is stored in a map either by position or by key. After "Ada" is removed from the front of the list, the position-based map points at the wrong person.

Kotlin Why keys keep state on the right row (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the deletion, the position-based version shows Grace expanded: the state stayed at index 1, but index 1 now holds a different row. The keyed version still shows Linus.

Spacing, padding and arrangement

  • contentPadding = PaddingValues(16.dp) adds padding inside the scrolling area: items scroll under it and are clipped at the true edge of the list. This is different from Modifier.padding(16.dp) on the list, which would shrink the viewport and cut items off before the screen edge. Use contentPadding for the bottom inset of a list under a navigation bar or floating button, and for side margins.
  • verticalArrangement = Arrangement.spacedBy(8.dp) puts gaps between items only.
  • reverseLayout = true starts at the bottom, which suits chats.
  • userScrollEnabled = false disables touch scrolling while keeping programmatic scroll.

Sticky headers and grouped data

For grouped lists, such as contacts by first letter, use stickyHeader. It pins the current group's header at the top while its items scroll beneath it:

Kotlin
// read-only example: needs Android and Compose
LazyColumn {
    grouped.forEach { (initial, people) ->
        stickyHeader(key = initial) {
            Text(initial.toString(), Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface))
        }
        items(people, key = { it.id }) { person -> PersonRow(person) }
    }
}

Depending on your Compose version, stickyHeader may require an opt-in annotation (@OptIn(ExperimentalFoundationApi::class)); the compiler tells you. The header needs a background, otherwise the scrolling items show through it. Here forEach is fine, because it runs in the description lambda to add items, not inside an item. A key per header keeps keys unique across the list: header keys and item keys share one key space, so an id can collide with a letter's key only if their types and values match.

Grids

LazyVerticalGrid takes a columns rule:

Kotlin
// read-only example: needs Android and Compose
LazyVerticalGrid(
    columns = GridCells.Adaptive(minSize = 128.dp),   // as many columns as fit
    contentPadding = PaddingValues(12.dp),
    horizontalArrangement = Arrangement.spacedBy(12.dp),
    verticalArrangement = Arrangement.spacedBy(12.dp),
) {
    item(span = { GridItemSpan(maxLineSpan) }) {
        Text("Photos", style = MaterialTheme.typography.titleLarge)   // full-width header
    }
    items(photos, key = { it.id }) { photo -> PhotoCard(photo) }
}

GridCells.Fixed(2) always uses two columns, while Adaptive(minSize) fits as many columns of at least that width as possible, so a phone shows two and a tablet shows five without extra code. GridItemSpan(maxLineSpan) makes an item as wide as the whole row. For images of different heights (a masonry look), LazyVerticalStaggeredGrid with StaggeredGridCells is the tool. Layouts that react to window size are covered in Adaptive Layouts and Window Size Classes.

Scroll state

Every lazy layout has a state object you can create and read:

Kotlin
// read-only example: needs Android and Compose
val listState = rememberLazyListState()
val scope = rememberCoroutineScope()

LazyColumn(state = listState) { /* items */ }

// Reading: where are we?
val atTop = listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset == 0

// Acting: scroll to the top
Button(onClick = { scope.launch { listState.animateScrollToItem(0) } }) { Text("Top") }

firstVisibleItemIndex and firstVisibleItemScrollOffset tell you the position; layoutInfo.visibleItemsInfo lists what is visible; scrollToItem and animateScrollToItem are suspend functions, so they run in a coroutine (Coroutines on Android). Reading listState values in composition causes recomposition on every scroll frame. For derived conditions such as "show the scroll-to-top button", use derivedStateOf, which is explained in rememberSaveable, derivedStateOf and Collections.

Which items are composed?

A lazy layout asks "which items overlap the viewport at the current scroll offset?" and composes just those. As you scroll, items that leave the viewport are disposed or reused and new ones are composed. The stand-in below does the same arithmetic for rows of equal height: from the scroll offset it computes firstVisibleItemIndex, firstVisibleItemScrollOffset and the range of items intersecting the viewport. The beyond argument models the buffer of extra items that lazy layouts prepare ahead of the scroll.

Kotlin Which items fall in the viewport (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Whatever the scroll offset, only eight items are composed out of ten thousand. That is why lazy lists scale, and also why you must not rely on every item existing: an item that is off screen has no composable instance, no remember state (unless it is saved by key) and no side effects running.

flowchart LR
    S["Scroll offset<br/>and viewport height"] --> R["Find items<br/>that intersect the viewport"]
    R --> C["Compose and measure<br/>only those items"]
    C --> D["Items that scroll away<br/>are disposed or reused"]

A lazy layout recomputes the visible range as you scroll and composes just that range.

Common mistakes

  • Nesting scrollables in the same direction. A LazyColumn inside a verticalScroll parent crashes at runtime with an infinite-height error. Put header and footer content in the list as items.
  • No keys with a changing list. Reordering or inserting causes lost state and wasteful recomposition.
  • Heavy work in item bodies. Items are composed while scrolling; parse, sort and format data before it reaches the list.
  • Unstable item parameters. Passing a new lambda or a mutable list into every row can force every visible row to recompose; Recomposition and Stability explains how to avoid that.
  • A Column for long data. If the length is unbounded, use a lazy layout. For truly huge sets loaded from a database or the network, combine it with paging (Paging 3 for Large Lists).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of LazyColumn over Column for long lists?

    A lazy layout composes only the items intersecting the viewport (plus a small buffer), so cost depends on what is visible rather than on the list length.
  2. 2. Why should you provide a key in items(list, key = { it.id })?

    Without a key an item is identified by position, so inserts or deletions move remembered state onto the wrong item. A stable, unique key ties state to the data.
  3. 3. What is the difference between contentPadding and Modifier.padding on a LazyColumn?

    Modifier.padding shrinks the viewport, clipping items before the screen edge. contentPadding keeps the full viewport and adds space around the content.
  4. 4. What goes wrong when you put a LazyColumn inside a verticalScroll Column?

    A scrolling parent offers unbounded height, so the lazy list cannot know how many items to compose. Put header and footer content in the list as items instead.
  5. 5. Which grid rule shows two columns on a phone and more on a tablet automatically?

    Adaptive fits as many columns of at least minSize as the width allows, so the count grows with the screen.

Summary

  • Lazy layouts (LazyColumn, LazyRow, LazyVerticalGrid) compose and measure only visible items, so they scale to huge lists.
  • Describe content with item, items and itemsIndexed inside the scope block; use items, not forEach, to emit rows.
  • Give items a unique, stable key (such as a database id) so state and scroll position follow the data.
  • Use contentPadding for padding inside the scroll area, Arrangement.spacedBy for gaps and stickyHeader for pinned group headers.
  • Grids use GridCells.Fixed or Adaptive; GridItemSpan(maxLineSpan) makes full-width items.
  • rememberLazyListState exposes the scroll position and suspend scroll functions; derive conditions with derivedStateOf.
  • Do not nest same-direction scrollables, and do not assume off-screen items exist.
  • The Compose code is read-only; the TryIt blocks are stand-ins for keys and viewport math.

Next: State and remember