Is there a way to support iOS-like scroll-to-top in Kotlin Multiplatform Compose?
On iOS, every scrollable view supports scroll-to-top out of box so users are accustomed to it, but is there a way to support that in KMP Compose?
Scroll-to-top is ability of scrollable views to scroll to top when user taps on top of the device. If there are multiple scrollable views (think iPad), then the one above which is tapped will be scrolled to top.
Flutter, for example, does support that.
There is no such functionality out of the box, but you can easily build it yourself to work with LazyColumn
like this:
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScrollToTopScaffold() {
val coroutineScope = rememberCoroutineScope()
val scrollState = rememberLazyListState()
Scaffold(
topBar = {
CenterAlignedTopAppBar(
modifier = Modifier.clickable {
coroutineScope.launch {
scrollState.animateScrollToItem(0)
} },
title = { Text(text = "Application") }
)
}
) {
LazyColumn(
modifier = Modifier
.padding(it)
.fillMaxSize(),
state = scrollState
) {
items(100) { index ->
Text(
modifier = Modifier.fillMaxWidth(),
fontSize = 24.sp,
text = "Item #$index"
)
}
}
}
}
Output: