Jetpack Compose: Bottom bar and Nested Navigation
B

1

6

I have setup a Bottom Bar in project on Jetpack Compose app with 2 destinations. I have tried to follow the samples from Google.

So for example it looks something like this:

@Composable
fun ExampleBottomBar(navController: NavHostController) {
val items = listOf(
    BottomNavigationGraph.Graph1,
    BottomNavigationGraph.Graph2
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination

BottomNavigation {
    items.forEach { screen ->
        BottomNavigationItem(
            onClick = {
                navController.navigate(screen.route) {
                    popUpTo(navController.graph.findStartDestination().id) {
                        saveState = true
                    }

                    launchSingleTop = true
                    restoreState = true

                }
            },
            selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
            icon = { Icon(imageVector = screen.icon, contentDescription = null) },
            label = { Text(stringResource(screen.label)) }
        )
      }
     }
    }

This all works fine and I'm able to navigate between the two destinations. However, When I navigate from Graph-1 Screen-2 to Graph-2 Screen-2, It navigates without any issue. But when I press Bottom Tab on Graph-1, it doesn't work. The Bottom Tab seems to be not clickable anymore. So I tried this solution to navigate to nested screen (different graph):

navigate(route) {
    launchSingleTop = true
    restoreState = false
    popUpTo(graph.findStartDestination().id) {
        saveState = true
    }
}

Now this solution works perfectly. Now when I click on Bottom Tab for Graph-1 it switches and retain state for Graph-1 Screen-2, But when I press back button from Graph-2 Screen-2, it navigates me directly to Graph-1 Screen-1 which creates basically another stack for Graph-1 Screen-1. So basically what I want is to retain state for Graph-1 Screen-2 on back press or BottomTab click.

Am I doing something wrong or is this a bug? Can someone help me out here ? Thanks in advance.

Berardo answered 27/6, 2022 at 7:53 Comment(2)
Have you found any solution?Rightly
@AlvinDizon I didn't maintained the previous entries for bottom tab (when user press the back button from any tab). so here is hack - When pressing back button from any tab, you need to manually perform the top level navigation. By doing so, it will retain state for last nested screen for first tab.Berardo
S
0

In my case, setting saveState and restoreState from NavOptionsBuilder as false helped to resolve the issue.

Stairwell answered 21/2 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.