So i’m trying to use the “dialog” feature on the n...
# compose
m
So i’m trying to use the “dialog” feature on the navigation component. I’ve got things working mostly as i want, except for the handling of the back button. The back button should basically dismiss the dialog, which it does. However, i also want to run some code to insert a log statement when that happens. You can do this with the normal “Dialog” composable, via the
onDismissRequest
parameter. However, that seems to be missing from the navComponent.
i
There's really two separate layers to consider: 1. The layer that owns the creation and dismissal of the
Dialog
2. The content that is hosted within the
Dialog
In the Navigation world, that first layer is what the
NavHost
is doing for you. Callbacks for when a destination is shown / popped should be looking at the NavController's state as the source of truth i.e.,
Copy code
val navController = rememberNavController()
val currentBackStackEntry by navController.currentBackStackEntryAsState()
if (currentBackStackEntry != null) {
  LaunchedEffect(logger, currentBackStackEntry) {
    // Log whenever the current destination changes
    logger.logCurrentScreen(currentBackStackEntry.destination.route)
  }
}
For the second case where you are providing the content of a
Dialog
,
AnimatedContent
, etc., you'd generally use a
DisposableEffect
and specifically its
onDispose
to tell when that content goes out of scope - i.e., your dialog is no longer visible.
Copy code
dialog("dialogRoute") { backStackEntry ->
  // This is the content within the Dialog
  DisposableEffect(logger) {
    logger.logScreenVisible(backStackEntry.destination.route)
    onDispose {
      logger.logScreenDismised(backStackEntry.destination.route)
    }
  }
}