Skip to content Skip to sidebar Skip to footer

How To Handle Navigation In Jetpack Compose?

In Jetpack Compose, how is navigation supposed to be done? All (and there aren’t many) examples (including the official sample from Google) use sealed classes and loading new scr

Solution 1:

New Jetpack lib has published for Compose navigation. It is still in alpha.

In this new library, now user can able to navigation between different composables with navigation components features.

Using navigation-compose:

dependencies {
    def nav_compose_version = "1.0.0-alpha01"
    implementation "androidx.navigation:navigation-compose:$nav_compose_version"
}

Example:

Step 1: create a NavController by using the rememberNavController() method in your composable: Link:

valnavController= rememberNavController()

Step 2: Creating the NavHost requires the NavController previously created via rememberNavController() and the route of the starting destination of your graph:Link.

NavHost(navController, startDestination = "profile") {
    composable("profile") { Profile(...) }
    composable("friendslist") { FriendsList(...) }
    ...
}

Step 3: To navigate to a composable use navigate():

funProfile(navController: NavController) {
    ...
    Button(onClick = { navController.navigate("friends") }) {
        Text(text = "Navigate next")
    }
    ...
}

check more https://developer.android.com/jetpack/compose/navigation

Solution 2:

Here is an unofficial approach of navigation in Jetpack Compose. Try it out until you get an official word from the Google android devs.

compose-router

https://github.com/zsoltk/compose-router

Solution 3:

Use androidx.navigation:navigation-compose. See @pRaNaY's answer.

Original Answer

It seems that they are moving away from XML.

The new official samples released after the release of 1.0.0-alpha, have a shared code to manage backstack and navigation. This code is not part of the library yet.

https://github.com/android/compose-samples/blob/master/Owl/app/src/main/java/com/example/owl/ui/utils/Navigation.kthttps://github.com/android/compose-samples/blob/master/Jetsnack/app/src/main/java/com/example/jetsnack/ui/utils/Navigation.kt

Update

Because sample projects are migrated to androidx.navigation:navigation-compose, links are dead. I tried to find the most up to date commits which links are not dead.

https://github.com/android/compose-samples/blob/17b362f0315cf786d3d77d6964ee39b50e311199/Owl/app/src/main/java/com/example/owl/ui/utils/Navigation.kt

https://github.com/android/compose-samples/blob/17b362f0315cf786d3d77d6964ee39b50e311199/Jetsnack/app/src/main/java/com/example/jetsnack/ui/utils/Navigation.kt

Solution 4:

I have writed how to handle Navigation with Jetpack Compose

Link : https://medium.com/@gsaillen95/how-to-handle-navigation-in-jetpack-compose-a9ac47f7f975

Post a Comment for "How To Handle Navigation In Jetpack Compose?"