Alex
07/17/2024, 10:01 AMNavBackStackEntry
matches one of my Route definitions (the data classes that I have pushed into Jetpack Compose Navigation via navController.navigate(route)
?
For example: I navigated to data class SomeRoute(val parameter: String)
and now I want to return true
if the current NavBackStackEntry
corresponds to SomeRoute("hello")
Stylianos Gakis
07/17/2024, 10:11 AMAlex
07/17/2024, 10:12 AMAlex
07/17/2024, 10:13 AMSomeRoute("a")
and SomeRoute("b")
would both return true
if the entry corresponds to SomeRoute
?Stylianos Gakis
07/17/2024, 10:21 AMAlex
07/17/2024, 10:22 AMAlex
07/17/2024, 10:23 AMhasRoute
with all possible routes, hardcoded since I need to provide the type I guess?Stylianos Gakis
07/17/2024, 10:23 AMAlex
07/17/2024, 10:24 AMStylianos Gakis
07/17/2024, 10:25 AMAlex
07/17/2024, 10:25 AMAlex
07/17/2024, 10:26 AMAlex
07/17/2024, 10:26 AMAlex
07/17/2024, 10:27 AMStylianos Gakis
07/17/2024, 10:28 AMval backStackEntry = this
if (backStackEntry.hasRoute<MyDataClass>()) {
val route = backStackEntry.toRoute<MyDataClass>()
if (route == someExpectedInstanceOfMyDataClass) return true
// or
if (route.someField == "a") return true
}
return false
Something like this?Alex
07/17/2024, 12:04 PMStylianos Gakis
07/17/2024, 12:07 PMAlex
07/17/2024, 12:09 PMStylianos Gakis
07/17/2024, 12:22 PMAlex
07/17/2024, 1:04 PMStylianos Gakis
07/17/2024, 2:04 PMfun main() {
val navBackStackEntry: NavBackStackEntry = ...
val didMatch = navBackStackEntry.matchesDestination(MyDestination("123"))
}
private inline fun <reified T : Any> NavBackStackEntry.matchesDestination(expectedInstance: T): Boolean {
if (!this.destination.hasRoute<T>()) {
return false
}
val route = this.toRoute<T>()
return route == expectedInstance
}
But I didn't run or write this in the IDE so not sure how it behaves, but it's what I had in mind at least.
What did you write which was getting too many matches?