Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 292
Thracian Avatar asked Dec 22 '20 20:12

Thracian


2 Answers

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")
    }
}
like image 52
riggaroo Avatar answered Oct 19 '22 09:10

riggaroo


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")
}
like image 24
Gabriele Mariotti Avatar answered Oct 19 '22 10:10

Gabriele Mariotti