The navigation component in Jetpack Compose helps you navigate between composables and take advantage of the features it provides.
dependencies {
def nav_compose_version = "1.0.0-alpha02"
implementation "androidx.navigation:navigation-compose:$nav_compose_version"
}
NavController
The NavController
keeps track of the back stack of composables and the state of each one. It is also stateful which means that can directly change or mutate state.
We must create it in the place where composable hierarchy is specified so that all composables that need to reference it can access it.
To create a NavController we can use rememberNavController()
:
@Composable
fun ToDometerApp() {
val navController = rememberNavController()
...
NavHost
The NavController
created must be associated with a NavHost
composable. Inside the NavHost
you specify the composables that you should be able to navigate to. To construct the navigation graph inside the NavHost
we can use the Navigation Kotlin DSL. Using the composable
method we specify the route of destination and the composable related to the destination.
Navigate
To navigate to a destination, we use navigate()
method which takes a String parameter that represents the destination’s route.
navController.navigate("addProject")
To return to the previous composable we simply call popBackStack()
.
Passing arguments between destinations
We can also pass data between destinations by defining placeholders in the composable route, in the same way that we specify path placeholders in a URL.
composable("route/{navArg}")
We can specify the type of argument by passing the NavType
to type
parameter in navArgument
function, because by default all arguments are parsed as strings.
navController.navigate("taskDetail/1")