I have a Kotlin multiplatform app that calls an API and this API supplies me a URL I want to use this URL to open an in-App Webview but I keep getting this error
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}
Here's my navigation code
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)
}
}
Now the error is indicating that I am going to the wrong route how do I fix this?
So what I learnt was that the '/' in my URL were causing this error because my NavHost saw all the slashes as different routes it needed to get to which is not what I want to do.
So I resolved this by encoding the URL like this
composable("newsList") {
val newsViewModel = getViewModel(Unit, viewModelFactory { NewsViewModel() })
NewsPage(newsViewModel) { news ->
navController.navigate("webview/${UrlEncoderUtil.encode(news.url.orEmpty())}")
}
}
And then I was decoding it just before I passed it into the webview like this
composable("webview/{url}") {
val url = it.arguments?.getString("url") ?: ""
val decodedUrl = UrlEncoderUtil.decode(url)
WebView(decodedUrl, navController)
}
I used this dependency to do Url encoding and decoding
implementation("net.thauvin.erik.urlencoder:urlencoder-lib:1.4.0")