简体   繁体   中英

Remember scroll position in lazycolumn?

I am aware of the remember lazy list state and it works fine

 setContent {       
       Test(myList) // Call Test with a dummy list
    }

  @Composable
    fun Test(data: List<Int>){
        val state = rememberLazyListState()

        LazyColumn(state = state) {
            items(data){ item ->Text("$item")}
          }
     }

It will remember scroll position and after every rotation and change configuration it will be the same
But whenever I try to catch data from database and use some method like collectAsState
it doesn't work and it seem an issue

   setContent{
      val myList by viewModel.getList.collectAsState(initial = listOf())
      Test(myList)
   }

Unfortunately for now there's not a native way to do so, but you can use this code:

val listState = rememberLazyListState()

listState has 3 methods:

  • firstVisibleItemIndex
  • firstVisibleItemScrollOffset
  • isScrollInProgress

All of them are State() so you will always get the data as it updates. For example, if you start scrolling the list, isScrollInProgress will change from false to true .

SAVE AND RESTORE STATE

val listState: LazyListState = rememberLazyListState(viewModel.index, viewModel.offset)

  LaunchedEffect(key1 = listState.isScrollInProgress) {
    if (!listState.isScrollInProgress) {
      viewModel.index = listState.firstVisibleItemIndex
      viewModel.offset = listState.firstVisibleItemScrollOffset
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM