Leave a rating/review
When navigating to destinations, you sometimes need to pass data to the destination. In this episode, you’ll learn how to pass data to destinations using the Jetpack Compose navigation library.
You’ll use the Safe Args plugin to pass data to destinations. The Safe Args plugin generates type-safe code for navigating to destinations and passing data to them. This plugin is included in the Jetpack Compose navigation library.
Head over to the project-level build.gradle. Add the following code above the plugins block:
buildscript {
dependencies {
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.3"
}
}
This code adds the Safe Args plugin to your project.
Next,open the app module-level build.gradle.
Add the following code below the kotlin-parcelize plugin:
id 'androidx.navigation.safeargs.kotlin'
Do a gradle sync to add the plugin to your project.
Navigate to TaskDetailsScreen composable.
Add the following arguments to the TaskDetailsScreen composable:
taskName: String?,
onBackPressed: () -> Unit
In this code, the taskName argument is the name of the task. The onBackPressed argument is a lambda that is called when the user clicks the back button.
Now, head over to AppNavHost.kt file. Replace the TaskDetailScreen composable in the graph with the following code:
composable(
route = "${Screens.TaskDetailScreen.route}/{taskListName}",
arguments = listOf(navArgument("taskListName") { type = NavType.StringType })
) {
TaskDetailScreen(
taskName = it.arguments?.getString("taskListName"),
onBackPressed = { navController.popBackStack() }
)
}
A few changes to highlight:
-
You’ve added the
argumentsparameter to thecomposablefunction. This parameter takes a list ofNavArgumentobjects. TheNavArgumentobject takes the name of the argument and the type of the argument. In the code above, you’re passing thetaskListNameargument and the type of the argument is a string. -
You’re passing the
taskListNameargument to theTaskDetailScreencomposable. You’re also passing a lambda to theonBackPressedparameter. This lambda calls thepopBackStackmethod on thenavController. This will pop the current destination from the back stack and navigate to the previous destination.
Lastly, you need to pass the taskListName argument to the TaskDetailScreen composable.
Still inside AppNavHost.kt, inside the TaskLisScreen composable nav graph entry, replace the navigate lambda contents with the following code:
navController.navigate("${Screens.TaskDetailScreen.route}/$taskListName")
Here, you pass the taskListName argument to the TaskDetailScreen composable.
Build and run the app.
Click on a task to navigate to the TaskDetailScreen composable. nothing much changed as you haven’t finalized all the pieces yet. In the next episode, you’ll add the functionality to save task todos for the TaskDetailScreen composable. You’ll also display the task name on the TaskDetailScreen composable.