0

How do I know a LazyColumn can be navigated?

For example, a list contains 100 elements, then it is a lazy column that can be scroll and we show a fab button to scroll up, but when this list contains 5 elements, the lazy column is not scrollable and the FabButton is no longer needed.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ghasem
  • 467
  • 5
  • 8

1 Answers1

0

The lazy list layout information can be obtained from state, which is passed to LazyColumn.

In my example, I use derivedStateOf to prevent redundant recompositions - this will cause a recomposition only when the value actually changes. Reading LazyColumn state information without derivedStateOf or side effect function can cause significant performance problems.

The most basic logic in such cases is to check if the first element has been scrolled:

val canScrollToTop by remember {
    derivedStateOf {
        state.layoutInfo.visibleItemsInfo.run {
            isNotEmpty() && (first().index > 0 || first().offset < 0)
        }
    }
}
LazyColumn(state = state) {
   // ...
}
if (canScrollToTop) {
    // your button
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220