Hello all. Just getting starting with compose nav...
# compose
b
Hello all. Just getting starting with compose navigation, trying to set my general app structure. I will have some main screens to handle app setup for the user and authentication. Once authenticated I would like to navigate to the home screen, which has a bottom navigation in a scaffold. I am trying to do this with 2 NavHosts, which means I need to nav controllers. Everything works fine from the main screen to the home screen, but upon navigation from home back to main (simulated logout), if I try and go back to the home screen I get
Copy code
ViewModelStore should be set before setGraph call
Code in comments
Copy code
@Composable
fun MainScreen() {
   val mainNavController = rememberNavController()
   val homeNavController = rememberNavController()
   val scaffoldState = rememberScaffoldState()

   NavHost(
      navController = mainNavController,
      startDestination = "main"
   ) {
      composable("main") {
         Box(Modifier.fillMaxSize()) {
            TextButton(
               modifier = Modifier.align(Alignment.Center),
               onClick = { mainNavController.navigate("home") }
            ) {
               Text("Home")
            }
         }
      }

      composable("home") {
         Scaffold(
            scaffoldState = scaffoldState,
            bottomBar = {
               BottomNavigation {
                  val navBackStackEntry by homeNavController.currentBackStackEntryAsState()
                  val currentDestination = navBackStackEntry?.destination

                  BottomNavigationItem(
                     icon = {
                        Icon(
                           Icons.Default.Share,
                           contentDescription = "Tab 1"
                        )
                     },
                     label = { Text("Tab 1") },
                     selected = currentDestination?.hierarchy?.any { it.route == "home/tab1" } == true,
                     onClick = {
                        homeNavController.navigate("home/tab1") {
                           popUpTo(homeNavController.graph.findStartDestination().id) {
                              saveState = true
                           }
                           launchSingleTop = true
                           restoreState = true
                        }
                     }
                  )

                  BottomNavigationItem(
                     icon = {
                        Icon(
                           <http://Icons.Default.Menu|Icons.Default.Menu>,
                           contentDescription = "Tab 2"
                        )
                     },
                     label = { Text("Tab 1") },
                     selected = currentDestination?.hierarchy?.any { it.route == "home/tab2" } == true,
                     onClick = {
                        homeNavController.navigate("home/tab2") {
                           popUpTo(homeNavController.graph.findStartDestination().id) {
                              saveState = true
                           }
                           launchSingleTop = true
                           restoreState = true
                        }
                     }
                  )
               }
            }
         ) {
            NavHost(
               navController = homeNavController,
               startDestination = "home/tab1"
            ) {
               composable("home/tab1") {
                  Box(
                     Modifier
                        .fillMaxSize()) {
                     Column( modifier = Modifier.align(Alignment.Center)) {

                        Text("Tab 1")

                        TextButton(
                           onClick = {
                              mainNavController.navigate("main")
                              homeNavController.navigate("home/tab1")
                           })
                        {
                           Text("Main")
                        }
                     }
                  }
               }
               composable("home/tab2") {
                  Box(
                     modifier = Modifier.fillMaxSize(),
                  ) {
                     Column( modifier = Modifier.align(Alignment.Center)) {

                        Text("Tab 2")

                        TextButton(
                           onClick = {
                              mainNavController.navigate("main")
                           })
                        {
                           Text("Main")
                        }
                     }
                  }
               }
            }
         }
      }
   }
}
c
I think the general feedback if you're using navigation compose is to use a single navHost, with the start destination being the screen that users will land on once they are logged in. When they get to your main screen, you can do a check to show the user/navigate the user to the login screen. Once the login is complete, then you just pop your login screen and the user will see the screen underneath.
here's a case study video on navigation that i thought was helpful. although its not compose specific its the same navigation paradigm. timestamped for convenience:

https://youtu.be/09qjn706ITA?t=288

