registerPopGestureCallback method

  1. @override
void registerPopGestureCallback(
  1. VoidCallback callback,
  2. BuildContext context
)
override

注册系统返回手势的回调

当检测到 iOS 左滑返回手势时,会调用栈顶的回调函数。 多个页面可以同时注册回调,只有栈顶(最后注册)的回调会被调用。

参数:

  • context: 注册回调时的 BuildContext,作为回调的唯一标识, 同时用于检查页面是否还在顶层

示例:

PopscopeIos.registerPopGestureCallback(() {
  print('手势触发');
}, context);

// 组件销毁时注销
PopscopeIos.unregisterPopGestureCallback(context);

Implementation

@override
void registerPopGestureCallback(
  VoidCallback callback,
  BuildContext context,
) {
  _ensureHandlerInitialized();

  // 添加断言检查
  assert(
    context.mounted,
    'Cannot register callback with unmounted context. '
    'Make sure to call registerPopGestureCallback in didChangeDependencies() '
    'or after the widget is mounted.',
  );

  // 验证 context 有效性(生产环境也会检查)
  if (!context.mounted) {
    PopscopeLogger.warn(
      'Attempted to register callback with unmounted context: ${context.hashCode}. '
      'Registration ignored.',
    );
    return;
  }

  // 如果已经注册过,先移除旧的
  if (_callbackMap.containsKey(context)) {
    _callbackOrder.remove(context);
    PopscopeLogger.debug(
      'Re-registering callback for context: ${context.hashCode}',
    );
  }

  // 添加到 Map 和顺序列表
  _callbackMap[context] = _CallbackEntry(callback, context);
  _callbackOrder.add(context);

  PopscopeLogger.debug(
    'Callback registered: context=${context.hashCode}, total=${_callbackOrder.length}',
  );

  // 当注册回调时,启用 iOS 端的手势拦截
  _enableIosGestureIfNeeded();
}