Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
   }
like image 489
Khashayar Avatar asked May 21 '21 17:05

Khashayar


1 Answers

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
    }
  }
like image 135
Mattia Ferigutti Avatar answered Oct 06 '22 22:10

Mattia Ferigutti