Calling js from Dart

Issue

How do I go call code like this from Dart?

$('.datepicker').datepicker();

I know I can call functions using the “package:js/js.dart” package, like this

@JS("Plotly.plot")
external plot(DivElement element, List<PlotData> plotData, Margin margin);

…but calling a function on an element?

Solution

It’s not 100% clear what you’re asking, but I think you’re asking how to call arbitrary methods on a JS object. It’s not super easy to do this (it is better to write typed interfaces). You have two options:

  1. Use package:js/js_util.dart and invoke callMethod.
  2. Write a @JS()-annotated class for what you want.

For the first, you can write the following:

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

void openDatePicker(Object elements) {
  js.callMethod(elements, 'datepicker', []);
}

… not super elegant (or well typed), but it works. I’d only recommend doing this if you really just need to invoke a single method, and don’t expect to be calling other methods or passing complex arguments.

For the latter, you can still use @JS() technique. For example:

@JS()
external JQueryElements $(String selector);

@JS()
// Because this doesn't "really" align to a class in the JS/DOM.
@anonymous
abstract class JQueryElements {
  @JS()
  external void datepicker();
}

… and you could use it like this:

void main() {
  $('.datepicker').datepicker();
}

Answered By – matanlurey

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *