Navigation in Jetpack Compose

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Jellyfish

Lesson 02: Use Navigation Arguments

Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll continue to build on the movie booking application from the previous lesson.

Open the starter project and find a file named TicketSelectionScreen.kt added to the project. This screen prompts the user to select the number of tickets required for the movie selected on the MovieSelectionScreen.kt.

You’re going to define the logic to navigate from MovieSelectionScreen to TicketSelectionScreen, wherein you’ll pass the movie name as a navigation argument from MovieSelectionScreen to TicketSelectionScreen.

Open Screens.kt and notice that a route for TicketSelectionScreen has been added in the Screens enum for your convenience. However, it doesn’t support any argument yet.

Back in MovieSelectionScreen.kt, you can observe the lambda defined as the onNextClick parameter of MovieSelectionScreen, which navigates to the route but doesn’t specify any argument currently.

Define a destination in the navigation graph in MainActivity.kt for TicketSelectionScreen with a ‘movieName’ argument as follows:

composable(
  TICKET_SELECTION_SCREEN.route,
  arguments = listOf(navArgument("movieName") { type = NavType.StringType })
) { backStackEntry ->
  TicketSelectionScreen(
    movieName = requireNotNull(
      backStackEntry.arguments?.getString(MOVIE_NAME_ARG)
    )
  )
}

Try running the app. Observe that when the user navigates from the movie selection screen to the ticket selection screen, the app crashes. This is because the argument wasn’t provided to the ticket selection screen.

To define the argument in the route for ticket-selection screen, update TICKET_SELECTION_SCREEN inside Screens as follows:

TICKET_SELECTION_SCREEN("ticket-selection/{$MOVIE_NAME_ARG}"),

Now, head back to MainActivity.kt to pass the argument when navigating from the movie-selection screen as shown below:

MovieSelectionScreen(onNextClick = { movieName ->
  navController.navigate(
    TICKET_SELECTION_SCREEN.route.replace(
      "{$MOVIE_NAME_ARG}",
      movieName
    )
  )
})

Run the app to see if it works.

Voila! The app successfully navigates from the movie-selection screen to the ticket-selection screen. The movie name passed as the argument to the ticket selection screen is used to inform the user of the movie name they are trying to select tickets for.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion