tezvyn:

Navigation in Compose

AI-drafted, machine-checkedSource: developer.android.comintermediate
Navigation in Compose

Navigation in Compose treats screens as state. You define a graph of composables, each with a string 'route', and navigate by changing the current route. It's ideal for single-activity apps.

WHY IT EXISTS: To provide a declarative, Compose-native way to handle navigation, replacing the imperative, fragment-based Navigation component from the View system. It integrates state management directly into navigation logic, making it a natural fit for the Compose paradigm.

THE MENTAL MODEL: Treat your app's screens like a state machine. Each screen is a composable function identified by a unique string called a "route". Navigation is simply the act of changing the current route state, which causes the NavHost to display the corresponding composable. Think of it like a web browser: routes are URLs, and navigating is like clicking a link.

HOW IT WORKS: You create a NavController instance, usually remembered at a high level in your UI tree. This controller is then passed to a NavHost composable. Inside the NavHost, you build a navigation graph using a DSL. This graph maps string routes to the composable functions that should be displayed for those routes. To trigger a navigation event, you call a method on the controller, like navController.navigate("profile_route"). The NavController updates its internal back stack and state, and the NavHost recomposes to show the new screen.

WHEN TO USE IT: This is the standard library for navigation in any app built primarily with Jetpack Compose. Use it for handling screen transitions, passing arguments between screens, implementing deep links, and managing a back stack within a single-activity architecture. It provides a scalable and testable structure for your app's flow.

WHEN NOT TO USE IT: In a legacy application heavily reliant on Fragments, a full migration might be complex. While interoperability APIs exist to navigate between Compose and View-based screens, they add complexity. For extremely simple UIs that only toggle between two views, a simple boolean state might suffice, though the Navigation component offers a more robust long-term solution.

ONE CANONICAL EXAMPLE: A NavHost is defined with two destinations. The first has the route "home" and shows a HomeScreen composable. The second has the route "profile/{userId}" and shows a ProfileScreen composable, which accepts a userId argument. From the home screen, a button's onClick listener would call navController.navigate("profile/user123"). The Navigation library automatically parses "user123" from the route, passes it as an argument to the ProfileScreen, and displays it.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.