2

我正在尝试在此SO 线程之后设置导航返回按钮,但无法使其工作。

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

任何人都可以帮忙解决这个问题吗?谢谢!

4

1 回答 1

3

更改navController状态不会使其容器重组,这就是它navigationIcon保持不变的原因null

要使其重组,您需要使用addOnDestinationChangedListener

var canPop by remember { mutableStateOf(false) }

navController.addOnDestinationChangedListener { controller, _, _ ->
    canPop = controller.previousBackStackEntry != null
}

val navigationIcon: (@Composable () -> Unit)? =
    if (canPop) {
        {
            IconButton(onClick = { navController.popBackStack() }) {
                Icon(imageVector = Icons.Filled.ArrowBack, contentDescription = null)
            }
        }
    } else {
        null
    }
...
于 2021-08-08T12:51:06.530 回答