简体   繁体   中英

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 NavController to handle the navigation between the Composable

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM