Do NOT Make This Navigation Mistake in Jetpack Compose
Grab a coffee ☕, and let me show you what navigation mistake is often encountered in Jetpack Compose.
PROBLEM
Take a look at Screen 1, which has the issue that I am talking about. The second screen is the fixed variant.
When does this happen?
This often happens when the user is on a screen and presses the navigate back button multiple times.
You may think “Who does that?” some people happen to do that, or their phone is laggy so we need to ensure that this won’t happen to them. Also, it is easy to fix this.
UPDATE
You can use navigateUp
method to prevent this behaviour.
FIX
We need to create a variable and a small helper function.
canGoBack
— True when the app lifecycle isRESUMED
. This is when the user can interact with the app again.navigateBack
— UsescanGoBack
andnavController
to navigate back.
val NavHostController.canGoBack: Boolean
get() = this.currentBackStackEntry?.lifecycle?.currentState
== Lifecycle.State.RESUMED
fun NavHostController.navigateBack() {
if (canGoBack) {
popBackStack()
}
}
Now you can call navController.navigateBack()
and the problem is solved!
For the latest updates, follow me and subscribe to the newsletter. If you want to see more content, make sure to follow me on X and subscribe to my YouTube channel! Thanks for reading! 😊☕️