1
votes

How can import and use any third party javascript libraries in dart..? I want to use snapsvg in my dart application to render svg. But not sure how to add dependencies to add and import it.

I added js: any to my pubspec.yaml and imported packages/browser/interop.js into my html. Where do I place downloaded snapsvg.js and import it to my dart source file to use it.

I am trying to use following javascript code using snapsvg framework from dart.

s = Snap(800, 600);
s.rect(0, 0, 100, 100).attr({
    fill: 'white',
    stroke: 'black'
});

I tried this code from in dart:

  import 'package:js/js.dart' as js;
  void main() {
      var s = js.context.Snap(800, 600);
      s.rect(0, 0, 100, 100);
  }

This works fine in dartium, but when I Run as Javascript after build, I got javascript error "method zm not found in object"

I believe this is not right way and I should use be using callMethod on proxy. So I changed code like this

import 'dart:js' show context, JsObject;
void main() {
     var snap = context['Snap'];
    snap.callMethod('rect', 0,0,100,100);
}

This is not working in Dartium as itself. I would appreciate if someone can provide example of how to call constructor Snap(800, 600) from dart and also rect and attr methods in my example code.

2

2 Answers

1
votes

You add them to the HTML file using <script> tags.
You can call JavaScript functions from Dart using dart-js-interop. There are many examples here on Stackoverflow under this tag - just click on the tag below your question. When you provide a more concrete example it is easier to help.

1
votes

You can call into JavaScript with the built-in dart:js library. Please try to avoid using /package/ js, which is what you install by adding js: any to your pubspec. The js package is likely to cause the dart2js output to be bloated and we're probably going to deprecate it at some point.

You can reference JavaScript files like you would in any HTML page, via script tags. You don't actually import them into Dart source, you use dart:js to access JavaScript via its top-level context property.