How to Navigate with Passing Arguments in Jetpack Compose?

39 Views Asked by At

Could someone provide a clear explanation or example code demonstrating how to navigate between destinations and pass arguments using Jetpack Compose?

In LoginPage1 when I click on button I want to go to next page with same param

//MainActivity.kt
Surface(
    modifier = Modifier.fillMaxSize(),
    color = MaterialTheme.colorScheme.background
) {
    LoginPage1(navController)
}

//LoginPage1
Button(
    onClick = { "go to next page" },
    shape = MaterialTheme.shapes.medium,
    colors = ButtonDefaults.buttonColors(orange),
) {
}

I tried this but I get a java.lang.NullPointerException:

Button(
    onClick = { navController.navigate("onboardingPage1") },
    shape = MaterialTheme.shapes.medium,
    colors = ButtonDefaults.buttonColors(orange),
)
2

There are 2 best solutions below

0
On

In Jetpack Compose, we can use the NavController to navigate between composable functions. We can also pass arguments between destinations. First, you need to set up your navigation in your MainActivity.kt:

val navController = rememberNavController()

NavHost(navController, startDestination = "loginPage1") {
    composable("loginPage1") { LoginPage1(navController) }
    composable("onboardingPage1/{param}", arguments = listOf(navArgument("param") { type = NavType.StringType })) { backStackEntry ->
        OnboardingPage1(backStackEntry.arguments?.getString("param"))
    }
}

{param} is a placeholder here for the argument that you want to pass to onboardingpage1.

Then, in LoginPage1, you can navigate to onboardingpage1 and pass an argument like:

Button(
    onClick = { navController.navigate("onboardingpage1/actual_value") },
    shape = MaterialTheme.shapes.medium,
    colors = ButtonDefaults.buttonColors(orange),
) {
    Text("Go to next page")
}

Here also replace "onboardingpage1/actual_value" with your actual route and parameter.

In onboardingpage1, you can retrieve the passed argument like:

@Composable
fun onboardingpage1(param: String?) {
    // Use param here
}

The NullPointerException you’re seeing might be due to navController being null at the time of the onClick event. Make sure navController is properly initialized before it’s used.

3
On

First You need to declare param in destination route

object Constants {
    const val USER_DETAIL = "USER_DETAIL/{USER_ID}"
}

On Navigation Button Click

rootNavController.navigate(Constants.USER_DETAIL.replace("USER_ID",userId))

get param value in below way in Nav graph

@Composable
fun NavigationGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Screen.Login.route
    ){
        // .... 
        
        //.....
        composable(Constants.UserDetail) {
            val userId = it.arguments?.getString("USER_ID")?.toLong() ?: -1L
            UserDetailScreen(
                userId = userId
            )
        }
    }
}