androidkotlinandroid-jetpack-composeandroid-jetpackandroid-jetpack-navigation

Scaffold top bar appears/disappears before the screen content is loaded (Jetpack Compose)


In my activity, I set the content to be a Scaffold to have my custom navhost as it's content, where the navhost controls which composables are shown. I also have a pageName shown in the topbar, but only when the string is not blank.

val pageName by remember { mutableStateOf("") }
val navController = rememberNavController()
Scaffold (
    topBar = {
        if (pageName.isNotBlank()) {
            Row {
                Text(text = pageName)
            }
        }
    }
) {
    MyNavHost(navController, pageName)
}

Essentially, some screens won't have a top bar while other screens will. For the ones that won't, in the navhost I will be setting that composable to set pageName to "" so that it will trigger the scaffold pageName in the activity and update to make the topBar disappear.

The problem is that when we transition from a screen with a topbar and a screen without the top bar (""), there is a slight lag/delay between top bar disappearing/appearing vs the screen content being loaded. The top bar appearing/disappearing happens instantly, while the screen content is still loading for another half-second (note: there are no effects in the navhost).

What can I do to make the top bar appear and disappear with the content of the navhost composables?


Solution

  • You can animate the visibility of the TopBar.

    Scaffold(
        topBar = {
            AnimatedVisibility(visible = pageName.isNotBlank()) {
                Row {
                    Text(text = pageName)
                }
            }
        }
    ) {
        MyNavHost(navController, pageName)
    }