I've a details screen where i want to scroll item ...
# compose
r
I've a details screen where i want to scroll item to specified index in LazyColumn. Below code (in thread) works, but it recomposes multiple times because i can't use LaunchedEffect() in
index?.let {}
block. What are the alternatives?
Copy code
@Composable
fun DetailScreen(
    indexToScroll: Int? = null
) {
    val coroutineScope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    LazyColumn(
        state = listState
    ) {
        // LazyColumn Content

        indexToScroll?.let { index ->
            // Can't use LaunchedEffect here
            Log.d(TAG, "scrolling to $index")
            coroutineScope.launch {
                listState.scrollToItem(index = index)
            }
        }
    }
}
o
You have your list state hoisted to the
DetailScreen
composable, so I believe you could have your
LaunchedEffect
there. Right before
LazyColumn
composable usage:
Copy code
fun DetailScreen(...) {
    val listState = ...
    LaunchedEffect(indexToScroll) { ... }
    LazyColumn { ... }
}
r
It's not working. list is not getting scrolled to index
Copy code
val listState = rememberLazyListState()

LaunchedEffect(key1 = indexToScroll) {
    indexToScroll?.let { index ->
        Log.d(TAG, "scrolling to $index")
        coroutineScope.launch {
            listState.scrollToItem(index = index)
        }
    }
}
LazyColumn() { ... }
🤔 1
c
You don't need both LaunchedEffect and .launch
o
True, you can directly call suspend function in the LaunchedEffect. But it will not fix scrolling, because when effect is launched there are no items in the column. I guess you could try to add items to the key of the LaunchedEffect to re-trigger when the lazy column is filled with data. But in this case it will scroll again, when some item is added / removed 😞
c
Shouldn't it work OK if the LaunchedEffect is after the LazyColumn? I've got some similar code doing that successfully
🤷 1
I'm doing something like this:
Copy code
fun ItemList(model: MyViewModel) {
  val selectedIndex by remember { model.selectedItem }
  val state = rememberLazyListState(selectedIndex)
  LazyColumn(state = state) { ... }
  LaunchedEffect(selectedIndex) {
    if (!state.isVisible(selectedIndex)) {
      state.animateScrollToItem(selectedIndex)
    }
  }
}
r
i also tried using
LaunchedEffect
below
LazyColumn
but that didn't worked , too
Copy code
val listState = rememberLazyListState()
LazyColumn() { ... }
LaunchedEffect(key1 = indexToScroll) {
    indexToScroll?.let { index ->
        Log.d(TAG, "scrolling to $index")
        coroutineScope.launch {
            listState.scrollToItem(index = index)
        }
    }
}