Jetpack Compose Navigation with ViewModels (Example)

Short answer: in Jetpack Compose you navigate with the Navigation Compose library. Create a NavController with rememberNavController(), declare your screens inside a NavHost with composable(route), and move between them with navController.navigate(route). Each destination can have its own ViewModel scoped to its back stack entry.

This guide shows a complete example with arguments, back navigation, bottom-bar style navigation and ViewModels. Check the official Navigation documentation for the latest version number.

Step 1: Add the dependencies

dependencies {
    implementation("androidx.navigation:navigation-compose:NAV_VERSION")
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:LIFECYCLE_VERSION")
}

Step 2: Create the screens

@Composable
fun HomeScreen(onOpenDetails: (Int) -> Unit) {
    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text("Home", style = MaterialTheme.typography.headlineMedium)
        Button(onClick = { onOpenDetails(42) }) {
            Text("Open item 42")
        }
    }
}

@Composable
fun DetailsScreen(itemId: Int, onBack: () -> Unit) {
    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text("Details for item $itemId", style = MaterialTheme.typography.headlineMedium)
        Button(onClick = onBack) { Text("Back") }
    }
}

Screens receive callbacks instead of the NavController. That keeps them easy to preview and test.

Step 3: Set up the NavHost

@Composable
fun AppNavigation() {
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = "home") {
        composable("home") {
            HomeScreen(onOpenDetails = { id -> navController.navigate("details/$id") })
        }
        composable(
            route = "details/{itemId}",
            arguments = listOf(navArgument("itemId") { type = NavType.IntType })
        ) { backStackEntry ->
            val itemId = backStackEntry.arguments?.getInt("itemId") ?: 0
            DetailsScreen(
                itemId = itemId,
                onBack = { navController.popBackStack() }
            )
        }
    }
}

Call AppNavigation() from setContent { } in your Activity. Pass only simple values such as IDs between screens, then load the full data in the destination’s ViewModel. Do not pass large objects as arguments.

Step 4: Use a ViewModel for each destination

When you call viewModel() inside a composable destination, the ViewModel is scoped to that back stack entry. It is created when the screen is first shown and cleared when the screen is popped off the back stack.

class DetailsViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val itemId: Int = checkNotNull(savedStateHandle["itemId"])

    private val _title = MutableStateFlow("Item $itemId")
    val title: StateFlow<String> = _title.asStateFlow()
}

composable(
    route = "details/{itemId}",
    arguments = listOf(navArgument("itemId") { type = NavType.IntType })
) {
    val viewModel: DetailsViewModel = viewModel()
    val title by viewModel.title.collectAsState()
    Text(title)
}

Navigation puts the route arguments into the SavedStateHandle, so the ViewModel can read them directly. If your ViewModel has other constructor parameters, use a factory or Hilt with hiltViewModel(). For more on structuring state, see our MVVM tutorial.

Share a ViewModel between screens

To share state across several screens in one flow, scope the ViewModel to a parent entry or a nested navigation graph:

composable("checkout/address") { entry ->
    val parentEntry = remember(entry) { navController.getBackStackEntry("checkout") }
    val sharedViewModel: CheckoutViewModel = viewModel(parentEntry)
    // use sharedViewModel
}

Bottom navigation without piling up screens

When tabs switch between top-level screens, avoid stacking duplicates and keep each tab’s state:

navController.navigate(route) {
    popUpTo(navController.graph.findStartDestination().id) {
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}

Type-safe navigation

Newer versions of Navigation Compose support type-safe routes using Kotlin serializable classes instead of route strings, which removes many string typos. If your project uses a recent version, check the official docs and consider using it for new code. The concepts above (NavHost, NavController, back stack, scoped ViewModels) stay the same.

Common mistakes

  • Creating a new NavController in each screen. Create it once at the top and pass callbacks down.
  • Passing whole objects through the route. Pass an ID and load the data in the ViewModel.
  • Calling navigate() during composition. Call it from click handlers or effects, not while drawing.
  • Forgetting launchSingleTop and ending up with duplicate screens on the back stack.
  • Typos in route strings. Define routes as constants or use type-safe navigation.

FAQ

How do I navigate between screens in Jetpack Compose?

Use Navigation Compose: create a NavController, define destinations in a NavHost and call navController.navigate("route").

How do I pass arguments between screens?

Add a placeholder to the route such as details/{itemId}, declare it with navArgument, and read it from backStackEntry.arguments or the ViewModel’s SavedStateHandle.

Is a ViewModel created for each screen?

Yes. A ViewModel requested inside a destination is scoped to that back stack entry and cleared when the entry is removed.

How do I go back to the previous screen?

Call navController.popBackStack() or let the system back button handle it.

Next, add a navigation drawer in Jetpack Compose or browse more Jetpack Compose tutorials.