26

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();

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

6 Comments

And when importing, we should specify the prefix for the above code to work: import 'package:js/js.dart' as js;
what is js:0.0.13 for and how is that different from js: any
is js.scoped still being used?
js.scoped has been removed since package:js is baked with dart:js.
js.context does not exist anymore
|
12

Maybe my answer will be worth it for somebody, so that's why I'm posting a simple JS function call from Dart.

  1. Add the js package dependency:
    dependencies:
      js: any
    
  2. Create a JS file, let's say example.js:
    function test() {
      return 12+20;
    }
    
  3. Add the example.js above inside index.html with the <script src="..."> tag.
  4. Interop the function above from JS to Dart:
    @JS()
    library t;
    
    import 'package:js/js.dart';
    
    @JS()
    external int Test();
    
    class MyOwn {
      int get value => Test();
    }
    
  5. And, in AngularDart's TODOLIST — which is default component available —:
    @override
    Future<Null> ngOnInit() async => print(MyOwn().value);
    

1 Comment

What do I do if the JS I want to call is an NPM package? Eg., github.com/polkadot-js/extension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.