Navigation lets users move between screens. In Compose, the Navigation component gives you a NavHost, routes, and a NavController.
Basic Setup
Each screen gets a route.
object Routes {
const val Home = "home"
const val Details = "details"
}
Then define a navigation graph.
@Composable
fun AppNavHost() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = Routes.Home
) {
composable(Routes.Home) {
HomeScreen(
onOpenDetails = {
navController.navigate(Routes.Details)
}
)
}
composable(Routes.Details) {
DetailsScreen(
onBack = { navController.popBackStack() }
)
}
}
}
Passing Arguments
Routes can include arguments.
navController.navigate("lesson/$lessonId")
Define the receiving route:
composable("lesson/{lessonId}") { backStackEntry ->
val lessonId = backStackEntry.arguments?.getString("lessonId")
LessonScreen(lessonId = lessonId)
}
For larger apps, use typed routes with @Serializable data classes instead of raw strings. Typed routes catch typos and argument mismatches at compile time.
@Serializable
data object HomeRoute
@Serializable
data class LessonRoute(val lessonId: String)
// Navigate
navController.navigate(LessonRoute(lessonId = "lesson-1"))
// In NavHost
composable<LessonRoute> { backStackEntry ->
val route: LessonRoute = backStackEntry.toRoute()
LessonScreen(lessonId = route.lessonId)
}
This requires Navigation 2.8.0 or later, which is now the standard.
Back Stack
Navigation keeps a back stack. navigate adds a destination. popBackStack returns to the previous one.
Use popUpTo when you do not want users to return to earlier screens after a state change like login. Without it, pressing back from Home would return the user to the Login screen.
navController.navigate(Routes.Home) {
popUpTo(Routes.Login) { inclusive = true }
}
inclusive = true removes the Login destination itself from the stack. After this, the back stack starts at Home and pressing back exits the app.
Practice
Create three screens: Home, Lesson List, and Lesson Detail. Navigate from Home to the list, then from a lesson row to the detail screen.
Summary
Compose Navigation gives structure to screen movement. Learn NavHost, NavController, typed routes, argument passing, popUpTo for clearing the back stack, and back stack behavior. These are used in every multi-screen Android app.