How to retrieve the scrolling direction for LazyRow

Viewed 1523

For a LazyRow, or Column, how to I know whether the user has scrolled left or right ( or up or... you know). We do not need callbacks in compose for stuff like that, since mutableStateOf objects always anyway trigger recompositions so I just wish to know a way to store it in a variable. Okay so there's lazyRowState.firstVisibleItemScrollOffset, which can be used to mesaure it in a way, but I can't find a way to store its value first, and then subtract the current value to retrieve the direction (based on positive or negative change). Any ideas on how to do that, thanks

2 Answers

Currently (1.0.x) there is no built-in function to get this info from LazyListState.

You can use something like:

@Composable
private fun LazyListState.isScrollingUp(): Boolean {
    var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }
    var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) }
    return remember(this) {
        derivedStateOf {
            if (previousIndex != firstVisibleItemIndex) {
                previousIndex > firstVisibleItemIndex
            } else {
                previousScrollOffset >= firstVisibleItemScrollOffset
            }.also {
                previousIndex = firstVisibleItemIndex
                previousScrollOffset = firstVisibleItemScrollOffset
            }
        }
    }.value
}

Then just use listState.isScrollingUp() to get the info about the scroll.

This snippet is used in a google codelab.

Got it

{ //Composable Scope
val lazyRowState = rememberLazyListState()
    val pOffset = remember { lazyRowState.firstVisibleItemScrollOffset }
    val direc = lazyRowState.firstVisibleItemScrollOffset - pOffset
    val scrollingRight /*or Down*/ = direc > 0 // Tad'aa
}
Related