简体   繁体   中英

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 :

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

For creating viewModel instance every time when composable is started you need do this:

val viewModel= remember { MyViewModel() }

That's it. No need in popBackStack and etc.

But i recommend you to found way to listen changes of data in your viewModel.

That will be more clear. JetPack Compose gives you another way how to write code and make Android application, so use it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM