Site icon

Compose Destinations – Annotation processing library for type-safe Jetpack Compose navigation

A KSP library that processes annotations and generates code that uses Official Jetpack Compose Navigation under the hood. It hides the complex, non-type-safe and boilerplate code you would have to write otherwise.
No need to learn a whole new framework to navigate – most APIs are either the same as with the Jetpack Components or inspired by them.

Compose Destinations Main Features

For a deeper look into all the features, check our documentation website.


Compose Destinations Basic Usage

  1. Annotate your screen Composables with @Destination:
fun ProfileScreen() { /*...*/ }
  1. Add navigation arguments to the function declaration:
fun ProfileScreen(
   id: Int, // <-- required navigation argument
   groupName: String?, // <-- optional navigation argument
   isOwnUser: Boolean = false // <-- optional navigation argument
) { /*...*/ }

ParcelableSerializableEnum and classes annotated with @kotlinx.serialization.Serializable (as well as Arrays and ArrayLists of these) work out of the box! You can also make any other type a navigation argument type. Read about it here

There is an alternative way to define the destination arguments in case you don’t need to use them inside the Composable (as is likely the case when using ViewModel). Read more here.

  1. Build the project (or ./gradlew kspDebugKotlin, which should be faster) to generate all the Destinations. With the above annotated composable, a ProfileScreenDestination file (that we’ll use in step 4) would be generated.

  2. Use the generated [ComposableName]Destination invoke method to navigate to it. It will have the correct typed arguments.

@RootNavGraph(start = true) // sets this as the start destination of the default nav graph
fun HomeScreen(
   navigator: DestinationsNavigator
) {
   navigator.navigate(ProfileScreenDestination(id = 7, groupName = "Kotlin programmers"))

DestinationsNavigator is a wrapper interface to NavController that if declared as a parameter, will be provided for free by the library. NavController can also be provided in the exact same way, but it ties your composables to a specific implementation which will make it harder to test and preview. Read more here

  1. Finally, add the NavHost call:
DestinationsNavHost(navGraph = NavGraphs.root)

NavGraphs is a generated file that describes your navigation graphs and their destinations. By default all destinations will belong to “root” (@RootNavGraph), but you can create your own nav graphs annotations to have certain screens in other navigation graphs.

This call adds all annotated Composable functions as destinations of the Navigation Host.

That’s it! No need to worry about routes, NavType, bundles and strings. All that redundant and error-prone code gets generated for you.

Compose Destinations on GitHub:
Platform: Android
⭐️: 1.2K
Exit mobile version