Jetpack Compose Navigation — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Navigation. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You navigate to a screen and the back button takes you to the wrong place, or you pass arguments that arrive as null, or the screen recreates when it shouldn't.
Wrong Approach ❌
@Composable
fun BadNav() {
val navController = rememberNavController()
NavHost(navController, startDestination = "home") {
composable("home") { Home(navController) }
composable("details/{id}") { backStackEntry ->
val id = backStackEntry.arguments?.getString("id") // Null!
Details(id ?: "missing")
}
}
}
// Direct navigation without route management
navController.navigate("details/123") // Multiple back stack entries
Output: Null argument, multiple "details" entries on the back stack.
Right Approach ✅
// Define routes as sealed class
sealed class Screen(val route: String) {
object Home : Screen("home")
object Details : Screen("details/{id}") {
fun create(id: String) = "details/$id"
}
}
@Composable
fun GoodNav() {
val navController = rememberNavController()
NavHost(navController, startDestination = Screen.Home.route) {
composable(
route = Screen.Details.route,
arguments = listOf(navArgument("id") { type = NavType.StringType })
) { backStackEntry ->
val id = backStackEntry.arguments?.getString("id") ?: return@composable
Details(id)
}
composable(Screen.Home.route) {
Home(onNavigate = { navController.navigate(Screen.Details.create(it)) })
}
}
}
// Single top — prevents duplicate entries
navController.navigate(Screen.Details.create(id)) {
launchSingleTop = true
restoreState = true
}
Output: Type-safe arguments, single top stack, proper state restoration.
Prevention
- Always use
NavTypefor arguments — never parse them manually. - Use
launchSingleTop = trueto prevent duplicate screens. - Use
restoreState = trueto preserve state when navigating back. - Define routes in a sealed class for compile-time safety.
Common Mistakes with compose navigation
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro