aldefy/compose-skill / skills/compose-expert
compose-expert
UnverifiedCompose and Compose Multiplatform expert for UI development across Android, Desktop, iOS, and Web. Use whenever the user mentions Compose APIs (@Composable, remember, LaunchedEffect, NavHost, MaterialTheme, LazyColumn, Modifier, recomposition), Compose Multiplatform (commonMain, expect/actual, Res.*, ComposeUIViewController, UIKitView, ComposeViewport), Android TV (tv-material, D-pad, focus, Carousel), Material 3 motion, atomic design systems, design-to-code workflows, Paging 3, or navigation. Activates Review Mode on GitHub PR URLs and review phrases ("review this PR", "what's wrong with this"). Auto-detects Compose projects on session_start. Backed by actual androidx/androidx and JetBrains/compose-multiplatform-core source receipts. See "## When this skill applies" in SKILL.md for the full trigger surface.
references/navigation.md
View on GitHub# Navigation in Jetpack Compose
Reference: `androidx/navigation/navigation-compose/src/commonMain/kotlin/androidx/navigation/compose/`
> **Compose Multiplatform readers:** Navigation 2 (the `NavHost` / `NavController`
> API documented below) targets Android. Compose Multiplatform support for Nav 2
> in `commonMain` is partial and historically lagged Android. For new
> multiplatform projects (Android + iOS + Desktop + Web), prefer Navigation 3 —
> see `navigation-migration.md` for the API differences and a decision guide.
> The Nav 2 patterns in this file remain accurate for Android-only apps and for
> understanding the migration target.
## Setup
### Basic NavHost and NavController
```kotlin
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "home" // Use Route::class with type-safe navigation
) {
composable<Home> {
HomeScreen(onNavigate = { navController.navigate(Details()) })
}
}
```
`rememberNavController()` creates a `NavController` that survives recomposition. Always use it in `NavHost`—never create `NavController` in a ViewModel.
## Type-Safe Navigation (Navigation 2.8+)
Use `@Serializable` route classes instead of string routes. This is the recommended pattern.
```kotlin
@Serializable
data class Home(val userId: String? = null)
@Serializable
data class Details(val itemId: Int)
NavHost(navController, startDestination = Home()) {
composable<Home> { backStackEntry ->
val args = backStackEntry.toRoute<Home>()
HomeScreen(userId = args.userId)
}
composable<Details> { backStackEntry ->
val args = backStackEntry.toRoute<Details>()
DetailsScreen(itemId = args.itemId)
}
}
```
Serialize complex types using `@Serializable` on nested data classes:
```kotlin
@Serializable
data class User(val id: Int, val name: String)
@Serializable
data class UserProfile(val user: User)
// Navigate:
navController.navigate(UserProfile(user = User(1, "Alice")))
```
## Declaring Destinations
### composable — Screen destinations
```kotlin
composable<Route> { backStackEntry ->
ScreenContent()
}
```
### dialog — Dialog destinations
```kotlin
dialog<Route> { backStackEntry ->
AlertDialog(...)
}
```
### navigation — Nested graphs (feature modules)
```kotlin
navigation<RootRoute>(startDestination = Home()) {
composable<Home> { HomeScreen() }
composable<Details> { DetailsScreen() }
}
```
## Navigating
### Navigate to a destination
```kotlin
// Type-safe
navController.navigate(Details(itemId = 42))
// Avoid: string-based navigation
navController.navigate("details/42") // Anti-pattern
```
### Pop back stack
```kotlin
navController.popBackStack()
// Pop with return value (save state before popping)
navController.previousBackStackEntry?.savedStateHandle?.set("key", value)
navController.popBackStack()
// In destination, retrieve:
val result = navController.currentBackStackEntry?.savedStateHandle?.get<T>("key")
```
### popUpTo — Clear back stack
```kotlin
// Navigate to Details, clearing Home from stack
navController.navigate(
Details(itemId = 42),
navOptions = navOptions {
popUpTo(Home::class) { inclusive = false }
}
)
// inclusive = true: Remove the target route too
navController.navigate(
Login(),
navOptions = navOptions {
popUpTo(Home::class) { inclusive = true }
}
)
// launchSingleTop: Reuse existing instance if already on stack
navController.navigate(
Details(itemId = 42),
navOptions = navOptions {
launchSingleTop = true
}
)
```
## Arguments and Back Stack Data
Compose Navigation handles serialization automatically with `@Serializable` routes.
### Passing complex data
```kotlin
@Serializable
data class Message(val id: Int, val text: String, val metadata: Metadata)
@Serializable
data class Metadata(val timestamp: Long, val priority: Int)
navController.navigate(Message(1, "Hello", Metadata(System.currentTimeMillis(), 1)))
```
### Result passing via SavedStateHandle
```kotlin
// Send result back
navController.previousBackStackEntry?.savedStateHandle?.set("result", "success")
navController.popBackStack()
// Receive in previous screen
val result = navController.currentBackStackEntry?.savedStateHandle?.get<String>("result")
```
## Nested Navigation Graphs
Organize related destinations into feature graphs.
```kotlin
navigation<FeatureRoot>(startDestination = FeatureHome()) {
composable<FeatureHome> { FeatureHomeScreen(onNext = { navController.navigate(FeatureDetail()) }) }
composable<FeatureDetail> { FeatureDetailScreen() }
}
```
Benefits: scoped ViewModels, separate back stack behavior, feature isolation.
## Deep Links
Declare deep links to open your app from URLs or notifications.
```kotlin
composable<Details>(
deepLinks = listOf(
navDeepLink<Details>(
uriPattern = "https://example.com/details/{itemId}"
)
)
) { backStackEntry ->
val args = backStackEntry.toRoute<Details>()
DetailsScreen(itemId = args.itemId)
}
// Navigate via deep link
navController.navigate("https://example.com/details/42")
```
Handle in `AndroidManifest.xml`:
```xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="example.com" />
</intent-filter>
</activity>
```
## Back Stack Management
### saveState / restoreState
Preserve screen state during navigation:
```kotlin
navController.navigate(
Details(itemId = 42),
navOptions = navOptions {
saveState = true
restoreState = true
}
)
```
### Check current route
```kotlin
val currentRoute = navController.currentBackStackEntry?.destination?.route
```
### Observe back stack
```kotlin
val backStackEntry by navController.currentBackStackEntryAsState()
val route = backStackEntry?.destination?.route
```
## Bottom Navigation Integration
```kotlin
var selectedItem by remember { mutableStateOf("home") }
val navController = rememberNavController()
Scaffold(
bottomBar = {
NavigationBar {
NavigationBarItem(
selected = selectedItem == "home",
onClick = {
selectedItem = "home"
navController.navigate(Home()) {
popUpTo(Home::class) { inclusive = true }
launchSingleTop = true
}
},
icon = { Icon(Icons.Default.Home, null) },
label = { Text("Home") }
)
NavigationBarItem(
selected = selectedItem == "profile",
onClick = {
selectedItem = "profile"
navController.navigate(Profile()) {
popUpTo(Home::class) { inclusive = false }
launchSingleTop = true
}
},
icon = { Icon(Icons.Default.Person, null) },
label = { Text("Profile") }
)
}
}
) {
NavHost(navController, startDestination = Home()) {
composable<Home> { HomeScreen() }
composable<Profile> { ProfileScreen() }
}
}
```
Executable smoke check for the bottom bar semantics:
```kotlin verify
// name: bottom-navigation-renders-tab-labels
// repeat: 3
// assert: text = "Home"
// assert: text = "Profile"
// assert: content-description = "Home tab"
// assert: content-description = "Profile tab"
// assert-not: text = "Settings"
@Composable
fun Subject() {
NavigationBar {
NavigationBarItem(
selected = true,
onClick = {},
icon = { Box(Modifier.semantics { contentDescription = "Home tab" }) },
label = { Text("Home") }
)
NavigationBarItem(
selected = false,
onClick = {},
icon = { Box(Modifier.semantics { contentDescription = "Profile tab" }) },
label = { Text("Profile") }
)
}
}
```
## Shared Element Transitions
```kotlin
NavHost(navController, startDestination = List()) {
composable<List>(
sharedTransitionSpec = {
SharedTransitionLayout()
}
) {
ListScreen()
}
composable<Detail>(
sharedTransitionSpec = {
SharedTransitionLayout()
}
) {
DetailScreen()
}
}
```
Use in screens:
```kotlin
Image(
painter = painterResource(id = R.drawable.image),
contentDescription = null,
modifier = Modifier.sharedBounds(
sharedContentState = rememberSharedContentState(key = "image"),
animatedVisibilityScope = this
)
)
```
## ViewModel Scoping with Navigation
Use `hiltViewModel()` to scope ViewModels to a back stack entry.
```kotlin
composable<Details> { backStackEntry ->
val viewModel: DetailsViewModel = hiltViewModel()
DetailsScreen(viewModel = viewModel)
}
```
ViewModels scoped this way survive configuration changes but are cleared when the back stack entry is removed.
## Testing Navigation
Use `TestNavHostController` to test navigation behavior.
```kotlin
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun navigateToDetails() {
val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
navController.navigatorProvider.addNavigator(ComposeNavigator())
composeTestRule.setContent {
NavHost(navController, startDestination = Home()) {
composable<Home> { HomeScreen(onNavigate = { navController.navigate(Details()) }) }
composable<Details> { DetailsScreen() }
}
}
composeTestRule.onNodeWithTag("detail_button").performClick()
assertEquals(Details::class.serializer().descriptor.serialName, navController.currentBackStackEntry?.destination?.route)
}
```
## Anti-Patterns
### Don't: Use string-based routes
```kotlin
// ❌ Anti-pattern
navController.navigate("details/42")
// ✅ Correct
navController.navigate(Details(itemId = 42))
```
### Don't: Create NavController in ViewModel
```kotlin
// ❌ Anti-pattern
class MyViewModel : ViewModel() {
val navController = NavController(context) // Wrong!
}
// ✅ Correct
// NavController lives in NavHost, injected into composables
```
### Don't: Navigate in composition
```kotlin
// ❌ Anti-pattern
@Composable
fun MyScreen() {
if (condition) {
navController.navigate(Details()) // Navigates on every recomposition!
}
}
// ✅ Correct
@Composable
fun MyScreen() {
LaunchedEffect(condition) {
if (condition) {
navController.navigate(Details())
}
}
}
```
### Don't: Mix navigation approaches
```kotlin
// ❌ Anti-pattern
navigation<Feature>(startDestination = "home") {
composable("home") { } // String-based
composable<Details> { } // Type-safe mixed with strings
}
// ✅ Correct
@Serializable
object FeatureHome
navigation<FeatureRoot>(startDestination = FeatureHome()) {
composable<FeatureHome> { }
composable<FeatureDetails> { }
}
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |