Ravi Kumar
Ravi Kumar

Reputation: 4508

Passing URL as a parameter to Jetpack Compose Navigation

I have created a destination for HistoryDetail screen in my app.

composable(
    route = "HistoryDetail/{webpage}",
    arguments = listOf(
        navArgument("webpage") {
            type = NavType.StringType
        }
    ),
) { entry ->
    val text = entry.arguments?.getString("webpage") ?: ""
}

When I try to navigate to that screen by calling:

navController.navigate("HistoryDetail/http://alphaone.me/")

I'm getting illegalArgumentException with the below message.

java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/HistoryDetail/http://alphaone.me/ } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0x78c9ba0c) route=Home}

Edit:

It works if I call: navController.navigate("HistoryDetail/test").

Upvotes: 61

Views: 14627

Answers (2)

Phil Dukhov
Phil Dukhov

Reputation: 87605

Navigation routes are equivalent to urls. Generally you're supposed to pass something like id there.

When you need to pass a url inside another url, you need to encode it:

val encodedUrl = URLEncoder.encode("http://alphaone.me/", StandardCharsets.UTF_8.toString())
navController.navigate("HistoryDetail/$encodedUrl")

Note that you don't need to decode the argument on the view side, because Navigation library is gonna do it for you.

Upvotes: 110

uemoo
uemoo

Reputation: 59

How is this?

composable(
    route = "HistoryDetail?webpage={webpage}",
    arguments = listOf(
        navArgument("webpage") {
            type = NavType.StringType
        }
    ),
) { entry ->
    val text = entry.arguments?.getString("webpage") ?: ""
}

Upvotes: 5

Related Questions