Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Understanding Lazy Lists

When rendering a large data set with an unknown number of items, you’ll run into many performance issues if you use a regular Row/Column layout because it will compose all the items, whether they’re visible on the screen or not.

Exploring LazyListScope

Before working with the lazy composables, its important to understand how they differ from regular list composables.

@Composable  
fun LazyColumn(  
  modifier: Modifier = Modifier,  
  state: LazyListState = rememberLazyListState(),  
  contentPadding: PaddingValues = PaddingValues(0.dp),  
  reverseLayout: Boolean = false,  
  verticalArrangement: Arrangement.Vertical =  
    if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,  
  horizontalAlignment: Alignment.Horizontal = Alignment.Start,  
  flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),  
  userScrollEnabled: Boolean = true,  
  content: LazyListScope.() -> Unit  
)

@Composable  
fun LazyRow(  
  modifier: Modifier = Modifier,  
  state: LazyListState = rememberLazyListState(),  
  contentPadding: PaddingValues = PaddingValues(0.dp),  
  reverseLayout: Boolean = false,  
  horizontalArrangement: Arrangement.Horizontal =  
    if (!reverseLayout) Arrangement.Start else Arrangement.End,  
  verticalAlignment: Alignment.Vertical = Alignment.Top,  
  flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),  
  userScrollEnabled: Boolean = true,  
  content: LazyListScope.() -> Unit  
)
@LazyScopeMarker
interface LazyListScope {
  fun item(key: Any? = null, content: @Composable LazyItemScope.() -> Unit)

  fun items(
    count: Int,
    key: ((index: Int) -> Any)? = null,
    itemContent: @Composable LazyItemScope.(index: Int) -> Unit
  )

  @ExperimentalFoundationApi
  fun stickyHeader(
    key: Any? = null, 
    content: @Composable LazyItemScope.() -> Unit
  )
}

Using a LazyRow

The simplest way to use a LazyRow is as follows:

LazyRow {  
  item {  
    Text("first item")  
  }  

  item {  
    Text("second item")  
  }  
} 
LazyRow {  
    items(15) { index ->
      Text("Item: $index")  
    }    
  } 
LazyRow {
  items(pictures) { picture ->
    CarouselItem(picture)
  }  
}

Using a LazyColumn

You use LazyColumn much like you use LazyRow.

LazyColumn {

  item {
    Header()
  }       
  
  items(posts) { post ->
    PostItem(post)
  }
  
  item {
    Footer()
  }       
  
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo