Yokan / rebuild
Course 1 8624561

07-navigation.md

.codex/skills/compose-kotlin-agent-skills/references/07-navigation.md

documentation / design asset311 lines
1# Navigation — Nav 3, Type-Safe Routes, Deep Links23## Contents45- Navigation 3 overview6- Type-safe routes with @Serializable7- Deep links8- Back stack management9- Shared element transitions10- Bottom nav + nested graphs11- Migration from Nav 21213## Navigation 3 Overview1415Nav 3 (androidx.navigation 2.9+) uses `@Serializable` data classes as routes instead of string paths.1617```toml18[dependencies]19navigation-compose = { module = "androidx.navigation:navigation-compose", version = "2.9.0" }20kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version = "1.8.1" }21```2223## Type-Safe Routes2425```kotlin26// Define routes as @Serializable classes27@Serializable28object Home2930@Serializable31object Settings3233@Serializable34data class AccountDetail(val accountId: String)3536@Serializable37data class Workout(val type: String, val difficulty: String = "standard")3839// NavHost setup40@Composable41fun AppNavHost(navController: NavHostController = rememberNavController()) {42    NavHost(navController = navController, startDestination = Home) {4344        composable<Home> {45            HomeScreen(46                onAccountClick = { id ->47                    navController.navigate(AccountDetail(accountId = id))48                },49                onSettingsClick = { navController.navigate(Settings) }50            )51        }5253        composable<AccountDetail> { backStackEntry ->54            val route = backStackEntry.toRoute<AccountDetail>()55            AccountDetailScreen(56                accountId = route.accountId,57                onBack = { navController.popBackStack() }58            )59        }6061        composable<Settings> {62            SettingsScreen(onBack = { navController.popBackStack() })63        }6465        composable<Workout> { backStackEntry ->66            val route = backStackEntry.toRoute<Workout>()67            WorkoutScreen(68                workoutType = route.type,69                difficulty = route.difficulty70            )71        }72    }73}74```7576**Why @Serializable routes:** compile-time type safety. String routes like `"detail/$id"` crash at runtime if you typo the arg name. Serializable routes fail at compile time.7778## Deep Links7980### Implicit Deep Links8182```kotlin83composable<AccountDetail>(84    deepLinks = listOf(85        navDeepLink<AccountDetail>(86            basePath = "https://myapp.com/account"87        )88    )89) { backStackEntry ->90    val route = backStackEntry.toRoute<AccountDetail>()91    AccountDetailScreen(accountId = route.accountId)92}93```9495```xml96<!-- AndroidManifest.xml -->97<activity android:name=".MainActivity">98    <intent-filter>99        <action android:name="android.intent.action.VIEW" />100        <category android:name="android.intent.category.DEFAULT" />101        <category android:name="android.intent.category.BROWSABLE" />102        <data android:scheme="https" android:host="myapp.com" />103    </intent-filter>104</activity>105```106107### Explicit Deep Links (Internal Navigation)108109```kotlin110// From notification or accessibility service111val intent = Intent(context, MainActivity::class.java).apply {112    data = "https://myapp.com/account?accountId=abc123".toUri()113    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP114}115context.startActivity(intent)116```117118## Back Stack Management119120### Pop to Specific Destination121122```kotlin123// Pop back to Home, removing everything above it124navController.popBackStack(route = Home, inclusive = false)125126// Navigate and clear back stack (login → home)127navController.navigate(Home) {128    popUpTo(navController.graph.startDestinationId) { inclusive = true }129    launchSingleTop = true130}131```132133### Single Top — Prevent Duplicate Destinations134135```kotlin136navController.navigate(Settings) {137    launchSingleTop = true  // reuse existing instance instead of creating new138}139```140141### Save and Restore State (Tab Navigation)142143```kotlin144fun NavHostController.navigateToTab(route: Any) {145    navigate(route) {146        popUpTo(graph.startDestinationId) {147            saveState = true     // save state of popped destinations148        }149        launchSingleTop = true150        restoreState = true      // restore state when re-selecting tab151    }152}153```154155## Bottom Navigation + Nested Graphs156157```kotlin158@Serializable object HomeGraph159@Serializable object ProgressGraph160@Serializable object SettingsGraph161162@Serializable object HomeRoot163@Serializable object ProgressRoot164@Serializable object SettingsRoot165@Serializable data class WorkoutDetail(val id: String)166167@Composable168fun MainScreen() {169    val navController = rememberNavController()170171    Scaffold(172        bottomBar = {173            NavigationBar {174                val currentEntry by navController.currentBackStackEntryAsState()175                val currentRoute = currentEntry?.destination?.route176177                NavigationBarItem(178                    selected = currentRoute?.contains("Home") == true,179                    onClick = { navController.navigateToTab(HomeGraph) },180                    icon = { Icon(Icons.Default.Home, "Home") },181                    label = { Text("Home") }182                )183                NavigationBarItem(184                    selected = currentRoute?.contains("Progress") == true,185                    onClick = { navController.navigateToTab(ProgressGraph) },186                    icon = { Icon(Icons.Default.Timeline, "Progress") },187                    label = { Text("Progress") }188                )189                NavigationBarItem(190                    selected = currentRoute?.contains("Settings") == true,191                    onClick = { navController.navigateToTab(SettingsGraph) },192                    icon = { Icon(Icons.Default.Settings, "Settings") },193                    label = { Text("Settings") }194                )195            }196        }197    ) { padding ->198        NavHost(199            navController = navController,200            startDestination = HomeGraph,201            modifier = Modifier.padding(padding)202        ) {203            navigation<HomeGraph>(startDestination = HomeRoot) {204                composable<HomeRoot> {205                    HomeScreen(onWorkoutClick = { id ->206                        navController.navigate(WorkoutDetail(id))207                    })208                }209                composable<WorkoutDetail> { /* ... */ }210            }211212            navigation<ProgressGraph>(startDestination = ProgressRoot) {213                composable<ProgressRoot> { ProgressScreen() }214            }215216            navigation<SettingsGraph>(startDestination = SettingsRoot) {217                composable<SettingsRoot> { SettingsScreen() }218            }219        }220    }221}222```223224**Nested graphs** give each tab its own back stack. Navigating between tabs preserves scroll position and state.225226## Passing Complex Data227228```kotlin229// WRONG — serializing entire object through nav args230navController.navigate(AccountDetail(account = entireAccountObject))231232// RIGHT — pass ID, fetch in destination ViewModel233@Serializable234data class AccountDetail(val accountId: String)  // just the ID235236@HiltViewModel237class AccountDetailViewModel @Inject constructor(238    private val repo: AuthRepository,239    savedStateHandle: SavedStateHandle240) : ViewModel() {241    private val accountId: String = savedStateHandle.toRoute<AccountDetail>().accountId242243    val account: StateFlow<AuthAccount?> = repo.getAccountById(accountId)244        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)245}246```247248**Rule:** nav args = IDs and simple primitives. Fetch the full object from ViewModel/Repository on the destination screen.249250## Shared Element Transitions251252```kotlin253@Composable254fun AppNavHost(navController: NavHostController) {255    SharedTransitionLayout {256        NavHost(navController = navController, startDestination = Home) {257            composable<Home> {258                HomeScreen(259                    onAccountClick = { account ->260                        navController.navigate(AccountDetail(account.id))261                    },262                    animatedVisibilityScope = this263                )264            }265            composable<AccountDetail> {266                AccountDetailScreen(267                    animatedVisibilityScope = this268                )269            }270        }271    }272}273274@Composable275fun AccountCard(276    account: AuthAccount,277    onClick: () -> Unit,278    sharedTransitionScope: SharedTransitionScope,279    animatedVisibilityScope: AnimatedVisibilityScope280) {281    with(sharedTransitionScope) {282        Card(283            modifier = Modifier284                .sharedElement(285                    state = rememberSharedContentState(key = "card-${account.id}"),286                    animatedVisibilityScope = animatedVisibilityScope287                )288                .clickable(onClick = onClick)289        ) {290            Text(291                text = account.serviceName,292                modifier = Modifier.sharedElement(293                    state = rememberSharedContentState(key = "name-${account.id}"),294                    animatedVisibilityScope = animatedVisibilityScope295                )296            )297        }298    }299}300```301302**Keys must match** between source and destination. Use consistent key generation: `"card-${id}"`, `"name-${id}"`.303304## Anti-Patterns305306- **String route paths** → use `@Serializable` routes. String typos crash at runtime307- **Passing Parcelable/Serializable objects as nav args** → pass IDs, fetch on destination308- **`navigate()` without `launchSingleTop`** → rapid taps create duplicate destinations309- **Nested `NavHost` for bottom tabs** → use nested `navigation()` graphs in single NavHost310- **ViewModel in nav args** → ViewModels are scoped to lifecycle, not navigation. Use `hiltViewModel()` scoped to back stack entry311- **Forgetting `popUpTo` on login→home** → user presses back from home and sees login again312

Search chapters, reference and source filenames.