androidandroid-jetpack-composematerial-designmaterial3

TopAppBar has unknown padding when using nested Scaffold with Compose Navigation


I have a Scaffold at the root level of app where I host the navigation. This scaffold doesn't have a top app bar and only contains a FAB. Then, in one of the destinations, I am using another Scaffold which does have a top app bar.

Now, when go to that destination the top app bar is having some unknown/extra padding on top. I didn't specify any extra padding to it using Modifier. The following screenshot shows it:

Screenshot of destination with problem

As you can see above Medicines, we have some extra padding which is unexpected. How can I solve this problem? Does it have anything to do with nested Scaffolds and whether it is recommended to do so or not?


Solution

  • You should make the Scaffold part of each screen instead of having it at the root level. This gives you more control over how each screen looks and behaves. If a screen doesn't need a Scaffold, you can omit it.

    Something similar to this:

    class MainActivity : ComponentActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            enableEdgeToEdge()
            setContent {
                NavLearnTheme {
                    val navController = rememberNavController()
    
                    NavHost(navController = navController, startDestination = "top") {
                        composable("top") { TopScreen( /* ... */ ) }
                        composable("another") { AnotherScreen( /* ... */ ) }
                        // Add more destinations similarly.
                    }
                }
            }
        }
    }
    
    @Composable
    fun TopScreen() {
        Scaffold(
            floatingActionButton = { /* fab code here */ },
            // other content
        ) { innerPadding ->
            // content here
        }
    }
    
    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun AnotherScreen() {
        Scaffold(
            floatingActionButton = { /* fab code here */ },
            topBar = {
                TopAppBar(title = { /*TODO*/ })
            }
            // other content
        ) { innerPadding ->
            // content here
        }
    }