how to use javascript library in dart

Tags: , , ,



I am learning package:js and the dart file, which is a dart wrapper for chart.js.

I think this file is a bridge which connects dart and javascript. So, in this file, it must tell what javascript library this dart file is trying to connect. Am I right? But I did not find it.

What do the following statements mean? Do the following two statements tell what javascript library this dart file is trying to connect?

@JS('Chart')
library chart.js;

I have no idea how to map functions https://github.com/google/chartjs.dart/blob/master/lib/chartjs.dart to functions in https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js. Anyone can give more tutorials?

Answer

You don’t need to map to a JavaScript file, you just need to map to JS objects and functions.

You need to add a script tag to index.html that loads the JavaScript file you want to map to, this will make it available globally.

You then need to map

  • Dart functions to JavaScript functions, so when you call such a Dart function the call will actually be forwarded to the JavaScript function.

  • Dart classes so that you can use strongly typed Dart classes which will then be converted to and from JavaScript objects when you for example pass them as parameters to mapped functions or get them as return values from such function calls.

@JS('Chart')
library chart.js;

The name chart.js after library is arbitrary. The library directive just needs an unique name.

@JS('Chart') means that the loaded chart.js library is available in JavaScript land under window.Chart (window means global in JS land and is implicit).

@JS()
class Chart {

declares a Dart class Chart and @JS() maps it to a JS class with the same name in the library scope declared above. So the Dart class Chart will map to the JavaScript class window.Chart.Chart.

external factory Chart(

The external ... declarations inside the Dart Chart class map to the JS methods with the same name.

More details can be found in the README.md https://pub.dartlang.org/packages/js.

If you’re still stuck you can ask more concrete questions. It’s difficult to answer generic questions about how to use a package.



Source: stackoverflow