DEV Community

Douglas Fornaro
Douglas Fornaro

Posted on

How to proper pop the Login flow from the back stack using Navigation Component

After a login flow, for example, you should pop all of the login-related destinations off of the back stack so that the back button doesn’t take the users back into the login flow again.

Let's see the example below where the startDestination is the loginFragment, which is possible to navigate to the createAccountFragment or directly to the feedFragment. Once the user access the Feed screen (from the Login or the Create Account screen) the app should pop all the login-related destinations from the back stack so the user can close the app from the Feed as expected.

Navigation graph

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/app_navigation"
    app:startDestination="@id/loginFragment">

    <fragment
        android:id="@+id/loginFragment"
        android:name="br.com.fornaro.app.features.login.LoginFragment"
        android:label="fragment_login"
        tools:layout="@layout/fragment_login">
        <action
            android:id="@+id/createAccountFragment"
            app:destination="@id/createAccountFragment" />
        <action
            android:id="@+id/feedFragment"
            app:destination="@id/feedFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true" />
    </fragment>

    <fragment
        android:id="@+id/createAccountFragment"
        android:name="br.com.fornaro.app.features.createaccount.CreateAccountFragment"
        android:label="fragment_create_account"
        tools:layout="@layout/fragment_create_account">
        <action
            android:id="@+id/feedFragment"
            app:destination="@id/feedFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true" />
    </fragment>

    <fragment
        android:id="@+id/feedFragment"
        android:name="br.com.fornaro.app.features.feed.FeedFragment"
        android:label="FeedFragment" />
</navigation>
Enter fullscreen mode Exit fullscreen mode

The code that is responsible for this is the popUpTo and the popUpToInclusive in the action tag.

The popUpTo should be the destination where the current destination (which is indicated in the action) will return when the user leaves from.

The popUpInclusive indicates that the destination from popUpTo will also be removed from the back stack.

For the code above, the loginFragment and createAccountFragment use the same action to navigate to the feedFragment. This way it doesn't matter if the user navigates to the Feed screen from the Login or from the Create Account screen, when the user backs from the Feed the behavior will be the same (removing Login and Create Account from the back stack).

Top comments (0)