Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-navigationjetpack-compose-accompanist

How to keep bottom sheet in backstack when navigating forward?


I am using Accompanist Bottom Sheet Destinations in my project. The setup is exactly the same as shown in docs.

@Composable
fun MyApp() {
    val bottomSheetNavigator = rememberBottomSheetNavigator()
    val navController = rememberNavController(bottomSheetNavigator)
    ModalBottomSheetLayout(bottomSheetNavigator) {
        NavHost(navController, Destinations.Home) {
           composable(route = "home") {
               HomeScreen(
                   openBottomSheet = { navController.navigate("sheet")  }
               )
           }
           bottomSheet(route = "sheet") {
               MyBottonSheet(
                   navigateToSomeRoute = { navController.navigate("some_route") }
               )
           }
           composable(route = "some_route") {
               SomeComposable(
                   onBackPress = { navController.navigateUp() }
               )
           }
        }
    }
}

Here I have a button in MyBottomSheet which opens the SomeComposable screen. But when I navigateUp from there, I reach HomeScreen i.e. the bottom sheet was popped off the backstack when I navigated away from it. How can I keep my bottom sheet in the backstack so that when I press Back in SomeComposable I go back to the previous state with MyBottonSheet open (on top of HomeScreen)?


Solution

  • This is not possible. As per the Navigation and the back stack documentation:

    Dialog destinations implement the FloatingWindow interface, indicating that they overlay other destinations on the back stack. As such, one or more FloatingWindow destinations can be present only on the top of the navigation back stack. Navigating to a destination that does not implement FloatingWindow automatically pops all FloatingWindow destinations off of the top of the stack. This ensures that the current destination is always fully visible above other destinations on the back stack.

    Bottom sheet destinations are also FloatingWindow destinations that float above the other destinations. As such, it is expected that they are automatically popped off the back stack when you navigate to anything other than another dialog or bottomSheet destination.