Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is something similar like swiperefreshlayout to pull to refresh in the LazyColumn jetpack compose

There is something similar like swiperefreshlayout to pull to refresh in the jetpack compose

like image 380
Rafael Souza Avatar asked Sep 10 '25 15:09

Rafael Souza


2 Answers

Edit: Google Accompanist's swipe refresh is deprecated with official pull refresh support in androidx.compose.material.pullrefresh

Sample usage:

val viewModel: MyViewModel = viewModel()
val refreshing by viewModel.isRefreshing

val pullRefreshState = rememberPullRefreshState(refreshing, { viewModel.refresh() })

Box(Modifier.pullRefresh(pullRefreshState)) {
    LazyColumn(Modifier.fillMaxSize()) {
        ...
    }

    PullRefreshIndicator(refreshing, pullRefreshState, Modifier.align(Alignment.TopCenter))
}

Original Answer:

You can use Google's Accompanist library for implementing swipe-to-refresh.

Sample usage:

val viewModel: MyViewModel = viewModel()
val isRefreshing by viewModel.isRefreshing.collectAsState()

SwipeRefresh(
    state = rememberSwipeRefreshState(isRefreshing),
    onRefresh = { viewModel.refresh() },
) {
    LazyColumn {
        items(30) { index ->
            // TODO: list items
        }
    }
}

Documentation: https://google.github.io/accompanist/swiperefresh/

like image 187
Saurabh Thorat Avatar answered Sep 12 '25 06:09

Saurabh Thorat


Starting with M2 1.3.0-beta03 there is a new built-in Pull-To-Refresh component, with the pullRefresh modifier.

You can use something like:

val refreshScope = rememberCoroutineScope()
var refreshing by remember { mutableStateOf(false) }
var itemCount by remember { mutableStateOf(15) }

fun refresh() = refreshScope.launch {
    refreshing = true
    delay(1500)
    itemCount += 5
    refreshing = false
}

val state = rememberPullRefreshState(refreshing, ::refresh)

//pullRefresh modifier
Box(Modifier.pullRefresh(state)) {

    //vertically scrollable content
    LazyColumn(Modifier.fillMaxSize()) {
        if (!refreshing) {
            items(itemCount) {
                ListItem { Text(text = "Item ${itemCount - it}") }
            }
        }
    }

    //standard Pull-Refresh indicator. You can also use a custom indicator 
    PullRefreshIndicator(refreshing, state, Modifier.align(Alignment.TopCenter))
}

enter image description here

Note: currently, the content of the Composable with the pullRefresh modifier needs to be 'vertically scrollable' to be able to react to swipe gestures. Layouts such as LazyColumn are automatically vertically scrollable, in the other cases you can provide a verticalScroll modifier to that content.

Something like:

//pullRefresh modifier
Box( Modifier.pullRefresh(state) ) {

    //vertically scrollable content
    Column(Modifier.verticalScroll(rememberScrollState())) {
        // content
    }

    //PullRefreshIndicator
}
like image 36
Gabriele Mariotti Avatar answered Sep 12 '25 06:09

Gabriele Mariotti