Skip to main content
The library directive is a top-level declaration that explicitly identifies a Dart compilation unit as a named library and serves as the syntactic target for library-level metadata and documentation.

Syntax

The directive consists of the library keyword followed by a qualified identifier (one or more identifiers separated by dots) and a semicolon.
// Single identifier
library core;

// Dot-separated identifier (conventional)
library my_package.utils;

// With metadata and documentation
/// Provides mathematical constants and functions.
@Deprecated('Use package:math_plus instead')
library my_package.math;

Placement and Composition

  1. Ordering: The library directive must be the first executable directive in the file. It may only be preceded by comments, whitespace, and the script tag (shebang #!). It must appear before any import, export, or part directives.
  2. Cardinality: A compilation unit may contain no more than one library directive.

Library Classification and Scope

Dart files function in one of three capacities based on the presence of library and part of directives:
  1. Explicit Library: A file containing a library directive. It defines the library scope and name.
  2. Implicit Library: A file containing neither a library directive nor a part of directive. The compiler treats this file as a library with an empty name.
  3. Part File: A file containing a part of directive. This file is not a library; it is a component of another library and shares that library’s scope.

Privacy Scope

Privacy in Dart is scoped to the library, not the file. Identifiers prefixed with an underscore (_) are private to the library. Consequently, private members declared in the main library file are accessible within any associated part files, and vice versa.

Metadata and Documentation

The library directive provides the specific attachment point for:
  • Library-level Annotations: Metadata that applies to the entire library context (e.g., @Deprecated, @TestGroup) rather than a specific class or function.
  • Doc Comments: Documentation comments (///) placed immediately before the directive are parsed as the documentation for the library itself.

Interaction with Part Directives

When a library is split into multiple files using part directives, the library directive establishes the name referenced by legacy part of directives.
  • Named Resolution: If the library is declared as library my_lib;, part files may declare ownership via part of my_lib;.
  • URI Resolution: Modern Dart permits part files to reference the library file by URI (e.g., part of 'main.dart';), rendering the explicit library name optional for file linkage purposes.
Master Dart with Deep Grasping Methodology!Learn More