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
}