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 thelibrary keyword followed by a qualified identifier (one or more identifiers separated by dots) and a semicolon.
Placement and Composition
- Ordering: The
librarydirective 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 anyimport,export, orpartdirectives. - Cardinality: A compilation unit may contain no more than one
librarydirective.
Library Classification and Scope
Dart files function in one of three capacities based on the presence oflibrary and part of directives:
- Explicit Library: A file containing a
librarydirective. It defines the library scope and name. - Implicit Library: A file containing neither a
librarydirective nor apart ofdirective. The compiler treats this file as a library with an empty name. - Part File: A file containing a
part ofdirective. 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
Thelibrary 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 usingpart 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 viapart 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





