2

How to create swipe to refresh in Jetpack compose using kotlin? Please Share proper reference link

SwipeRefresh is not available

 SwipeRefresh(
        state = rememberSwipeRefreshState(isRefreshing),
        onRefresh = {  },
    ) {
        LazyColumn {
           
        }
    }
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841

2 Answers2

3

Now you can use the built-in pullRefresh modifier.

Something like:

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

fun refresh() = refreshScope.launch {
    refreshing = true
    //...do something
    refreshing = false
}

val state = rememberPullRefreshState(refreshing, ::refresh)

Box(Modifier.pullRefresh(state)) {
    LazyColumn(Modifier.fillMaxSize()) {
        if (!refreshing) {
            items(itemCount) {
                //...
            }
        }
    }

    PullRefreshIndicator(refreshing, state, Modifier.align(Alignment.TopCenter))
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 1
    EDIT: If you're using material3, there is no built-in `pullRefresh` yet. We have to use the accompanist version. Is this correct? – Simon Mar 14 '23 at 14:19
  • @Simon that is deprecated – Gabriele Mariotti Mar 14 '23 at 18:13
  • 1
    I know, but when somebody is not using `material` and instead only uses `material3` there's no `pullRefresh` available – Simon Mar 15 '23 at 08:04
  • What is the solution for material3, it's stull confusing ! – Sathish Gadde Mar 15 '23 at 15:28
  • 1
    @SathishGadde You can check the official feature request [here](https://issuetracker.google.com/issues/261760718). The best option today is to adapt the current implementation copying the PullRefresh.kt PullRefreshIndicator.kt, PullRefreshIndicatorTransform.kt, PullRefreshState.kt files. – Gabriele Mariotti Mar 15 '23 at 17:43
1

To create a swipe-to-refresh layout, we need to add dependency in buld.gradle which will provide swipe to refresh layout just like SwipeRefreshLayout in traditional android.

  implementation 'com.google.accompanist:accompanist-swiperefresh:0.24.13-rc'

..

To create this kind of layout we require two APIs one SwipeRefresh for layout and another rememberSwipeRefreshState which will remember the state.

@Composable
fun SwipeRefreshCompose() {

    var refreshing by remember { mutableStateOf(false) }
    LaunchedEffect(refreshing) {
        if (refreshing) {
            delay(3000)
            refreshing = false
        }
    }

    SwipeRefresh(
        state = rememberSwipeRefreshState(isRefreshing = refreshing),
        onRefresh = { refreshing = true },
    ) {

       // list view

    }

}