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-alpha01") } // ... } }

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.

Consider the following implementation aspects:

  • The ViewModel factory allows creating ViewModel entities of the correct type on iOS and web.

  • The ComposeViewModelStoreOwner class implements the ViewModelStoreOwner interface to provide a fallback for platforms other than Android and desktop.

  • Compose Multiplatform string resources are used in place of Jetpack Compose resources.

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

Last modified: 17 April 2024