What does external mean in Dart?
DartDart Problem Overview
What does external
mean in Dart? For example: external DateTime._now();
I'm new to Dart, I can't find documentation for external
, so can you give an example to help explain?
Dart Solutions
Solution 1 - Dart
> 9.4 External Functions
> An external function is a function whose body is provided separately from its
> declaration. An external function may be a top-level function (17), a method
The body of the function is defined somewhere else.
As far as I know this is used to fix different implementations for Dart VM in the browser and Dart VM on the Server.
Solution 2 - Dart
When we make an external function inside a class like toString()
external String toString();
means this method is abstract and the child of the parent class will add the function body, that's because in Dart we only can make an abstract class.
Summary:
> external function = abstract function in not abstract classes
Solution 3 - Dart
I don't think external
keyword is meant to be used to mark methods as abstract, even if that's possible
It's enough to leave a method with no implementation to set it abstract, inside an abstract class
It's the equivalent of declare
in TypeScript, and extern
in C#, those are used for interoperability with other runtimes, which means you're telling the compiler "Don't worry about this method's implementation, I promise it will exist at runtime", the runtime may be in C or Javascript or whatever
Solution 4 - Dart
In case, if you are wondering why or where should I even use external
keyword, here is a one more example for Flutter.
class MyStruct extends Struct {
@Int32()
external int a;
@Float()
external double b;
external Pointer<Void> c;
}
Sometimes, but not often when you play with native libraries, in this case with Struct
to access native struct's field in memory. Under Struct
We must declare all fields as external
because it will be external fields from dart:ffi
(C / C++).
So, external
is more than just way to declare "abstract method".
Solution 5 - Dart
In my opinion it is an equivalent of Java native
keyword. For example, since current time milliseconds is implemented differently on Android, iOS, Linux etc, DateTime.now().millisecondsSinceEpoch
will be linked to different implementations at runtime. So it is not initially known how this method will look like. For this reason it is marked as external
meaning it is platform dependent.