Skip to main content
An external constructor is a constructor declaration marked with the 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 the external keyword and terminate the declaration with a semicolon.
class NativeResource {
  // External generative constructor
  external NativeResource(int id);

  // External factory constructor
  external factory NativeResource.fromSystem();

  // External constant factory constructor
  external const factory NativeResource.symbol(String name);
}

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 external modifier 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 an external constructor, it resolves the implementation through specific backend mechanisms:
  1. Patch Files: In the Dart SDK, @patch annotations 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).
  2. JavaScript Interop: When compiling to JavaScript, external factory constructors in classes annotated with @JS map Dart instantiation syntax directly to JavaScript new operator calls or other JS-side object creation logic.
  3. 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