Leave a rating/review
To start navigating, you need to create a navhost. This is a container that holds the navigation graph and the current destination.
You can create a navhost using the NavHost composable.
Inside your navigation package, create a new file named AppNavHost.kt. Add the following code to the file:
@Composable
fun AppNavHost() {
}
Here, you’re creating a composable function named AppNavHost. This function will be used to create the navhost for your app. Inside the function, create a navController using the function:
val navController = rememberNavController()
This function creates a NavController using rememberNavController() and remembers it across compositions. The navController is the controller that manages the navigation graph and the current destination.
Next, create a NavHost composable and pass the navController and the startDestination as parameters. Add the following code to the AppNavHost composable:
NavHost(
navController = navController,
startDestination = Screens.TaskListScreen.route
) {
}
In the above code, you use the NavHost composable from the navigation library. It provides a place in the Compose hierarchy for self-contained navigation to occur.
The startDestination is the first destination that the user sees when the app starts. In this case, the startDestination is the TaskListScreen.
There’s a Todo to add screens which you’ll tackle in a moment.
Inside the NavHost Composable lambda, add the following code:
composable(Screens.TaskListScreen.route) {
TaskListScreen()
}
In this code, you’re adding the TaskListScreen to the NavHost composable. composable is a composable function that takes a route and a composable function as parameters. The route is the route to the screen. The composable function is the composable function that represents the screen.
Your graph is ready for use.
Next, open MainActivity. You need to replace the call to TaskListScreen inside MainActivity with the AppNavHost composable. Your final result should look like this:
ListMakerScriptTheme {
AppNavHost()
}
Build and run the app. You should see the TaskListScreen as the first screen when the app starts. No functionality has changed, but you’ve set up the navigation graph for your app.
Remember to remove the Preview from this file since you are longer calling TaskListScreen directly and are rather using the navigation graph.