How to Navigate in Jetpack Compose in Android
In Jetpack Compose, navigation is handled using the
Navigation component and NavController. You define navigation routes with NavHost and navigate between composables using navController.navigate().Syntax
Jetpack Compose navigation uses these main parts:
- NavController: Controls navigation actions.
- NavHost: Hosts composables and defines navigation graph.
- Composable destinations: Screens defined with routes.
- navController.navigate(route): Moves to a new screen.
kotlin
val navController = rememberNavController() NavHost(navController = navController, startDestination = "home") { composable("home") { HomeScreen(navController) } composable("details") { DetailsScreen() } }
Example
This example shows a simple app with two screens: Home and Details. Clicking a button on Home navigates to Details.
kotlin
import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.navigation.compose.* @Composable fun AppNavigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "home") { composable("home") { HomeScreen(navController) } composable("details") { DetailsScreen() } } } @Composable fun HomeScreen(navController: NavController) { Button(onClick = { navController.navigate("details") }) { Text("Go to Details") } } @Composable fun DetailsScreen() { Text("This is the Details Screen") }
Output
The app shows a button labeled 'Go to Details'. When tapped, it navigates to a screen displaying 'This is the Details Screen'.
Common Pitfalls
Common mistakes when navigating in Jetpack Compose include:
- Not using
rememberNavController()to keep navigation state. - Forgetting to add all routes in
NavHost. - Using incorrect route strings in
navController.navigate(). - Not handling back navigation properly.
Always define all composable destinations and use consistent route names.
kotlin
/* Wrong: Missing NavHost or wrong route */ navController.navigate("detail") // typo: should be "details" /* Right: Correct route and NavHost setup */ navController.navigate("details")
Quick Reference
| Concept | Description |
|---|---|
| NavController | Manages app navigation and back stack |
| NavHost | Container that hosts composable destinations |
| composable(route) | Defines a screen with a route string |
| navController.navigate(route) | Navigate to a screen by route |
| rememberNavController() | Creates and remembers NavController instance |
Key Takeaways
Use rememberNavController() to create a navigation controller in Compose.
Define all screens as composable destinations inside NavHost with unique routes.
Navigate between screens using navController.navigate(route).
Ensure route names are consistent and correctly spelled.
Handle back navigation automatically with NavController.