Navigate to another screen without the previous scaffold in Jetpack Compose

Viewed 854

My app has a main screen with a Scaffold and a BottomNavigation bar:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val navController = rememberNavController()
            MyApplicationTheme {
                Scaffold(
                    bottomBar = {
                        BottomBar(navController = navController)
                    }
                ) {
                    NavigationGraph(navController = navController)
                }
            }
        }
    }

...

@Composable
fun NavigationGraph(navController: NavHostController){
    NavHost(navController = navController, startDestination = BottomMenuOption.Home.route) {

        composable(route = BottomMenuOption.Home.route) {
            HomeScreen(navController = navController)
        }

        composable(route = BottomMenuOption.Settings.settings) {
            SettingsScreen()
        }
        composable(route = BottomMenuOption.Profile.route) {
            ProfileScreen()
        }

       composable(route = "feature") {
           FeatureScreen()
       }
    }

}

FeatureScreen has it's own Scaffold with a topBar instead of a bottomBar and when I navigate to it from HomeScreen, I want to replace the previous one from the main screen and just see a topBar but instead, I'm seeing the two bars in the screen.

@Composable
fun FeatureScreen() {
    Scaffold (
        topBar = {
            TopBar(" Feature Screen")
        }
            )  {

    }
}

Is it possible to accomplish this? I'm thinking it could be done by just using a new Activity but ideally, I would like to keep the Single Activity approach.

1 Answers

I would suggest creating a new function like this:

@Composable
fun MainScaffold(
    topBar: @Composable (() -> Unit) = {},
    bottomBar: @Composable (() -> Unit) = {},
    content: @Composable (PaddingValues) -> Unit){
    Scaffold(
        bottomBar = bottomBar,
        topBar = topBar,
        content = content
    )
}

then, use this main scaffold in your screens:

@Composable
fun HomeScreen(navController: NavHostController) {
    MainScaffold(
        bottomBar = { BottomBar(navController = navController) },
        content = {
        // content
     })
}

and in your feature screen:

@Composable
fun FeatureScreen() {
    MainScaffold (
        topBar = {
            TopBar(" Feature Screen")
        }
    )  {
        //content
    }
}

and in setContent

setContent {
       val navController = rememberNavController()
       VoiceAssistantJetpackComposeTheme {
           NavigationGraph(navController = navController)
       }}
Related