Home > front end >  How to exit the app when the user press back button in navigation component?
How to exit the app when the user press back button in navigation component?

Time:11-24

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?

CodePudding user response:

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:

navController.popBackStack()
navController.navigate(Destinations.Profile)

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
    }
}
  • Related