Share composable in nav host

Viewed 34

I have a NavHost which hosts multiple composables from the main screen to the login screen as show below:

@Composable
fun Navigation() {
    val navController = rememberNavController()
    NavHost(
        navController = navController,
        startDestination = Screen.Main.route) {
        composable(route = Screen.Main.route) {
            StatusBar()
            Main()
        }
        composable(route = Screen.Login.route) {
            StatusBar()
            Login()
        }
    }
}

You see how the Status bar is in both Main and Login composables I was just wondering if it would be possible to define it in one place so it can be used across all composables?

1 Answers

To keep your code clean I would recommend using the StatusBar in Main and Login. Because at the end the StatusBar and its state belongs to the screen and not to the NavHost.

The problem is that your screen is the component which owns all the information that the StatusBar needs (even though there are no parameters; this is theoretical representation). So it makes sense that the Screen owns its sate.

The composable of the NavHost on the otherside only knows the curren screen, but none of its state unless you state hoist it in a very ugly way. So it makes sense that it only holds that state it is best in managing.

Because of the fact that you already have put the StatusBar into an composable you also don't have a problem with code duplication.

Related