I want to have two versions of nav_graph
in two build variant so and the first variant will use the main
nav_graph
and the second variant will add some more destinations to the main nav_graph
so this makes the second graph duplicate of the main nav_graph
but with more destinations which is hard to manage and keep update both at the same time so to solve this i go for dynamic navigation by creating a navigation graph by code which works fine but when i want to add a nested graph for second build variant destinations to the MainGraph
it's not working
this file is in the main code base
MainGraph
object MainGraph{
var id_counter = 1
private val id = id_counter++
object Destinations {
val mainFragment = id_counter++
// ...
}
object Actions {
// ...
val to_settingsFragment = id_counter++
}
fun setGraph(context: Context, navController: NavController) {
navController.graph = navController.createGraph(id, Destinations.mainFragment) {
fragment<MainFragment>(Destinations.mainFragment) {
label = context.getString(R.string.app_name)
// ...
action(Actions.to_settingsFragment) {
destinationId = Destinations.settingsFragment
}
}
// ...
fragment<SettingsFragment>(Destinations.settingsFragment) {
label = context.getString(R.string.settings)
}
}
}
}
this file only in the second build variant
NestedGraph
object NestedGraph {
val id = MainGraph.id_counter++
object Destinations {
val nestedFirstFragment = MainGraph.id_counter++
val nestedSecondFragment = MainGraph.id_counter++
}
object Actions {
val to_nestedSecondFragment = MainGraph.id_counter++
}
fun addDestinations(navController: NavController) {
val navGraph = navController.createGraph(
[email protected],
Destinations.nestedFirstFragment
) {
fragment<NestedFirstFragment>(Destinations.nestedFirstFragment) {
action(Actions.to_nestedSecondFragment) {
destinationId = Destinations.nestedSecondFragment
}
}
fragment<NestedSecondFragment>(Destinations.nestedSecondFragment)
}
navController.graph.addAll(navGraph) // not working
}
}
After some debugging and try n fail i found that there is not wrong with NavGraph.addAll() method its working find it's just my mistake i was using the nested graph id instead of destination id when calling navigate
and if anyone in future also get this kind of behaviour just make sure make the id
variable private