我遇到了一个问题,从 showDialog() 调用 Navigator.pop() 两次会导致空白屏幕

问题描述 投票:0回答:1

我遇到一个问题,从 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);
              },
            ),
          ],
        );
      },
    );
  }

流行之前 before pop

流行之后 after pop

即使堆栈路由为空,路由也会不断弹出而不是退出应用程序。

flutter auto-route
1个回答
0
投票

嗯,而不是使用

Navigator.pop(context)
两次,我更喜欢你在 flutter 中使用 popUntil,这样它就会弹出,直到达到你想要的预期状态/屏幕,因为如果你需要它弹出几次,使用
Navigator.pop(context)
不会很好。这是 popUntil 的示例及其文档

static void popUntil(BuildContext context, RoutePredicate predicate) {
  Navigator.of(context).popUntil(predicate);
}

popUntil 的文档

© www.soinside.com 2019 - 2024. All rights reserved.