我遇到一个问题,从 showDialog() 调用 Navigator.pop() 两次会导致空白屏幕。我正在使用 auto_router 包。我该如何解决这个问题?
PopScope 小部件
PopScope(
canPop: false,
onPopInvoked: (didPop) {
log('on click back button ${MainApp.router.stack.toList()}');
log('didPop: $didPop');
if (didPop) {
log('after pop ${MainApp.router.stack.toList()}');
return;
}
_showBackDialog();
},
显示对话框功能
void _showBackDialog() {
showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
alignment: Alignment.bottomCenter,
title: const Text('Are you sure?'),
content: const Text(
'Are you sure you want to leave this page?',
),
actions: <Widget>[
TextButton(
style: TextButton.styleFrom(
textStyle: Theme.of(context).textTheme.labelLarge,
),
child: const Text('Nevermind'),
onPressed: () {
Navigator.pop(context);
},
),
TextButton(
style: TextButton.styleFrom(
textStyle: Theme.of(context).textTheme.labelLarge,
),
child: const Text('Leave'),
onPressed: () async {
Navigator.pop(context);
Navigator.pop(context);
},
),
],
);
},
);
}
即使堆栈路由为空,路由也会不断弹出而不是退出应用程序。
嗯,而不是使用
Navigator.pop(context)
两次,我更喜欢你在 flutter 中使用 popUntil,这样它就会弹出,直到达到你想要的预期状态/屏幕,因为如果你需要它弹出几次,使用 Navigator.pop(context)
不会很好。这是 popUntil 的示例及其文档
static void popUntil(BuildContext context, RoutePredicate predicate) {
Navigator.of(context).popUntil(predicate);
}