parsePath static method

PathGroup parsePath(
  1. String path
)

Function for parsing a string path to a PathGroup object.

This function is called by the didUpdateWidget function from the AdvanceNavigatorState when generating the DefaultRouteDelegate which uses the created PathGroup objects for matching any incoming path names (e.g. browser url) to a predefined path type from the paths map.

By default, this function will filter out segments enclosed in parentheses {...} as arguments. For example, for /users/{userId}/profile it would return a PathGroup which matches /users/DqHKNnIeZo7NtLfNjn6l/profile or /users/jACSWZyufIEbMFVYUOaN/profile but not users/profile.

This method can be changed externally by setting:

AdvancedNavigator.parsePath = (path) {
  //custom implementation
};

However, in most cases it will make more sense to either adjust the argPattern variable or to define a custom onGeneratePath function as a fallback.

Implementation

static PathGroup parsePath(String path) {
  var args = <int, String>{};
  var uri = Uri.parse(path);
  var pathSegments = List<String>.from(uri.pathSegments);
  var isNested = nestPattern.firstMatch(uri.path) != null;
  if (isNested) pathSegments.removeLast();
  var strPattern = '';
  pathSegments.asMap().forEach((index, pathSegment) {
    // check if segment is argument
    var argName = argPattern.firstMatch(pathSegment)?.group(1);
    if (argName == null) {
      strPattern += RegExp.escape('/$pathSegment');
    } else {
      args[index] = argName;
      strPattern += '/[^/]*';
    }
  });
  if (strPattern.isEmpty) strPattern = '/';
  strPattern = '^' + strPattern;
  if (!isNested) strPattern += r'$';
  var pattern = RegExp(strPattern);
  return PathGroup(pattern,
      length: pathSegments.length, nested: isNested, args: args);
}