also theres a section in the arch guide that you might find helpful https://developer.android.com/topic/architecture/ui-layer/events#compose_1
I have an article in my drafts on how to handle "login" screens with compose. I should really publish it. lol
2
i tired to take some of my learnings and just put them into a post. one day when i get some time to clean it up. /shruggie
👍🏼 1
b
Yeah as I do more research I am seeing that. Also seeing a lot of folks using 2 navhosts, which I don’t think is wrong just what most are used to, esp if coming from something like angular navigation. Biggest issue with compose navigation and showing hiding bottombar is the ugly animation between routes that have the bottom navbar and routes that do not. I think accompanist had some things to help with this, but still not trivial.
c
which I don’t think is wrong just what most are used to,
I don't want to relay the wrong information, but I could've sworn Ian has said that that's the wrong thing to do. Maybe he'll chime in here. I have bottom bar enter/exit animated. let me send you a snippet.
Copy code
AnimatedVisibility(
    currentDestination?.hierarchy?.any {
      it.route == Screen.Tab1.route ||
          it.route == Screen.Tab2.route ||
          it.route == Screen.Tab3.route
    } == true,
    enter =
        slideInVertically(
            initialOffsetY = { fullHeight: Int -> fullHeight }, animationSpec = tween(950)) +
            fadeIn(animationSpec = tween(950)),
    exit = fadeOut(animationSpec = tween(650)),
) {
s
i was looking to do some stuff with two nav hosts but it was a little tricky and yeah, it seemed like it wasn't recommeneded. I found this project where they have two nav hosts where one is a bottom bar..maybe it could give you some ideas
b
@Sterling Albury Ha yes, thanks, I found that project and just sent a PR for the logout issue that was submitted. @Colton Idle, yeah maybe “wrong” was the incorrect word, while I don’t think its recommended, it is a solution to the problem that its seems based on SO posts a lot of folks are trying to (pun intended) navigate. Projects like the one above really just rely on some coordination between nav controllers, at this point its a choice between a few lines of code to handle that coordination or a few lines of code to handle bottom bar animation. Probably best to stick with the recommended approach laid out by the compose devs, making it much easier to transition to newer version that might help solve this without any boilerplate code.
c
Yeah. I think if you're going compose nav... it's pretty opinionated anyway and you should stick to the direction in the docs. If you want some other nav then there is no shortage of compose nav libraries that don't bring along the "baggage" of an existing navigation system.
👍 1
b
For me the part that feels weird is to have to define a scaffold which might include a bottom sheet, a drawer and/or a bottom bar at the top level of the entire application. Considering that half of your app might not need those and just hide them, relying on other routes to show them. Would be nice to be able to use a scaffold at lower levels but still hook into the existing navController.
c
I typically will use a scaffold or something else at the top level, and then I will use a scaffold on an "inner" screen if I need. I like the flexibility it gives me. esp when it comes to transitions and animations since the screens are now decoupled from the top level navigation (bottom bar or nav drawer). but overall i def agree that it can sometimes feel "wrong" at first.
i
For me the part that feels weird is to have to define a scaffold which might include a bottom sheet, a drawer and/or a bottom bar at the top level of the entire application. Considering that half of your app might not need those and just hide them, relying on other routes to show them. Would be nice to be able to use a scaffold at lower levels but still hook into the existing navController.
If you want global UI, then putting it at the global level is exactly what you need to do - remember a `NavHost`/`AnimatedNavHost` is just a wrapper around an
AnimatedContent
composable, swapping between screens. You still need to figure out what needs to go inside and outside that level, whether you are using Navigation Compose or not
NavController just gives you a single source of truth for exactly what screen you are on so that you can react to moving from one screen to the other
Like that video shows you, things like deep links, cross linking between destinations, and basically every other bit of logic is going to be way, way easier with a single NavHost
👍 1
But I think once we get shared elements in Compose, what you want to put at the global level vs as part of each screen (i.e., a shared toolbar just between two screens) might have a lot more flexibility - you're basically handicapped right now on what you can do with shared UI
b
Ian, agreed. And I know compose and compose navigation is still in its infancy. I am sure a lot of good things are coming. I appreciate the conversation.
Looking more into
You still need to figure out what needs to go inside and outside that level, whether you are using Navigation Compose or not
Am I correct to assume that you are saying “put the scaffold/bottombar at the level you need it”. This was the intent of my original question, can I use a navhost to navigate to screens that contain a bottom sheet navigation component. I “hacked” in 2 NavHosts and it worked, however I would like to follow best practices.
Copy code
fun MainScreen() {
   val bottomSheetNavigator = rememberBottomSheetNavigator()
   val navController = rememberNavController(bottomSheetNavigator)

   NavHost(
      navController = navController,
      startDestination = "main"
   ) {
      homeGraph(navController, bottomSheetNavigator)
Copy code
fun NavGraphBuilder.homeGraph(
   navController: NavController,
   bottomSheetNavigator: BottomSheetNavigator
) {
   composable("home") {
      val scaffoldState = rememberScaffoldState()

      ModalBottomSheetLayout(bottomSheetNavigator) {
        Scaffold(
            scaffoldState = scaffoldState,
            drawerContent = {...},
            bottomBar = {...}
        ) {
            // Not entirely sure how to setup bottom nav tabs within the scaffold?
        }
      }
  }
}
i
I don't know why you'd ever put a
ModalBottomSheetLayout
within a
composable
destination. That is absolutely something that should exist at the global level (and needs to be if you consider contentPadding, system insets, and everything else that forces a
ModalBottomSheetLayout
to need to be at the topmost level). That will always be the case until the bottom sheet APIs are changed completely
Treating a bottom sheet just like
Dialog
is something being discussed in https://issuetracker.google.com/issues/217840726, which would potentially remove the need to use something like
ModalBottomSheetLayout
at all. I'd definitely +1 that CL is that's something you'd find easier to work with
👍 2
s
the accompanist material nav lib is pretty cool...it has us wrapping the nav host with the ModalBottomSheetLayout, which is i guess what you're referring to with being at the global level?
i
Yep
b
Yeah, sorry I forgot that modal sheet was there. Still trying to figure out if there is a way to have a bottom tab bar at a lower level. Without multiple navhosts I don't think it's possible to use the tabs as routes in a navigation graph unless the bottom tab bar is at the top level. Would be nice if there was a way to nest child graphs as separate components, similar to angular routing.
i
If you want something shared between multiple destinations, it needs to be outside the NavHost, which means at the global level
1
👍 1
In a shared element based world though, you certainly create your own wrapper around
composable
that adds a shared element bottom bar to each composable destination i.e.:
Copy code
fun NavGraphBuilder.bottomNavWrappedComposable(
  navController: NavController,
  // all the normal parameters to composable including the content block:
  content: @Composable (NavBackStackEntry) -> Unit
) = composable(
  // Add in all of the normal parameters
) { entry ->
  // Scaffold uses an expensive SubcomposeLayout, you really just need a Column
  Column {
    // First, display the content in a Box
    Box(modifier = Modifier.weight(1f) {
      content(entry)
    }
    // Then put your BottomNavigationBar, using the same logic as
    // the docs use: <https://developer.android.com/jetpack/compose/navigation#bottom-nav>
    BottomNavigationBar(
      // This would be the secret sauce that would keep the bottom bar in place as
      // other elements transition as you move between screens
      modifier = Modifier.sharedElement("bottomBar")
    ) {
      // your items
    }
  }
}
Essentially, your wrapper provides common UI, using shared elements to keep some elements in place as you move between screens
👍 2
d
@Colton Idle (or @Ian Lake maybe) With that animated visibility, don’t you get a single frame of jitter at least? I was using this
Copy code
Scaffold(
            bottomBar = {
                AnimatedVisibility(
                    visible = showBottomNav,
                    enter = slideInVertically(initialOffsetY = { it }),
                    exit = slideOutVertically(targetOffsetY = { it }),
                ) {
                    bottomBar(destination)
            },
and I was getting a quite visible layout jump whenever you navigate from a screen that has the BottomBar showing to one that doesn’t. I was putting that to the fact that AnimateVisibility doesn’t animate the height but now I’m thinking that’s wrong? Does it work smoothly for you, with the “content” nicely expanding to take the space freed up by the bottom bar?
c
my bottom bar animates smoothly yes. I'm not using a scaffold at the top layer, just a column. idk if that could be an issue since Ian just said above " // Scaffold uses an expensive SubcomposeLayout, you really just need a Column"
d
Thanks, I’ll have a deeper dive at this whenever I get some free time, at least knowing there’s a way to make it work makes me feel better
👍 2
s
https://kotlinlang.slack.com/archives/CJLTWPH7S/p1712495286104259?thread_ts=1668617994.752349&amp;cid=CJLTWPH7S I’ll take the role of the shared element evangelist and let you know that this is now possible 😅
207 Views