Compose nestedScrollConnection not being triggered with animated scroll

1.5k Views Asked by At

I've created a collapsible header in Compose with the NestedScrollConnection. Everything works perfectly but one addition had to be made: automatic scrolling to a certain item. The problem I have is that the header (connected using the NestedScrollConnection) does not update when triggering an animateScrollTo.

Found a similar version from the Android developer docs here (this is from the experimental Material3 library, but it also happens without):

val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
    modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
    topBar = {
        MediumTopAppBar(
            title = { Text("Medium TopAppBar") },
            navigationIcon = {
                Icon(imageVector = Icons.Filled.Menu, contentDescription = "Localized description")
            },
            scrollBehavior = scrollBehavior
        )
    },
    content = { innerPadding ->
        val listState = rememberLazyListState()

        val coroutines = rememberCoroutineScope()
        LaunchedEffect(key1 = Unit, block = {
            coroutines.launch {
                delay(5000)
                // Starts the scrollTo
                listState.animateScrollToItem(50, 0)
            }
        })

        LazyColumn(
            state = listState,
            contentPadding = innerPadding,
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            val list = (0..75).map { it.toString() }
            items(count = list.size) {
                Text(
                    text = list[it],
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
)

Even though scrolling to an item works and the item is visible the header did not update at all.

When looking to the documentation of the LazyListState animateScrollToItem it does not say anything about skipping nested scroll connections (like dispatchRawDelta does). Even with the linked example above the scrollTo item does not update the header state. The problem also occurs with a normal scrollable Column, LazyGrid etc.

I did think of other ways of fixing it:

  • Getting the amount of pixels scrolled and dispatch it to the nestedScrollConnection but there is no reliable way of getting the scrolled pixels from a LazyColumn
  • Measuring all items and passing that but when items would invalidate this will fail

I get the feeling that a part of this connection is missing. Does anyone have any ideas?

0

There are 0 best solutions below