Navigate with arguments in Jetpack Compose

Daniel Atitienei
3 min readAug 4, 2022

Introduction

There are 2 ways to navigate with arguments, and I’ll explain both of them.

  1. Pass arguments directly to the screen
  2. Get them from SavedStateHandle from ViewModel

Pass arguments directly to the screen

Firstly we need to add argument placeholders to the route.

Navigate with arguments (you can pass only string types)

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

NavHost(
navController = navController,
startDestination = "home"
) {
composable("car/{carId}") { navBackStackEntry ->
/* Extracting the id from the route */
val carId = navBackStackEntry.arguments?.getString("carId")
/* We check if is null */
carId?.let {
CarScreen(carId = it.toInt())
}
}
/* ... */
}
}

@Composable
fun HomeScreen(navController: NavController) {
Button(
onClick = {
/* Replacing {carId} with 1 */
navController.navigate(
"car/{carId}"
.replace(
oldValue = "{carId}",
newValue = "${1}"
)
)
}…

--

--