Skip to main content
An external package import in Dart is a directive that locates and loads source code from dependencies declared in the project’s pubspec.yaml file. These imports utilize the package: URI scheme, allowing the Dart compiler and runtime to resolve libraries managed by the Pub package manager rather than through relative file system paths.

Dependency Declaration

Before an external package can be imported, it must be registered as a dependency. The Dart build system relies on the pubspec.yaml manifest to validate availability.

# pubspec.yaml
dependencies:
  http: ^1.1.0

Import Syntax

The import directive uses a specific URI structure to reference external libraries.
import 'package:<package_name>/<path_to_file>';

URI Components

  • package:: The scheme identifier instructing the Dart compiler to look up the resource in the package configuration.
  • <package_name>: The unique identifier of the dependency as defined in pubspec.yaml.
  • <path_to_file>: The path to the Dart file relative to the package’s lib/ directory.

Resolution Mechanism

When the Dart compiler encounters a package: URI, it performs the following resolution steps:
  1. Configuration Lookup: It consults the .dart_tool/package_config.json file (generated by running dart pub get).
  2. Path Mapping: It maps the <package_name> to the specific file system location (usually within the system’s pub cache) defined in the configuration file.
  3. Lib Rooting: It implicitly treats the lib/ directory of the target package as the root for the <path_to_file> segment.

Namespace Modifiers

External package imports support standard Dart namespace modifiers to manage scope and symbol collisions.

Prefixing

Assigns a namespace alias to the imported package to prevent naming conflicts with local identifiers or other packages.
import 'package:http/http.dart' as http;

void main() {
  // Access symbols via the prefix
  final client = http.Client(); 
}

Filtering

Restricts the symbols imported into the current library scope using show (allowlist) or hide (blocklist).
// Only import the 'Client' class
import 'package:http/http.dart' show Client;

// Import everything except the 'delete' function
import 'package:http/http.dart' hide delete;
Master Dart with Deep Grasping Methodology!Learn More