applyTopLegacyRedirect method

FutureOr<RouteMatchList> applyTopLegacyRedirect(
  1. BuildContext context,
  2. RouteMatchList prevMatchList, {
  3. required List<RouteMatchList> redirectHistory,
})

Applies the legacy top-level redirect to prevMatchList and returns the resulting matches.

Returns prevMatchList when no redirect happens.

Shares redirectHistory with later route-level redirects for proper loop detection.

Recursively re-evaluates the top-level redirect when it produces a new location, so that top-level redirect chains (e.g. //a/b) are fully resolved. Loop detection and redirect limit are enforced via the shared redirectHistory.

Implementation

FutureOr<RouteMatchList> applyTopLegacyRedirect(
  BuildContext context,
  RouteMatchList prevMatchList, {
  required List<RouteMatchList> redirectHistory,
}) {
  final prevLocation = prevMatchList.uri.toString();
  FutureOr<RouteMatchList> done(String? topLocation) {
    if (topLocation != null && topLocation != prevLocation) {
      final RouteMatchList newMatch = _getNewMatches(
        topLocation,
        prevMatchList.uri,
        redirectHistory,
      );
      if (newMatch.isError) {
        return newMatch;
      }
      // Recursively re-evaluate the top-level redirect on the new location.
      return applyTopLegacyRedirect(context, newMatch, redirectHistory: redirectHistory);
    }
    return prevMatchList;
  }

  try {
    final FutureOr<String?> res = _runInRouterZone(() {
      return _routingConfig.value.redirect(context, buildTopLevelGoRouterState(prevMatchList));
    });
    if (res is String?) {
      return done(res);
    }
    return res.then<RouteMatchList>(done).catchError((Object error) {
      final GoException goException = error is GoException
          ? error
          : GoException('Exception during redirect: $error');
      return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra);
    });
  } catch (exception) {
    final GoException goException = exception is GoException
        ? exception
        : GoException('Exception during redirect: $exception');
    return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra);
  }
}