How to implement PullToRefresh in Jetpack Compose
Last updated:2024-07-10
To implement PullToRefresh with Jetpack Compose, follow these four steps:
- Create state
- Set up nestedScroll
- Put PullToRefreshContainer
- Write the code to be executed when refreshing
Create state
Use rememberPullToRefreshState()
.
val pullToRefreshState = rememberPullToRefreshState()
Set up nestedScroll
Set nestedScroll to Scaffold.
Scaffold(
modifier = Modifier.nestedScroll(pullToRefreshState.nestedScrollConnection),
) { innerPadding -> }
Put PullToRefreshContainer
Put a composable that indicates loading. Use Box
+ LazyColumn
.
Box(modifier = Modifier.padding(innerPadding)) {
LazyColumn(modifier = Modifier.fillMaxSize()) { ... }
PullToRefreshContainer(
state = pullToRefreshState,
modifier = Modifier.align(Alignment.TopCenter),
)
}
Write the code to be executed when refreshing
Check isRefreshing
and execute refresh process in LaunchedEffect
.
if (pullToRefreshState.isRefreshing) {
LaunchedEffect(Unit) {
viewModel.refresh()
}
}
Summary
@Composable
fun MainScreen(viewModel: MainViewModel) {
val pullToRefreshState = rememberPullToRefreshState()
Scaffold(
modifier = Modifier.nestedScroll(pullToRefreshState.nestedScrollConnection),
) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
LazyColumn(modifier = Modifier.fillMaxSize()) { ... }
PullToRefreshContainer(
state = pullToRefreshState,
modifier = Modifier.align(Alignment.TopCenter),
)
}
}
if (pullToRefreshState.isRefreshing) {
LaunchedEffect(Unit) {
viewModel.refresh()
}
}
}