android-jetpack-composeandroid-jetpack

Jetpack Compose - Detect when LazyColumn's scroll position is at the first index


I want to have a Scroll back to top button for my LazyColumn. I successfully made the button work. But I want it to not be visible if I'm already at the top of the LazyColumn. How could I achieve this?


Solution

  • LazyColumn has state property, and if you pass your custom value instead of the default one, you can react on the state changes.

    To prevent redundant recompositions, in such cases derivedStateOf should be used: it'll trigger recomposition only when the produced result, based on other state variables, is changed:

    Box {
        val state = rememberLazyListState()
        LazyColumn(state = state) {
            // ...
        }
        val firstItemVisible by remember {
            derivedStateOf {
                state.firstVisibleItemIndex == 0
            }
        }
        if (!firstItemVisible) {
            Button(onClick = { /*TODO*/ }) {
    
            }
        }
    }