Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose Dart functions to javascript

I'm a bit of a newb to dart, and trying to get my feet wet by writing some library functions in it.

While I've had no problem calling javascript functions from dart, I'd love to be able to call dart functions from javascript, but so far, I'm not having much like.

For example, I'd love to be able to expose some basic functions from dart, for example like so:

main() {
  String foo() {
    return "bar!";
  }

  js.scoped(() {
    js.context.foo = foo;
  });
}

and then be able to call them from javascript, like so:

<script>
  window.onload = function() {
    alert("foo() = " + foo());
  }
</script>

Is something like this even possible?

like image 276
Mason Bryant Avatar asked Mar 27 '13 20:03

Mason Bryant


People also ask

Can JavaScript call darts?

The Dart web platform supports calling JavaScript using the js package, also known as package:js. For help using the js package, see the following: Documentation for the js package: pub.

Is Dart better than JavaScript?

JavaScript gives the best support for dynamic and duck typing. However, JS is not a type-safe language as it allows every code for whatever developers type. Compare to JavaScript, Dart is much more type safer. It supports both open and robust prototyping.

Can I use JavaScript in flutter?

The Javascript runtimes runs synchronously through the dart ffi. So now you can run javascript code as a native citzen inside yours Flutter Mobile Apps (Android, IOS, Windows, Linux and MacOS are all supported).


2 Answers

No problem ! see Calling Dart from JavaScript.

In your case :

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = foo;
}
like image 109
Alexandre Ardhuin Avatar answered Sep 29 '22 04:09

Alexandre Ardhuin


In Dart 1.20 I had to add allowInterop()

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = allowInterop(foo);
}
like image 27
Günter Zöchbauer Avatar answered Sep 29 '22 06:09

Günter Zöchbauer