part directive is a compilation-level mechanism that aggregates multiple Dart source files into a single library unit. It instructs the compiler to include the content of referenced files into the parent library, treating the code as if it were defined within the same physical file.
Files connected via part and part of share a single library scope and private namespace. This allows mutual access to private members (identifiers prefixed with _) across the parent file and all its parts.
Syntax Overview
The relationship requires a bidirectional reference: the parent file declares thepart, and the child file declares it is part of the parent.
Parent File (Library Entry Point)
Directives
The part Directive
Located in the main library file, this directive specifies a URI pointing to a subordinate file.
- Placement: Must occur after the
librarydirective (if present) and after allimportandexportdirectives, but before any code declarations (classes, functions, variables). - Argument: A string literal representing the URI (relative or absolute) of the file to include.
The part of Directive
Located in the subordinate file, this directive specifies the library to which the file belongs.
- Placement: Must be the first directive in the file (excluding comments and metadata annotations).
- Modes:
- URI-based (Preferred): Points to the file path of the parent library (e.g.,
part of 'library_main.dart';). - Name-based (Legacy): Points to a named library defined in the parent (e.g.,
part of my_system;requireslibrary my_system;in the parent).
- URI-based (Preferred): Points to the file path of the parent library (e.g.,
Scoping and Namespace
- Shared Private Scope: Unlike
import, which isolates private members to their specific file,partfiles share the same private namespace. A class defined in apartfile can access private variables defined in the parent file, and vice versa. - Single Compilation Unit: The Dart compiler treats the parent file and all its parts as a single compilation unit.
- Dependency Management:
- No Imports in Parts: Files declared as a
partcannot containimportorexportdirectives. - Inherited Scope: All dependencies required by the part file must be imported in the parent library file. The part file inherits the import scope of the parent.
- No Imports in Parts: Files declared as a
Resolution Rules
- One-to-Many: A library file can have multiple
partdirectives. - Many-to-One: A part file can only be
part ofexactly one library. - Transitivity: Parts cannot have parts. A file declared as a
part ofanother library cannot utilize thepartdirective itself.
Master Dart with Deep Grasping Methodology!Learn More





