Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javascript from Dart

i was able to fire off an alert message from dart, but couldn't figure out how to call a function I wrote in another js file from dart. This would have been a great selling point if it was straight forward. I did see this post, which got me started, but i feel there must be a way, so please share the love if you figured it out.

Here's what I've done:

  1. Add this to yaml file:

    dependencies: js: hosted: js

  2. Add import statement to top of dart file: import 'package:js/js.dart' as js;

  3. Add this bit of code to show alert message

    js.scoped(() { js.context.alert("jump for joy!"); });

  4. Here's the part which I think should work but doesn't: given that I have a javascript function doSomething(), I should be able to call

    js.context.doSomething();

like image 562
BraveNewMath Avatar asked Dec 12 '12 17:12

BraveNewMath


People also ask

Can Dart run JavaScript?

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.

Can I run 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).

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.


1 Answers

First add the js package as dependency in your pubspec.yaml :

dependencies:
  js: any

Then you can use your own js function myFunc() like that :

import 'package:js/js.dart' as js;

main() {
  js.context.myFunc();
}

js.context is an alias to javascript window.

See Using JavaScript from Dart: The js Library for more details.

like image 109
Alexandre Ardhuin Avatar answered Sep 25 '22 23:09

Alexandre Ardhuin