How to exit the app when the user press back button in navigation component?


I’m trying to implement this scenario. I have a sign in screen with a sign in button. When the user clicks the button and gets authenticated, I send the user to the profile screen. The problem comes when the user hits the back button. Instead of existing the app, it goes back to the sign in screen, which is bad. If I have had activities, I have called finish() in the sign in activity when going forward to profile activity, and when the user pressed back, it quits the app. How to do the same thing using navigation?


You need to clear the navigation stack. You can do it in many ways.

For example, if you know that you only have a single item in your back stack, you can use popBackStack:


Or you can use popUpTo and specify the first destination you wanna pop up, and add inclusive parameter:

navController.navigate(Destinations.Profile) {
    popUpTo(Destinations.Login) {
        inclusive = true

Answered By – Phil Dukhov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published