Syntax and Declaration
Theexternal modifier precedes the function signature. Unlike standard functions, external functions are terminated with a semicolon (;) and do not contain a function body { ... }.
Mechanism and Semantics
- Signature Definition: The Dart compiler uses the
externaldeclaration to enforce type safety (parameter types and return types) during static analysis, treating the function as if it were fully implemented. - Concrete Status: Although
externalfunctions lack a body, they are considered concrete members. They are distinct fromabstractmethods, which are intended to be overridden by subclasses. - Implementation Resolution: The actual implementation is bound at runtime or compile-time depending on the compilation target and annotations.
- Dart Native (VM/AOT): The implementation is typically provided by C/C++ code via
dart:ffi(specifically Native Assets) or internal VM patch files. - Dart Web: The implementation is mapped to JavaScript code via
dart:js_interop.
- Dart Native (VM/AOT): The implementation is typically provided by C/C++ code via
Implementation Binding
Invoking anexternal function without a bound implementation results in a runtime error (typically a NoSuchMethodError). Binding is usually achieved through metadata annotations.
FFI Context (Native Assets)
In the context ofdart:ffi, the external keyword is used in conjunction with the @Native annotation. This mechanism, known as Native Assets, binds the Dart signature directly to a native symbol (e.g., a C function) in a dynamic library.
JavaScript Interop (Web)
In web compilation usingdart:js_interop, the external keyword pairs with @JS annotations to proxy calls to the JavaScript engine. The function signature must use types compatible with the interop boundary.
Restrictions
- No Body: An
externalfunction cannot define a block body. - Constructors: External generative constructors are permitted, provided they lack initializer lists and bodies. External factory constructors are also permitted.
- Static Interop Type Strictness: When using
dart:js_interop, parameters and return types are strictly validated:- Direct Primitives: Only
int,double,num,bool, andvoid(as a return type) are permitted as direct Dart primitives in the signature. - Mapped Types: The Dart
Stringtype is not a valid type for external signatures; it must be explicitly mapped toJSString. - Collections: Standard Dart collections (e.g.,
List,Map) are not allowed and must be typed as their JS counterparts (e.g.,JSArray,JSObject).
- Direct Primitives: Only
Master Dart with Deep Grasping Methodology!Learn More





