Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 819
MaxUt Avatar asked Oct 11 '25 22:10

MaxUt


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.

like image 116
MaxUt Avatar answered Oct 14 '25 12:10

MaxUt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!