Migrating to Navigation with Jetpack Compose

Elie Omatuku
3 min readOct 23, 2022

--

Photo by Robert Penaloza on Unsplash

Suppose, that you have done the hard part of migrating all your views to jetpack compose. However, your navigation still relies on the view system navigation and you’d also like to fully migrate to navigating with jetpack compose. Seat tight and bring out the popcorns, this article covers just that.

Navigation with the view system

To illustrate how to migrate from navigation with the view system to navigation with compose, an example of an application with two screens is used, the first screen is made of a button and clicks to the button, send the user to the second screen with a specific text to display. The Below code snippets showcase those screens.

Here is how the application’s navigation graph with the view system, looks like.

Since the application still relies on the navigation with the view system, its composables are wrapped inside fragments, FragmentOne and FragmentTwo.

FragmentOne constructs its view with the composable ScreenOne and set its navigation lambda.

Then inside the FragmentTwo, we retrieve the argument and display it to the composable ScreenTwo.

With the above mixture of composables and navigating with the view system, the application works as below.

Navigation with compose

Now, we would like to move the above code to use navigation with compose. The first step is to add the navigation compose dependency in the project, well detailed here.

Once all the necessary dependencies have been added, we’ll proceed by adding a file with destinations, as shown below.

With the destinations created, we’ll build the navigation graph, we’re going to call it MainNavGraph. The MainNavGraph composable takes in a startDestination, a NavController and a Modifier as parameters.

Once the MainNavGraph is added, we’ll proceed by adding the NavHost composable.

When navigating with compose, we need to pass a list of composables which will form the graph to the NavHost as shown below, the list of composables is equivalent to the list of fragment in the view system.

With the NavHost setup done, let’s add navigation arguments handling. ScreenTwo is meant to receive a String from ScreenOne. We first need to define a list of arguments, and pass it to the arguments parameter provided by the composable element, for our case, it is a String type.

Then we need to add actions to the graph. We define a class called NavigationAction with a NavController as a field and the navigateToScreenTwo method.

Finally, we add an actions variable inside our MainNavGraph and call its navigateToScreenTwo method inside the ScreenOne’s lambda.

And Voilà, here is the application after migrating to navigation with jetpack compose.

If you enjoyed this article, please like and follow. You can also find me on LinkedIn and Github.

--

--