Search code examples
kotlinandroid-jetpack-composeandroid-jetpack-navigation

currentBackStackEntry arguments is null when launching the app


In a compose app I'm trying to update the arguments of the currentBackStackEntry. It's just a side project. I do:

navController.currentBackStackEntry?.arguments?.putParcelable(
    "comic",
    selectedComic
)

I know I should probably use room to persist the value and only pass the id and/or use other compose navigation libs (as compose destinations or appyx) instead of passing parcelables this way but I want to keep it simple with compose navigation and without having it serialised in the url.

The problem is that the code doesn't always work and I don't understand why, when it loads the first time as first destination navController.currentBackStackEntry?.arguments is null so the code doesn't work. After navigating to any other composable if I go back to this one and that same code is executed arguments is not null and that code seems to always work.

Any ideas of something I could do so that the arguments are not empty the first time the app is run? I would also really want to understand why this is happening. I've being trying to find out what's happening for several days before asking in here.


Solution

  • The problem is that the code doesn't always work and I don't understand why, when it loads the first time as first destination navController.currentBackStackEntry?.arguments is null so the code doesn't work.

    The documentation for that method states (emphasis mine):

    the topmost entry on the back stack or null if the back stack is empty

    When "it loads the first time as first destination" it's expected that there is no backstack, by definition, so this is completely expected.

    Furthermore, the documenttion for currentBackStackEntry.arguments states:

    Note that the arguments of a NavBackStackEntry are immutable and defined when you navigate() to the destination - changes you make to this Bundle will not be reflected in future calls to this property.

    So it would seem that attempting to put stuff in that Bundle is incorrect anyway.

    Any ideas of something I could do so that the arguments are not empty the first time the app is run?

    I've not used the Nav library myself, but just from reading the docs, maybe currentDestination.arguments is what you want instead?