How can I start a LazyList by showing the last element in Jetpack Compose?

44 Views Asked by At

Background

  • I'm creating a chat application and I want the latest messages to be shown to the user when they launch the screen.
  • I'm also using sticky headers to show the dates, which I group by in my viewmodel.

Attempts

  • Setting reverseLayout = true in my LazyColumn was amazing but I had the stickyHeaders showing up as "stickyFooters" instead, which is not ideal
  • Setting scrollToItem works exactly as it should, BUT it's firstly showing the first items and then going to the last one, which causes an annoying flicker every time the user opens the screen.
scrollState.scrollToItem(
    scrollState.layoutInfo.totalItemsCount,
)

Some Code

LazyColumn(
        modifier = modifier,
//        reverseLayout = true,
        state = scrollState,
    ) {
        items.forEach { sectionedListItem ->
            stickyHeader {
                Text(
                    modifier = Modifier
                        .background(color = MaterialTheme.colorScheme.background)
                        .padding(vertical = if (sectionedListItem.sectionTitle == "") 0.dp else 8.dp)
                        .fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    text = sectionedListItem.sectionTitle
                )
            }
            items(
                count = sectionedListItem.items.size,
                key = { sectionedListItem.items[it].id },
                itemContent = {
                    val message = remember { sectionedListItem.items[it] }
                    TSDMessage(Modifier, message, userId == message.authorId, maxWidth)
                }
            )
        }
    }

Question

How can I start by showing the last elements in Jetpack Compose, without having the stickyHeaders showing under or by having the annoying flickering delay of scrollToItem?

More code and/or screenshots can be provided if necessary.

1

There are 1 best solutions below

0
Code Poet On

You can take your list and order it first. For instance, something like:

val orderedList = sectionedListItem.sortedByDescending {it.items}

and then pass your orderedList into your LazyColumn.

PS: It is recommended to perform the sorting in your viewModel.