external modifier that defines the formal parameter list and interface for object instantiation but delegates the implementation to the underlying runtime environment or a separate compilation unit. It allows a Dart class to expose a constructor signature while the logic for object creation is supplied by platform-specific code, compiler intrinsics, or patch files.
Syntax
To declare an external constructor, prefix the constructor name with theexternal keyword and terminate the declaration with a semicolon.
Semantics and Restrictions
- Implementation Separation: The compiler expects the implementation to be provided at link-time or runtime. If the implementation is missing, the code will fail to compile or throw a runtime error, depending on the compilation target.
- No Method Body: An external constructor cannot contain a block body (
{ ... }). It must end with a semicolon. - No Initializer List: External generative constructors cannot utilize initializer lists (e.g.,
: super(),: _field = value) in the Dart declaration. - No Initializing Formals: External constructors are prohibited from using initializing formals (syntax like
this.variable). Attempting to use them results in a compile-time error, as the constructor does not execute a standard Dart initialization phase where fields are assigned directly from parameters. - Constructor Types: The
externalmodifier applies to:- Generative Constructors: Delegates the creation of a new instance to the backend.
- Factory Constructors: Delegates the logic to return an instance (new or cached).
- Constant Factory Constructors: Allows the creation of compile-time constants via an external implementation (
external const factory).
Resolution Mechanism
When the Dart compiler encounters anexternal constructor, it resolves the implementation through specific backend mechanisms:
- Patch Files: In the Dart SDK,
@patchannotations in separate files define the actual logic, merging the user-facing declaration with the platform-specific implementation (e.g., distinct implementations for the Dart VM versus Dart for the Web). - JavaScript Interop: When compiling to JavaScript,
external factoryconstructors in classes annotated with@JSmap Dart instantiation syntax directly to JavaScriptnewoperator calls or other JS-side object creation logic. - Compiler Intrinsics: Certain external constructors in the core libraries are recognized directly by the compiler and replaced with optimized internal VM instructions or native hooks.
Master Dart with Deep Grasping Methodology!Learn More





