Hi. I am playing around with navigation in compose...
# compose
s
Hi. I am playing around with navigation in compose, but with no known pages. The idea is to have only one route
page/{pageName}
and then use
pageName
to to render the correct data. I mostly wanted to use navigation because of the built in backstack
Copy code
@Composable
fun NavigationTest() {
    val navController = rememberNavController()
    Scaffold(
        bottomBar = { SimpleBottomNav(navController) }
    ) { innerPadding ->
        NavHost(navController, startDestination = "page/{pageName}", Modifier.padding(innerPadding)) {
            composable(
                "page/{pageName}",
                arguments = listOf(navArgument("pageName") { defaultValue = "profile" })
            ) { backStackEntry ->
                val pageName = backStackEntry.arguments?.getString("pageName")
                if (pageName != null) {
                    PageContent(name = pageName)
                } else {
                    Text(text = "No page name")
                }
            }
        }
    }
}
See
SimpleBottomNav
code in the comments. The main issues that I have is that 1.
popUpTo()
does not seem to work properly when the startDestination has an argument in it and 2. the compose context seems to be shared between the different pages. E.g. when i use a LazyList in them, they all share the same scroll state. Did anyone ever have the same issues or has a working example for something similar?
Copy code
@Composable
fun SimpleBottomNav(navController: NavHostController) {
    var selectedRoute by remember { mutableStateOf("profile") }

    BottomNavigation {
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentDestination = navBackStackEntry?.destination
        listOf("profile", "for-you", "settings").forEach { pageName ->
            BottomNavigationItem(
                icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
                label = { Text(pageName) },
                selected = selectedRoute == pageName,
                onClick = {
                    selectedRoute = pageName
                    navController.navigate("page/$pageName") {
                        // TODO popping doesn't seem to work with start page containing an argument
//                        popUpTo(navController.graph.findStartDestination().id) {
//                            saveState = true
//                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                }
            )
        }
    }
}
i
You have to have "known pages". Can you explain why you think you don't know what pages you have?
s
the pages are server driven and dynamic.
pageName
is used inside `PageContent`'s VM to load the data (page names are loaded dynamically too at app start). This works great, but like i mentioned, I am mostly looking for a way to preserve the page state in a backstack when navigating away so it can be restored when navigating back. Navigation has that build in and i was hoping I could use it. I mean, one page is known, i just add an argument to define its data. Are you saying this is not the intended use of navigation?
i
The navigation graph is just code - you can load everything from the server and use that information to construct your graph, but you need each destination to be in your graph
But to support process death and recreation, you need a full graph constructed ahead of time with all possible destinations
That doesn't mean that the logic that moves from screen to screen can't be server driven either
Think of the graph like a map - just because there are 20 cities doesn't mean the routes your user takes have to include all 20
s
Unfortunately I can't define any pages beforehand. It's all the same composable that changes its look according to the data loaded with the pageName. So the navigation graph is only one node with the added parameter
Using navigation for this seems overkill, but it was the only way that i found to add a backstack
i
It's all the same composable that changes its look according to the data loaded with the pageName
That sounds like different composables. Specifically, different composables using a slot based API
Your bottom nav already declares pages up front, so you do know exactly what those destinations should be; just make those three separate destinations
Same for every decision you make: if you have an if check of choosing to show one content or another based on your pageName, those should be two separate destinations
s
right, i have the bottom nav hardcoded in above example, but in reality, they are also loaded dynamically on app start I don't know how many there are nor what pages they show. And yes, the
PageContent
composable plugs together different existing composables, but not in a way that they could be defined as navigation targets. Assume they are completely dynamic - they could contain just one composable, a list, grid or anything else.
i'm sorry, i am probably just doing a really bad job at explaining it...
i
Let's take your bottom nav as an example. You absolutely can have a server provide you a list of bottom nav items, do a for each loop, and add them all to your graph as separate destinations. It is Kotlin code, so you can use any Kotlin control syntax
And if you've done that, I'm not sure why that same technique doesn't apply elsewhere? Your server knows what is valid and not valid
c
FWIW I have a fully server driven app built in prod BUT the nav graph is deterministic, but each "screen" composable is the same. But having a concrete nav graph definitely simplified things. If your nav graph and everything is essentially server driven as well then I think you might be better off just handling navigation/backstack yourself? @ ian in the activity world, you could have multiple activities one on top of another. like. activityA launches activityA, which launches activityA. From what it sounds like you said above, that's not possible with Compose "screen" destinations? If you have destinationA launch destinationA, then you wouldn't have a stack.size=2?
i
Oh, you can absolutely have multiple copies of a single destination in a row (there's even that special flag,
launchSingleTop
, if you want to disable that behavior)
👍 2
But
popUpTo
takes one of the route patterns - i.e., that
page/{pageName}
and
popUpTo
will only pop up to the topmost copy of that destination...not up multiple copies of that destination
👍 1
s
ah i think i am finally understanding what you are saying. tried that real quick with only the bottomNavTabs and it works great. question is, how can i modify the graph later one? I don't know all possible destination at this point. New destination need to be added as the user clicks though the app. Only thing i could imagine is to use a state or a flow that emits am updated list of destinations and then rebuild the whole graph?
FYI this is the updated method
Copy code
@Composable
fun NavigationTest() {
    val navController = rememberNavController()
    Scaffold(
        bottomBar = { SimpleBottomNav(navController) }
    ) { innerPadding ->
        val bottomNavTabs = getServerBottomNavTabs()
        NavHost(
            navController, 
            startDestination = "page/${bottomNavTabs[0]}", 
            Modifier.padding(innerPadding)
        ) {
            bottomNavTabs.forEach { pageName ->
                composable("page/$pageName") {
                    PageContent(name = pageName)
                }
            }
        }
    }
}
thanks for bearing with me on this btw and explaining so patiently. i appreciate it
1
i
You need to get rid of the
page/$pageName
syntax - just use
pageName
as the route:
Copy code
fun NavigationTest() {
    val navController = rememberNavController()
    Scaffold(
        bottomBar = { SimpleBottomNav(navController) }
    ) { innerPadding ->
        val bottomNavTabs = getServerBottomNavTabs()
        NavHost(
            navController, 
            startDestination = bottomNavTabs[0], 
            Modifier.padding(innerPadding)
        ) {
            // Your bottom nav tabs use a fixed route
            bottomNavTabs.forEach { pageName ->
                composable("$pageName") {
                    PageContent(name = pageName)
                }
            }
            // These are your completely dynamic screens that don't have a fixed route
            composable("page/{$pageName}) { backStackEntry ->
                val pageName = backStackEntry.arguments?.getString("pageName")
                if (pageName != null) {
                    PageContent(name = pageName)
                } else {
                    Text(text = "No page name")
                }
            }
        }
    }
}
s
Ah yes definitely. That's just something I played around with. I think i can probably remove them for both, the bottom nav destination as well as the dynamic ones too