kotlinandroid-jetpack-composeandroid-jetpack-navigationonbackpressed

How to navigate back to the correct one screen before the previous in jetpack compose?


I have four compose screens and by clicking on their items user leads to my AdShowScreen then after watching the ad they lead to the FinalShow screen. like the image below enter image description here

Now I want to navigate correctly back from finalShowScreen to one of the four compose screens that came from by overriding the back press button in FinalShowScreen. This is my navGraph.

@SuppressLint("UnrememberedMutableState")
@Composable
fun MyNavGraph(

navController: NavHostController) {
val actions = remember(navController) { MainActions(navController) }

NavHost(
    navController = navController,
    startDestination = BottomNavItems.First.route
 ) {
    composable(BottomNavItems.First.route) {
        FirstScreen(actions)
    }
    composable(BottomNavItems.Second.route) {
        SecondScreen(navController, actions)
    }
    composable(BottomNavItems.Third.route) {
        ThirdScreen()
    }
    composable(Screens.Fourth.route) {
        FourthScreen(navController, actions)
    }
         
    composable("${Screens.FinalShow.route}/{maskArg}") {
        val maskArg = it.arguments?.getString("maskArg")
        if (maskArg != null) {
            FinalShowScreen(
                maskArg = maskArg, navController,actions
            )
        }
    }
    
    
    composable("${Screens.RewardedShow.route}/{maskArg}") {
        val maskArg = it.arguments?.getString("maskArg")
        if (maskArg != null) {
            RewardedShowCompose(
                maskArg = maskArg, navController = navController, actions = actions
            )
        }
      }
   }
}

class MainActions(navController: NavController) {
val goToRoute: (String) -> Unit = { route ->
    navController.navigate(route) {
        navController.graph.startDestinationRoute?.let { rout ->
            popUpTo(rout) {
                saveState = true
            }
        }
        launchSingleTop = true
        restoreState = true
    }
  }
 
}

I'm trying this code below but It doesn't work. it goes back to AdShowScreen

 val gotoAdShow: (String, String) -> Unit = { maskArg, route ->
    navController.navigate("$route/$maskArg") {
        navController.graph.startDestinationRoute?.let { rout ->
            popUpTo(rout) {
                saveState = true
                inclusive = true
            }
        }
        launchSingleTop = true
        restoreState = true
    }
}

Solution

  • Why are you using

    navController.navigate(route) {
        navController.graph.startDestinationRoute?.let { rout ->
            popUpTo(rout) {
                saveState = true
            }
        }
        launchSingleTop = true
        restoreState = true
    }
    

    What if instead you use navHostController.popBackStack("ad", inclusive = true) directly?