Skip to content Skip to sidebar Skip to footer

Jetpack Compose Paging 3 Auto Scroll To The Top

I am using page 3, when displaying data, I found that if the page switches and returns to the bottom page, the data will automatically roll to the top. If there are two items, it w

Solution 1:

For some reason you have optional wind elements, and your current code will create some number of zero-height cells, which can lead to this behavior. I suggest that you make it non optional, if possible.

Likewise, depending on your design, you may want to display a placeholder, otherwise don't add empty elements like here:

items(pagingItems.filterNotNull()) { wind ->
    WindRow(navController, wind)
}

Or, if your null objects may become non null and you need to display updates, you can do following:

pagingItems.forEachIndexed { i, wind ->
    if (wind != null) {
        item(key = i) {
            WindRow(navController, wind)
        }
    }
}

If none of this helped, please update your code to minimal reproducible example.

Solution 2:

If I'm understanding correctly, every new page load causes you to scroll to top with a static item at the top of your LazyColumn.

My best guess at what is happening here without actually trying it out in a sample, is that on every new page load, paging-compose resubmits the list to LazyColumn. Since there is a static item that is always there though, Compose will keep that item in view, and because that static item is at the top it has the effect of scrolling to top.

For a workaround, you could just use Paging's built-in support for headers

ViewModel.kt

val windList = Pager(..) { ..}
  .map { pagingData ->
    pagingData.insertHeaderItem(..)
  }
  .cachedIn(viewModelScope)
  .collectAsLazyPagingItems()

Also, I would recommend to implement the key mapping in items, as it will help you provide stable ids to Compose's LazyColumn, allowing it to understand how to resume scroll position on refresh or config change.

Post a Comment for "Jetpack Compose Paging 3 Auto Scroll To The Top"