Compose Lists
Dynamic UIs
The amount of available data is often outside of your control. You might have no idea if your application would typically display a handful of items, or a huge number.
Ideally, we would only emit the nodes to the composition tree if they are visible. To do this, we need to track which items are visible and as the user scrolls, and properly update them if the data behind them changes.
When we emit nodes to the composition tree, Compose typically keeps track of them by position. During recomposition, if the item in a position is stable and equals the previous item in that position, recomposition for that item can be skipped. If items are inserted or deleted, Compose may need to recompose items around it, and may not be able to determine how to apply animations on those inserts and deletes.
If instead, you assign keys that uniquely identify items in part of the composition tree, Compose can determine how a newly-emitted chunk of nodes relates to the previously-emitted nodes, and can animate insertions and deletions and possibly moves.
LazyColumn(...) { // AAA
items( // BBB
items = people,
key = { it.id },
) { item -> // CCC
Card( // DDD
elevation = 4.dp,
modifier = ...
) { // EEE
// content to display the item
}
}
}
Line | Description |
---|---|
AAA | LazyColumn dynamically emits nodes to the composition tree that will be visible (and others if necessary for scrolling and animation). Its content lambda declares which items are in the list, how to uniquely identify them, and what composition should display each item |
BBB | items declares the list of data to display in the LazyColumn and how to get a unique key for each item. The keys allow LazyColumn to determine when items have been inserted, deleted or moved, optimizing recomposition and allowing animation |
CCC | The current item to be displayed is passed to this lambda. The LazyColumn determines which items will be visible (or partially visible) and use the lambda to render them. |
DDD | Card is a composable that displays a raised, rounded-corner rectangle around its contents. You'll often see them used in displayed lists, but they're not required. You can use any other composable inside this lambda torender the content. |
EEE | The content composable lambda that declares the presentation of each item in the Card |
The above screen might look like
Note
If you want a horizontal display of items, LazyRow
works similar. LazyHorizontalGrid
and LazyVerticalGrid
arrange more than one item horizontally or vertically in rows/columns. We're only working with LazyColumn
in this course.