Compose navigation back button is not showing
Asked Answered
S

1

3

I am trying to set up the navigation back button following this SO thread, but can't make it work.

@ExperimentalFoundationApi
@Composable
fun LazyVerticalGridActivityScreen() {
    val navController = rememberNavController()

    val navigationIcon: (@Composable () -> Unit)? =
        if (navController.previousBackStackEntry != null) {
            {
                IconButton(onClick = { navController.popBackStack() }) {
                    Icon(imageVector = Icons.Filled.ArrowBack, contentDescription = null)
                }
            }
        } else {
            null
        }

    Scaffold(
        topBar = {
            TopAppBar(title = { Text("Lazy Vertical Grid") }, navigationIcon = navigationIcon)
        },
        content = {
            NavHost(navController = navController, startDestination = "home") {
                composable("home") { HomeScreen(navController) }
                composable("details/{listId}") { backStackEntry ->
                    backStackEntry.arguments?.getString("listId")
                        ?.let { DetailsScreen(it, navController) }
                }
            }
        }
    )
}

Can anyone please help to fix this? Thanks!

Sheathbill answered 8/8, 2021 at 12:40 Comment(0)
S
7

Changing navController state doesn't make it container recompose, that's why this navigationIcon stays null.

To make it recompose you need to use addOnDestinationChangedListener:

var canPop by remember { mutableStateOf(false) }

DisposableEffect(navController) {
    val listener = NavController.OnDestinationChangedListener { controller, _, _ ->
        canPop = controller.previousBackStackEntry != null
    }
    navController.addOnDestinationChangedListener(listener)
    onDispose {
        navController.removeOnDestinationChangedListener(listener)
    }
}

val navigationIcon: (@Composable () -> Unit)? =
    if (canPop) {
        {
            IconButton(onClick = { navController.popBackStack() }) {
                Icon(imageVector = Icons.Filled.ArrowBack, contentDescription = null)
            }
        }
    } else {
        null
    }
...
Saccharate answered 8/8, 2021 at 12:51 Comment(1)
Perfect! Thanks a lot!! :)Sheathbill

© 2022 - 2024 — McMap. All rights reserved.