Expose Dart functions to javascript

Issue

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?

Solution

No problem ! see Calling Dart from JavaScript.

In your case :

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

  js.context['foo'] = foo;
}

Answered By – Alexandre Ardhuin

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

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