Jetpack Compose LazyColumnFor deprecated, how to use LazyColumn with listState and list of objects?
Asked Answered
O

2

9

As of Jetpack Compose 1.0.0-alpha09 LazyColumn, LazyColumnForIndexed, and row counterparts are deprecated. How is LazyColumn used, where, why, and how should i use rememberLazyListState?

If you can provide a full example with items, state and onClick listener it would much obliged.

Orianna answered 22/12, 2020 at 20:15 Comment(0)
S
13

This documentation here describes how to use LazyColumn instead of LazyColumnFor.

https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/package-summary#lazycolumn

Particular part of interest from the documentation:

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text

val itemsList = (0..5).toList()
val itemsIndexedList = listOf("A", "B", "C")

LazyColumn {
    items(itemsList) {
        Text("Item is $it")
    }

    item {
        Text("Single item")
    }

    itemsIndexed(itemsIndexedList) { index, item ->
        Text("Item at index $index is $item")
    }
}
Sidney answered 23/12, 2020 at 7:26 Comment(3)
Thanks. Would you mind showing how to use rememberLazyListState too? Is it for saving and restoring scroll position?Orianna
I guess it's like other remembers. You keep the scroll position inside Composable function, right?Orianna
You need to import import androidx.compose.foundation.lazy.itemsProphesy
F
3

With 1.0.0-beta06 the LazyColumn produces a vertically scrolling list.

Something like:

val itemsList = (0..30).toList()

LazyColumn {
    items(itemsList) {
        Text("Item is $it")
    }
}

The LazyListState is a state object that can be hoisted to control and observe scrolling. It is created via rememberLazyListState.

val listState = rememberLazyListState()

It can be used to react and listen to scroll position and item layout changes.

// Provide it to LazyColumn
LazyColumn(state = liststate) {
    // Check if the first visible item is past the first item
   if (listState.firstVisibleItemIndex > 0){
       //...
   }
}

or to control the scroll position :

// Remember a CoroutineScope to be able to launch
val coroutineScope = rememberCoroutineScope()

LazyColumn(state = listState) {
    // ...
}

lazyListState.animateScrollToItem(lazyListState.firstVisibleItemIndex)

Button (
    onClick = { 
        coroutineScope.launch {
            // Animate scroll to item with index=5
            listState.animateScrollToItem(index = 5)
        }
    }
){
    Text("Click")
}
Fail answered 19/3, 2021 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.