Mohammad Derakhshan
Mohammad Derakhshan

Reputation: 1572

How to prevent multiple creation of a screen in jetpack compose navigation

I have a welcome screen containing two buttons:Login and Sign Up. Hence I have a screen for each one: login screen and sign up screen.

Both of them are in the same NavGraphBuilder. Users can navigate from sign up screen to login screen and vice versa.

At the moment, when the user is on the login screen and clicks on the signUp screen, the screen is added to backQueue even though it already exists.

I try to prevent new destination recreation by applying singleTop like this:

navController.navigate(AuthenticationNavGraph.SignInScreen.route) {
   this.launchSingleTop = true
}

But no progress. So how can I prevent new screen recreation if the screen already exists on backQueue?

Upvotes: 4

Views: 2198

Answers (2)

primo
primo

Reputation: 1472

Try this

I am imagining, login screen is your first screen.

While navigating from signup screen back to login screen

navController.navigateUp()

While navigating from login screen to signup screen

navController.navigate(AuthenticationNavGraph.SignInScreen.route)

It will simply navigate your graph one step up and will prevent creating a new entry of login screen in backstack.

Upvotes: 1

polis
polis

Reputation: 1033

Please try restoreState = true :

     navController.navigate(item.route) {
                        // Pop up to the start destination of the graph to
                        // avoid building up a large stack of destinations
                        // on the back stack as users select items
                        navController.graph.startDestinationRoute?.let { route ->
                            popUpTo(route) {
                                saveState = true
                            }
                        }
                        // Avoid multiple copies of the same destination when
                        // reselecting the same item
                        launchSingleTop = true
                        // Restore state when reselecting a previously selected item
                        restoreState = true
                    }

Upvotes: 3

Related Questions