getPackage static method

Package? getPackage(
  1. String name
)

Utility class for resolving and caching Dart packages at runtime.

PackageUtils provides static methods to locate Package instances from the runtime, cache them for efficient access, and avoid redundant scans.

It works in combination with a runtime reflection system, where available packages can be discovered via Runtime.getAllPackages().

Example:

final package = PackageUtils.getPackage('my_library');
print(package.name);

If the package is not found during lookup, an Exception will be thrown.

This utility is helpful in frameworks that need to access package metadata, scan classes, or perform analysis on Dart packages.

Returns a Package by its name. If the package has been previously resolved, it will be returned from the cache.

If the package cannot be found in the runtime environment, this method throws an Exception.

Example:

try {
  final package = PackageUtils.getPackage('jetleaf_core');
  print('Package URI: ${package.uri}');
} catch (e) {
  print('Package not found');
}

Implementation

static Package? getPackage(String name) {
  if (_packages.containsKey(name)) {
    return _packages[name];
  }

  final package = Runtime.getAllPackages().firstWhereOrNull((p) => p.getName() == name);
  if (package == null) {
    return null;
  }

  return _packages[name] = package;
}