popRoute method

  1. @override
Future<bool> popRoute()
override

Called by the Router when the Router.backButtonDispatcher reports that the operating system is requesting that the current route be popped.

The method should return a boolean Future to indicate whether this delegate handles the request. Returning true indicates that the request has been handled and prevents it from bubbling up. Returning false means this delegate did not handle the request, so the request may continue to a parent BackButtonDispatcher in a nested Router setup. If the request reaches the root WidgetsBinding and remains unhandled, the platform is requested to pop the application by calling SystemNavigator.pop.

Consider using a SynchronousFuture if the result can be computed synchronously, so that the Router does not need to wait for the next microtask to schedule a build.

Implementation

@override
Future<bool> popRoute() async {
  final navigatorState = navigatorKey.currentState;
  if (navigatorState == null) {
    return Future.value(false);
  }

  // 顶层存在 pageless 弹层(dialog / bottom sheet 等)或可弹出的页面时,
  // 统一交给 Navigator.maybePop 处理:
  //  - 弹层/页面内部的 PopScope(canPop: false) 与 MaterialPage.canPop 会被尊重;
  //  - page-based 页面的弹出经 onDidRemovePage 与声明式页面栈保持同步。
  // maybePop 对“已弹出”与“被拦截”两种情况均返回 true,这里统一返回 true,
  // 确保返回意图被消费,不会因被拦截而冒泡退出应用;普通弹层与页面的返回
  // 行为保持不变。
  if (_hasPagelessTopRoute() || canPop()) {
    await navigatorState.maybePop();
    return Future.value(true);
  }

  /// 如果页面栈也不能pop,则执行自定义的退出逻辑
  return _exitWindow == null
      ? Future.value(false)
      : _exitWindow!.call(navigatorState.context);
}