Jetpack Compose : How to keep UI state across pages/composable?

Viewed 1454

Is there a way to save the UI state of a Composable so that when switching between Composable their UI state is identical to when the view was left ?

I've tried using rememberLazyListState() (which uses rememberSaveable) to save the scroll state of a LazyColumn but it doesn't seems to work when coming back to the Composable.

Any ideas ?

Edit : I am using NavControllerto handle the navigation between the Composable

1 Answers

I just figured out how to do it. The idea is to hoist the LazyListState to the Composable managing the view navigation.

@Composable
fun AppScreenNav(screen: Screen) {
    val listState = rememberLazyListState()
    when (screen) {
        Screen.Home -> Home()
        Screen.Favorites -> Favorites(listState)
    }
}

@Composable
fun Favorites(listState: LazyListState) {
    val favorites: List<String> by rememberSaveable { mutableStateOf(List(1000) { "Favorites $it" }) }
    LazyColumn(
        state = listState
    ) {
        items(favorites) { item ->
            Text(
                color = Color.Black,
                text = item,
            )
        }
    }
}

Here we are hoisting the list state to the parent component. When switching between the Home() and Favorites() composable the list scrolling state should remains identical.

Related