AssetId.resolve constructor

AssetId.resolve(
  1. Uri uri, {
  2. AssetId? from,
})

Creates a new AssetId from an uri String.

This gracefully handles package: or asset: URIs.

Resolve a package: URI when creating an AssetId from an import or export directive pointing to a package's lib directory:

AssetId assetOfDirective(UriReferencedElement element) {
  return new AssetId.resolve(element.uri);
}

When resolving a relative URI with no scheme, specifyg the origin asset (from) - otherwise an ArgumentError will be thrown.

AssetId assetOfDirective(AssetId origin, UriReferencedElement element) {
  return new AssetId.resolve(element.uri, from: origin);
}

asset: uris have the format '$package/$path', including the top level directory.

Implementation

factory AssetId.resolve(Uri uri, {AssetId? from}) {
  var resolved = uri.hasScheme
      ? uri
      : from != null
          ? from.uri.resolveUri(uri)
          : (throw ArgumentError.value(
              from,
              'from',
              'An AssetId "from" must be specified to resolve a relative '
                  'URI'));
  if (resolved.scheme == 'package') {
    return AssetId(resolved.pathSegments.first,
        p.url.join('lib', p.url.joinAll(resolved.pathSegments.skip(1))));
  } else if (resolved.scheme == 'asset') {
    return AssetId(resolved.pathSegments.first,
        p.url.joinAll(resolved.pathSegments.skip(1)));
  }
  throw UnsupportedError(
      'Cannot resolve $uri; only "package" and "asset" schemes supported');
}