RootSegment<T> constructor

RootSegment<T>(
  1. {RouteBuilder<T>? create,
  2. required RouteBuilder<T> createError,
  3. List<Segment<T>> children = const [],
  4. List<SegmentVerifier<T>> verifiers = const [findConflictingParamKeys]}
)

Creates a RootSegment

As the name implies, this should always be the root node of your route tree.

Note that the constructor of RootSegment calls RootSegment.verify in its body. If you don't want that you have to manually pass an empty list to verifiers.

Use RootSegment.route to to the actual routing.

Note that Segments with LiteralParsers (in this library Segment.path which forwards to PathSegment()) are always looked up before any other Segments, regardless of the order in which they have been defined.

Internally Segment has two kinds of children, a Map<String, Segment<T>> of literal children and a List<Segment<T>> of non literal children, determined by whether a child has a LiteralParser which is usually only the case for Segment.path (which forwards to PathSegment). When routing the implementation first looks up the current path segment in the literal children, which is a O(1) operation. Only when no literal match was found does it linearly try the remaining children with an average complexity of O(n/2) for n non literal children.

For example:

final router = Segment.root<String>(
  create: (context) => 'rootRoute',
  createError: (context) => 'rootError',
  children: [
    Segment.regexPath(
      parser: RegExpParser(RegExp(r'.*')),
      create: (context) => 'regexRoute',
    ),
    Segment.path(
      name: 'user',
      create: (context) => 'userRoute',
    )
  ]
);

assert(router.route(Uri.parse('https://api.com/user')) == 'userRoute');

Implementation

RootSegment({
  RouteBuilder<T>? create,
  required this.createError,
  List<Segment<T>> children = const [],
  this.verifiers = const [findConflictingParamKeys],
}) : super(const LiteralParser('/'), create, createError, children) {
  assert(() {
    final result = verify();
    result.mapErr((errors) => throw ValidationError(errors));
    return true;
  }());
}