0

I have this navigation graph

fun NavGraphBuilder.manageAvailabilityGraph() {
    composable(
        "availability/{id}",
        arguments = listOf(
            navArgument("id") {
                type = NavType.StringType
                nullable = true
            },
        ),
    ) {
        ManageAvailabilityScreen()
    }
}

I thought I can use it for both

navHostController.navigate("availability")
navHostController.navigate("availability/123")

But first one does not work, I get

java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/availability } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0xcfbbf7da) route=home}

I fixed it by providing two different routes.

fun NavGraphBuilder.manageAvailabilityGraph() {
    composable(
        "availability",
    ) {
       ManageAvailabilityScreen()
    }

    composable(
        "availability/{id}",
        arguments = listOf(
            navArgument("id") {
                type = NavType.StringType
                nullable = true
            },
        ),
    ) {
        ManageAvailabilityScreen()
    }
}

However, I want to know is if it is possible to combine both and just have one route with name "availability", so I don't need to repeat "availability"? And eseentially, both use the same screen.

I tried something like this but does not work.

fun NavGraphBuilder.manageAvailabilityGraph() {
    composable(
        "availability",
    ) {

        ManageAvailabilityScreen()

        navigation(startDestination = "{id}", "{id}") {
            composable(
                "{id}",
                arguments = listOf(
                    navArgument("id") {
                        type = NavType.StringType
                    },
                ),
            ) {
                ManageAvailabilityScreen()
            }
        }
    }
}

Arst
  • 3,098
  • 1
  • 35
  • 42

1 Answers1

2

You can mark id as the optional parameter in the route. Refer Documentation

fun NavGraphBuilder.manageAvailabilityGraph() {
    composable(
        "availability?id={id}",
        arguments = listOf(
            navArgument("id") {
                type = NavType.StringType
                nullable = true
            },
        ),
    ) {
        ManageAvailabilityScreen()
    }
}

While navigating you can use,

navHostController.navigate("availability")
navHostController.navigate("availability?id=123")
Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40