Home > OS >  Change the appbar title based on current screen bottom navigation
Change the appbar title based on current screen bottom navigation

Time:07-21

I am trying to change the title of SmallTopAppBar based on what screen you navigate to. I get results printed out. But, when I assign this same result to title a global var it does not display.

var title = ""
LaunchedEffect(navController){
    navController.currentBackStackEntryFlow.collect{backStackEntry ->
        Log.d("App", backStackEntry.destination.route.toString())
        title = backStackEntry.destination.route.toString()
    }
}

Usage:

Scaffold(
        topBar = {
            SmallTopAppBar(
                title = { Text(text = title)

Clarity: The Log.d("App", backStackEntry.destination.route.toString()) does print out results, and it is dynamic coming from the navigation. But, for some unknown reason, this is not updated on the actual UI, what am I missing here.

Troubleshooted: "$title" does not work. I tried setting a title manually, title = { Text(text = "Home") } and this works, but, this isn't dynamic nor changing, stays the same all the time.

EDIT: It's inside a @Composable,

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Main() {
    var title = "Home"

CodePudding user response:

It's because you don't store value of title inside a remember and don't trigger a recomposition when it changes. When it recomposes it composes again with "" string

var title by remember {mutableStateOf("")} will make sure that it will be updated

  • Related