Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 screens in reaction to observing the change in the current screen. This does (sort of) work, but provides no navigation backstack, and the phone’s back button is totally unaware, just closes the app instead of going back to the previous screen. Is this supposed to somehow converge with the navigation component from AndroidX - but it’s XML based, and Compose is all about moving away from XML? Or is there a brand new navigation concept coming, perhaps similar to SwiftUI (navigationlink, etc)? This seems to be one of the biggest roadblocks - as without navigation you can only have a toy app. Anyone aware of the roadmap here?

like image 848
Dmitri Avatar asked Jan 07 '20 01:01

Dmitri


2 Answers

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:

val navController = 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():

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

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

like image 69
pRaNaY Avatar answered Sep 19 '22 05:09

pRaNaY


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

like image 22
sagar suri Avatar answered Sep 21 '22 05:09

sagar suri