androidkotlinnavigation

Difference between navigateUp() and popBackStack()


I'm creating a simple ToDo app and checking about the Navigation methods to return to my mainFragment from the AddTask Fragment. And I found that I can return using navigateUp() and also popBackStack(), but I don't understand the difference.

When I use this:

Navigation.findNavController(it).navigateUp()

Or this:

Navigation.findNavController(it).popBackStack()

I return to the mainFragment and I think, the addTaskFragment is popped from the stack, so could someone please explain me?


Solution

  • Sorry, the (edit: previously) accepted answer is absolutely wrong, navigateUp() will also pop the top fragment from the backstack, if there is any.

    For starters: If you arrived at your current destination from within your app, they act exactly identical.

    ONLY if you arrived at the current destination with a deeplink from a different app, they will behave differently:

    navigateUp() will leave your app and return to the app that navigated to the deep link in your app.

    popBackStack() will attempt to go back one step in your backstack, and will not do anything if there is no backstack entry.

    You can read up on the differences on: https://developer.android.com/reference/androidx/navigation/NavController#navigateUp()

    navigateUp() Attempts to navigate up in the navigation hierarchy. Suitable for when the user presses the "Up" button marked with a left (or start)-facing arrow in the upper left (or starting) corner of the app UI.

    The intended behavior of Up differs from Back when the user did not reach the current destination from the application's own task. e.g. if the user is viewing a document or link in the current app in an activity hosted on another app's task where the user clicked the link. In this case the current activity (determined by the context used to create this NavController) will be finished and the user will be taken to an appropriate destination in this app on its own task.

    and

    popBackStack() Attempts to pop the controller's back stack. Analogous to when the user presses the system Back button when the associated navigation host has focus.