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?
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.
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.
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).
No problem ! see Calling Dart from JavaScript.
In your case :
import 'dart:js' as js;
main() {
String foo() {
return "bar!";
}
js.context['foo'] = foo;
}
In Dart 1.20 I had to add allowInterop()
import 'dart:js' as js;
main() {
String foo() {
return "bar!";
}
js.context['foo'] = allowInterop(foo);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With