撰写导航后退按钮未显示

Compose navigation back button is not showing

我正在尝试在此 之后设置导航后退按钮,但无法正常工作。

@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) }
                }
            }
        }
    )
}

谁能帮忙解决这个问题?谢谢!

更改 navController 状态不会使其成为容器重组,这就是 navigationIcon 保持 null.

的原因

要使其重组,您需要使用 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
    }
...