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
s

Simon Stahl

06/09/2022, 1:59 AM
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
@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?
@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

Ian Lake

06/09/2022, 2:11 AM
You have to have "known pages". Can you explain why you think you don't know what pages you have?
s

Simon Stahl

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

Ian Lake

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

Simon Stahl

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

Ian Lake

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

Simon Stahl

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

Ian Lake

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

Colton Idle

06/09/2022, 4:36 AM
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

Ian Lake

06/09/2022, 4:40 AM
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

Simon Stahl

06/09/2022, 5:12 AM
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
@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

Ian Lake

06/10/2022, 10:03 PM
You need to get rid of the
page/$pageName
syntax - just use
pageName
as the route:
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

Simon Stahl

06/10/2022, 11:22 PM
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