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 routes (dialogs, bottom sheets, etc.) should still be dismissed
  // imperatively. Page-based routes must stay in sync with our declarative
  // stack to avoid transient reinsertions during system back gestures.
  if (_hasPagelessTopRoute()) {
    navigatorState.pop();
    return Future.value(true);
  }

  // 如果不行,则尝试从我们自己的页面栈中pop一个页面
  if (canPop()) {
    _popAndOnResult(null);
    notify();
    return Future.value(true);
  }

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