Calling Dart from Javascript

Issue

How can I let the dart to js compiler export a dart api to js with a direct mapping from the original dart api to the js api resulting from transpilation?

The purpose is simply to write a library in dart and use it from js.

There is no problem calling js from dart. But, my question adresses interop the other way around. At the moment I cant find any library or documentation as a solution to that issue. In the documentation of the dart:js and package:js libraries it is explicitly specified that interop works only one way.

There are improper solutions to achieve the other way of interop, but only by hack. For example Calling Dart code from javascript enforces passing and returning to and from a function in a way that is restricted by the interop library instead of the intention of the developer.

Explicitly I do not encourage a solution like this https://stackoverflow.com/a/45883551 as an answer since it is a flexible but not a standard solution. For some purposes it is recommendable to have a standard mapping between original and transpiled apis. And the referenced answer is quite complicated.

This means that even the term “I N T E R”op might be wrong as it implies two ways of operation! Currently, there seems to be no interop between dart and js – is that really true?

Solution

Dart is not a good fit for that use case.
dart:js and with a bit of hacking package:js allow to expose methods one by one, but that doesn’t seem to fit your use case.

You can use DDC which is intended for development but emits readable code that can be used from JS.

For production Dart is supposed to be compiled to JS using the dart2js tools that does tree-shaking and minification. Tree-shaking requires whole app-analysis to know what code needs to be retained.

I have heard from projects where DDC works good for use cases similar to yours.

Answered By – Günter Zöchbauer

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *