我有一个调用 API 的 Kotlin 多平台应用程序,该 API 为我提供了一个 URL,我想使用此 URL 打开应用程序内 Web 视图,但我不断收到此错误
kotlin.IllegalArgumentException: Navigation destination that matches route webview/https://tw.news.yahoo.com/%E6%9A%97%E9%BB%91maga-%E9%A6%AC%E6%96%AF%E5%85%8B%E9%A6%96%E5%BA%A6%E7%82%BA%E5%B7%9D%E6%99%AE%E9%80%A0%E5%8B%A2%E5%A4%A7%E6%9C%83%E7%AB%99%E5%8F%B0-043559839.html cannot be found in the navigation graph ComposeNavGraph startDestination={Destination route=newsList}
这是我的导航代码
NavHost(navController, startDestination = "newsList") {
composable("newsList") {
val newsViewModel = getViewModel(Unit, viewModelFactory { NewsViewModel() })
NewsPage(newsViewModel) { news ->
navController.navigate("webview/${news.url.orEmpty()}")
}
}
composable("webview/{url}") {
val url = it.arguments?.getString("url") ?: ""
WebView(url, navController)
}
}
现在错误表明我走错了路线,我该如何解决这个问题?
所以我了解到,我的 URL 中的“/”导致了此错误,因为我的 NavHost 将所有斜杠视为需要到达的不同路线,这不是我想要做的。
所以我通过像这样编码 URL 来解决这个问题
composable("newsList") {
val newsViewModel = getViewModel(Unit, viewModelFactory { NewsViewModel() })
NewsPage(newsViewModel) { news ->
navController.navigate("webview/${UrlEncoderUtil.encode(news.url.orEmpty())}")
}
}
然后我在将它传递到网络视图之前对其进行解码
composable("webview/{url}") {
val url = it.arguments?.getString("url") ?: ""
val decodedUrl = UrlEncoderUtil.decode(url)
WebView(decodedUrl, navController)
}
我用这个依赖来做Url编码和解码
implementation("net.thauvin.erik.urlencoder:urlencoder-lib:1.4.0")