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 will automatically scroll to the top, if there is one item, there is no problem
val pagingItems = viewModel.windList.collectAsLazyPagingItems()
LazyColumn(Modifier.fillMaxSize()) {
item {
...
}
items(pagingItems) { wind ->
if (wind != null) {
WindRow(navController, wind)
}
}
}
This way is fine
LazyColumn(Modifier.fillMaxSize()) {
items(pagingItems) { wind ->
if (wind != null) {
WindRow(navController, wind)
}
}
}
I inevitably use multiple items. How can I solve it?
CodePudding user response:
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.
CodePudding user response:
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.