我有一个包含多个视图元素的组合列。我想检测用户何时垂直滚动该列并到达其末尾。我们该如何做到这一点?
我有一个包含多个视图元素的组合列。我想检测用户何时垂直滚动该列并到达其末尾。我们该如何做到这一点?
derivedStateOf
}}:只有当基于其他状态变量(如scrollState
)产生的结果发生变化时,它才会触发重新组合:val scrollState = rememberScrollState()
val endReached by remember {
derivedStateOf {
scrollState.value == scrollState.maxValue
}
}
如果你需要在改变变量时执行一些副作用,比如请求更多数据,你可以根据副作用文档中的不同方法在Compose中实现。例如,使用LaunchedEffect
:
if (endReached) {
LaunchedEffect(Unit) {
// react on scroll end
}
}
val scrollState = rememberScrollState()
Log.i("ScrollValue", "current: ${scrollState.value}, max: ${scrollState.maxValue}")
if (scrollState.value == scrollState.maxValue) {
// End
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState)
) {...}
@Composable
fun LazyListState.OnBottomReached(
loadMore : () -> Unit
){
val shouldLoadMore = remember {
derivedStateOf {
val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
?: return@derivedStateOf true
lastVisibleItem.index == layoutInfo.totalItemsCount - 1
}
}
// Convert the state into a cold flow and collect
LaunchedEffect(shouldLoadMore){
snapshotFlow { shouldLoadMore.value }
.collect {
// if should load more, then invoke loadMore
if (it) loadMore()
}
}
}