Search code examples
androidkotlinandroid-jetpackandroid-jetpack-navigationandroid-jetpack-compose

Can you pass NavHostController to a child Composable in order to allow access to the navController.navigate("Route")?


I am new to Jetpack Compose and am struggling to understand how to integrate the Navigation library with Compose. I have successfully implemented a bottom navigation, but now and struggling to access the .navigate("route") method in a child component. Should I be passing in the navController as a param from the composeable inside the NavHost? Here is my code to make things more clear.

Here is my HomeScreen.kt @Composable which invokes the rememberNavController() method as well as the NavHost() composable as follows...

@Composable
fun HomeScreen() {
val navController = rememberNavController()
...
Scaffold(
   ...
) {
    NavHost(navController, startDestination = "route") {
        composable("route") { Settings(navController) }
  } 
}

So here you can see i'm passing the navController as a param to the Settings composable. I'm not sure if this is correct. Now, ultimately from within the Settings composable i'd like to access the navController.navigate("route") method if possible, similar to the following.

@Composable
fun Settings(navController: NavHostController) {
   ...
   Button(onClick = {navController.navigate("route")}) {
        Text(text = "button text")
    }
   ...
}

Unfortunately I cannot access the .navigate method as it says "None of the following functions can be called with the arguments supplied." Thanks for the time and help!!


Solution

  • The navigate("route") method is an extension method. Therefore you must explicitly import it:

    import androidx.navigation.compose.navigate