[Jetpack Compose] popUpTo 的一些理解

开发应用时遇到一个需求:无论处于哪个页面,按返回键时都弹出退出应用的提示。
我用了 BackHandler 处理返回事件,发现只有处于主页时才可触发回调,于是思考应该是导航相关的问题。
翻阅谷歌开发文档,看到了以下内容:

// Pop everything up to the "home" destination off the back stack before
// navigating to the "friendslist" destination
navController.navigate("friendslist") {
    popUpTo("home")
}

// Pop everything up to and including the "home" destination off
// the back stack before navigating to the "friendslist" destination
navController.navigate("friendslist") {
    popUpTo("home") { inclusive = true }
}

// Navigate to the "search” destination only if we’re not already on
// the "search" destination, avoiding multiple copies on the top of the
// back stack
navController.navigate("search") {
    launchSingleTop = true
}

我们来看看第一行注释:

Pop everything up to the "home" destination off the back stack before navigating to the "friendslist" destination

其译文为:在导航到"friendslist"页面之前,把在返回堆栈中所有处于"home"页面之上的项弹出
这句话意思就是,当导航到“friendlist”页面时,此时再按返回键,将返回到“home”页面,无论其中我跳转到其他页面多少次,只要最终我停留在“friendlist”页面,那我返回就一定是返回到“home”页面的。看到这里,我的问题也差不多解决了。
我们再看第7行注释,就可以知道加上inclusive = true就可以清空返回堆栈,那么此时,我再按返回,因为返回堆栈里已经没东西了,我的回调函数就可以成功触发了。

好吧,这个方法并没有解决,也不知道为啥,不过最终我把函数的参数id改成了0,解决了。

posted @ 2022-09-24 17:06  摘叶飞镖  阅读(231)  评论(0编辑  收藏  举报