How to update navigation bar selected item when I press back?

Viewed 111

The navigation item only updates when I press it manually in the navigation bar when I press back it navigates back but the highlighted item remains the same

// navigation bar composable
@Composable
fun BottomBar(navController: NavController) {
    // current destination and bottombar navigation items
    var curDestination by remember { mutableStateOf( 0 )}
    val items = listOf(
        BottomBarItem.Home,
        BottomBarItem.History
    )

    // navigation bar
    NavigationBar {
        items.forEachIndexed { index, item ->
            NavigationBarItem(
                selected = curDestination == index,
                onClick = {
                    curDestination = index
                    navController.navigate(item.route)
                          },
                label = { Text(text = item.label) },
                icon = {
                    Icon(
                        painter = painterResource(
                            id = if (curDestination == index) item.iconSelected else item.icon),
                        contentDescription = item.label
                    )
                }
            )
        }
    }
}
1 Answers

You can register an OnDestinationChangedListener on your navController to receive callbacks whenever the current destination changes. You can then update your curDestination to the correct index by checking if the destination matches one of your bottom nav items.

Related