简体   繁体   English

Jetpack Compose:如何保持 UI state 跨页面/可组合?

[英]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?有没有办法保存 Composable 的 UI state 以便在 Composable 之间切换时,它们的 UI state 与离开视图时相同?

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.我试过使用rememberLazyListState() (它使用rememberSaveable )来保存 LazyColumn 的滚动LazyColumn但回到可组合时它似乎不起作用。

Any ideas?有任何想法吗?

Edit: I am using NavController to handle the navigation between the Composable编辑:我正在使用NavController来处理 Composable 之间的导航

I just figured out how to do it.我只是想出了如何去做。 The idea is to hoist the LazyListState to the Composable managing the view navigation.这个想法是将LazyListState提升到管理视图导航的 Composable。

@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.在这里,我们将列表 state 提升到父组件。 When switching between the Home() and Favorites() composable the list scrolling state should remains identical.Home()Favorites()可组合之间切换时,列表滚动 state 应该保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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