Search code examples
androidkotlinnavigationandroid-jetpack-compose

Why bottom navigation state not saving on compose?


I use one graph in which the Login screen is set as the start screen. From the Login screen, you can navigate to a specific tab bottom navigation. If you clear the stack with popUpTo(0) when going from the login screen to the screen from the bottom navigation, then the bottom navigation stops saving state when switching between tabs.

navigate between tabs:

navController.navigate(item.route) {
    navController.graph.startDestinationRoute?.let { route ->
        popUpTo(route) {
            saveState = true
        }
    }
    launchSingleTop = true
    restoreState = true
}

navigate from login to bottom tab

navController.navigate(route = NavigationItem.Home.route, builder = { popUpTo(0) })

Solution

  • Because there is no stack left to save.

    navController.navigate(screen.route) {
                  // Pop up to the start destination of the graph to
                  // avoid building up a large stack of destinations
                  // on the back stack as users select items
                  popUpTo(navController.graph.findStartDestination().id) {
                    saveState = true
                  }
                  // Avoid multiple copies of the same destination when
                  // reselecting the same item
                  launchSingleTop = true
                  // Restore state when reselecting a previously selected item
                  restoreState = true
                }