2.5 Lazy Lists
Lazy lists are used to display a large number of items in a list. Using a Column or Row can cause performance issues since all of the items will be composed whether they are visible or not. LazyList can be compared to a RecyclerView in Android Native, but it eliminates the need for an Adapter.
LazyRow and LazyColumn are components provided by Jetpack Compose that display only the visible items in a designated orientation. As the name suggests, LazyRow creates a horizontal scrolling list, and LazyColumn creates a vertically scrolling list.
Unlike most layouts in Jetpack Compose, Lazy components do not accept a @Composable
block as a parameters. Instead, Lazy components provide a LazyListScope()
block, which offers a domain-specific language (DSL) that allows the app to describe the item contents. LazyRow and LazyColumn are then responsible for adding each item's contents to the list.
LazyListScope DSL
LazyListScope provides many functions that describe the items in the layout.
Most commonly, item()
is used to add a single item, and items(int)
are used to add a certain number of items.
There are also extension functions like List
that can add a collection of items and itemsIndexed()
where the content of an item is aware of its index. These functions are not as commonly seen, so they won't be covered in depth.
Padding
To make the list more visually appealing, padding can be added to the edges of the content. Lazy lists allows you to pass in PaddingValues
to the contentPadding
parameter.
Spacing
Spacing can also be added in between items in the lazy component by using Arrangement.spacedBy()
. LazyColumn sets the parameter verticalArrangement
while LazyRow sets the parameter horizontalArrangement
.
Tips for Lazy Lists
Avoid nesting components that scroll in the same direction
Nesting scrollable children without a predefined height inside a parent that scrolls in the same direction will throw an
IllegalStateException.
Instead, wrap everything into a Lazy list and use the DSL to pass in different types of content.Avoid putting multiple elements in an
item()
The elements will be unable to be composed seperately, which can lead to complexities if you only want one specific element to show. It can also interfere with other functions like
scrollToItem()
.
Last updated