goroute 实现GetOffNameUntil offAllName

// 新增两个小工具

  /// 把 RouteMatchList 变成完整路径列表

  static List<String> _currentPaths(BuildContext context) {

    final matches = GoRouter.of(context).routerDelegate.currentConfiguration;

    return matches.matches

        .map((m) => m.matchedLocation)

        .where((loc) => loc != '/') // 去掉根 "/" 占位

        .toList();

  }

  /// 安全地连续 pop

  static void _popTimes(BuildContext context, int times) {

    for (var i = 0; i < times; i++) {

      if (!GoRouter.of(context).canPop()) break;

      if (!context.mounted) return;

      GoRouter.of(context).pop();

    }

  }


  /// 一直返回,直到栈顶路径 == targetRoute

  static Future<T?> goUntil<T extends Object?>(

    String targetRoute, {

    Map<String, dynamic>? parameters,

  }) async {

    final context = validateContext();

    final router = GoRouter.of(context);

    // 当前路由栈

    final paths = _currentPaths(context);

    // 找到目标索引

    final index = paths.lastIndexWhere((p) => p == targetRoute);

    if (index == -1) {

        UNITIRoute.go('/', parameters: parameters);

      return null;

    }

    // 需要 pop 的次数

    final popCount = paths.length - 1 - index;

    _popTimes(context, popCount);

    return null;

  }

  /// 跳转到 newRoute,并移除从栈顶到 targetRoute 之后的所有页面

  static Future<T?> goOffNamedUntil<T extends Object?>(

    String newRoute,

    String targetRoute, {

    Map<String, dynamic>? parameters,

  }) async {

    final context = validateContext();

    final router = GoRouter.of(context);

    // 当前路由栈

    final paths = _currentPaths(context);

    final index = paths.lastIndexWhere((p) => p == targetRoute);

    final popCount = index == -1 ? paths.length : paths.length - 1 - index;

    _popTimes(context, popCount);

    return  UNITIRoute.push(newRoute, parameters: parameters);

  }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容