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?
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?
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*/ }) {
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(intent)
setContent {
val scrollState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
Column(modifier = Modifier.fillMaxSize()) {
if (scrollState.firstVisibleItemIndex > 0) {
Button(onClick = {
coroutineScope.launch {
scrollState.scrollToItem(0)
}
}, enabled = scrollState.firstVisibleItemIndex > 0) {
Text("Scroll to top")
}
}
LazyColumn(modifier = Modifier.fillMaxSize(), state = scrollState) {
items(MutableList(100) { it }) { i ->
Text(i.toString())
}
}
}
}
}
}