Kotlin Multiplatform Development Help

Navigation and routing

Navigation is a key part of UI applications that allows users to move between different application screens. Compose Multiplatform adopts the Jetpack Compose approach to navigation.

Setup

To use the navigation library, add the following dependency to your commonMain source set:

kotlin { // ... sourceSets { // ... commonMain.dependencies { // ... implementation("org.jetbrains.androidx.navigation:navigation-compose:2.8.0-alpha10") } // ... } }

Type-safe navigation

Starting with 1.7.0, Compose Multiplatform supports type-safe navigation in common code as described in the Jetpack documentation.

Sample project

To see the Compose Multiplatform navigation library in action, check out the nav_cupcake project, which was converted from the Navigate between screens with Compose Android codelab.

Just as with Jetpack Compose, to implement navigation, you should:

  1. List routes that should be included in the navigation graph. Each route must be a unique string that defines a path.

  2. Create a NavHostController instance as your main composable property to manage navigation.

  3. Add a NavHost composable to your app:

    1. Choose the starting destination from the list of routes you defined earlier.

    2. Create a navigation graph, either directly, as part of creating a NavHost, or programmatically, using the NavController.createGraph() function.

Each back stack entry (each navigation route included in the graph) implements the LifecycleOwner interface. A switch between different screens of the app makes it change its state from RESUMED to STARTED and back. RESUMED is also described as "settled": navigation is considered finished when the new screen is prepared and active. See the Lifecycle page for details of the current implementation in Compose Multiplatform.

Limitations

Current limitations of navigation in Compose Multiplatform, compared to Jetpack Compose:

Third-party alternatives

If the Compose Multiplatform navigation components do not solve your problems, there are third-party alternatives that you can choose from:

Name

Description

Voyager

A pragmatic approach to navigation

Decompose

An advanced approach to navigation that covers the full lifecycle and any potential dependency injection

Appyx

Model-driven navigation with gesture control

PreCompose

A navigation and view model inspired by Jetpack Lifecycle, ViewModel, LiveData, and Navigation

Circuit

A Compose-driven architecture for Kotlin applications with navigation and advanced state management.

Last modified: 16 October 2024