Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-navigation

How to check current Jetpack Compose destination in a type-safe manner?


Since version 2.8.0 of the library androidx.navigation:navigation-compose we have a new type-safe navigation API available. I am trying to use it in my app but I have this problem.

My app has a NavigationBar which has multiple destinations:

NavigationBar {
        BottomBarDestination.entries.forEach {
            NavigationBarItem(
                selected = ?????,
                label = { Text(text = it.title) },
                onClick = {/*TODO change destination*/},
                icon = { Icon(imageVector = it.icon, contentDescription = it.title) }
            )
        }
    }

When I change the destination, I need to update the selected property of each navigation item. However, I haven't found any type-safe solution that works. How can I check the current destination if it matches the destination of the NavigationItem? I know I can store a simple String inside the NavigationItem and compare it to the route but I don't find that very type-safe. I want to leverage the type-safe API.


Solution

  • There's a hasRoute() extension method on NavDestination specifically for this case.

    val items = listOf(Profile, Dashboard())
    
    NavigationBar {
        val navBackStackEntry = navController.currentBackStackEntryAsState().value
        val currentDestination = navBackStackEntry?.destination
        items.forEach { destination ->
            NavigationBarItem(
                selected = currentDestination?.hierarchy?.any {
                    it.hasRoute(destination::class)
                } == true,
                // ...
            )
        }
    }