How to pass argumens between BottomNavigationItem in Compose Navigation?

49 Views Asked by At

I have a problem. Could you please help me? I have a Jetpack Compose botton navigation where I need to pass arguments between screens. How do I do it with if I use BottomNavigationItem?

BottomNavigation(
    backgroundColor = colorResource(id = R.color.grey),
    contentColor = Color.Black
) {
    items.forEach { item ->
        BottomNavigationItem(
            icon = { Icon(painterResource(id = item.icon), contentDescription = item.route) },
            selectedContentColor = colorResource(id = R.color.yellow),
            unselectedContentColor = colorResource(id = R.color.white),
            alwaysShowLabel = true,
            selected = currentRoute == item.route,
            onClick = {
                navController.navigate(item.route) {
                    navController.graph.startDestinationRoute?.let { screen_route ->
                        popUpTo(screen_route) {
                            saveState = true
                        }
                    }
                    launchSingleTop = true
                    restoreState = true
                }
            }
        )
    }
}

enter image description here

1

There are 1 best solutions below

0
iamnaran On

You have various options for exchanging data between different screens. One common approach is to utilize a SharedViewModel shared among multiple screens.

Passing the view model directly to the composable, which is not recommended.

@Composable
fun MyNavigation() {
    val navController = rememberNavController()

    val viewModel: MainViewModel = viewModel()

    NavHost(navController = navController, startDestination = "home") {

    composable("home") {
         HomeScreen(navController, viewModel)
    }
    composable("dashboard") {
         DashboardScreen(navController, viewModel) }
    }
}

Alternatively, you can access the activity context view model within each screen by

val viewModel: MainViewModel = viewModel(LocalContext.current as ComponentActivity)