https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
b

Billy Newman

06/09/2022, 4:59 PM
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
ViewModelStore should be set before setGraph call
Code in comments
@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

Colton Idle

06/09/2022, 5:37 PM
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

Billy Newman

06/09/2022, 5:40 PM
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

Colton Idle

06/09/2022, 5:49 PM
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.
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

Sterling Albury

06/09/2022, 5:52 PM
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

Billy Newman

06/09/2022, 6:01 PM
@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

Colton Idle

06/09/2022, 6:04 PM
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

Billy Newman

06/09/2022, 6:06 PM
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

Colton Idle

06/09/2022, 6:10 PM
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

Ian Lake

06/09/2022, 6:25 PM
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

Billy Newman

06/09/2022, 6:41 PM
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.
fun MainScreen() {
   val bottomSheetNavigator = rememberBottomSheetNavigator()
   val navController = rememberNavController(bottomSheetNavigator)

   NavHost(
      navController = navController,
      startDestination = "main"
   ) {
      homeGraph(navController, bottomSheetNavigator)
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

Ian Lake

06/10/2022, 2:09 AM
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

Sterling Albury

06/10/2022, 2:16 AM
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

Ian Lake

06/10/2022, 3:04 AM
Yep
b

Billy Newman

06/10/2022, 3:09 AM
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

Ian Lake

06/10/2022, 4:31 AM
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.:
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

dorche

06/10/2022, 11:45 AM
@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
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

Colton Idle

06/10/2022, 11:58 AM
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

dorche

06/10/2022, 12:00 PM
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