Is it possible to define valid JavaScript's functions from Dart?

Issue

Sorry for my broken English.
I’m new to the Dart language. I have been searching for a way to communicate between JS and Dart. I want to call jQueryUI code from Dart.

When I create a jQueryUI’s dialog, the HTML and JS code will be like this:

HTML code:

...
<button id="btn1">OPEN</button>
<div id="msg">
Hello, world!
</div>
...

JS code:

$('#btn').click( function() {
  $('#msg').dialog('open');
});

$('#msg').dialog({
  autoOpen: false,
  buttons: {
    "OK": function() {
      $(this).dialog('close');
    }
  },
  title: "Dialog",
  modal: false,
  show: 'fold',
  hide: 'puff'
});

So, I tried to convert these JS code into Dart code.
However, when I write these test Dart codes below, I got an error message below.

Breaking on exception: Closure call with mismatched arguments: function 'call'

Dart code:

import 'dart:html';
import 'dart:js' as js;

void dartFunc() {
  print("test");
}

void main() {

  js.JsObject btn = js.context.callMethod(r'$', ['#btn']);
  btn.callMethod('click', [dartFunc]); //-----> ERROR!
  //...
}

But, when I wrote a JS function and Dart code below, the error disappeared and the program ran successfully.

JS code:

function jsFunc() {
  console.log("test");
}

Dart code:

import 'dart:html';
import 'dart:js' as js;

void dartFunc() {
  print("test");
}

void main() {

  js.JsObject btn = js.context.callMethod(r'$', ['#btn']);
  btn.callMethod('click', [jsFunc]); -----> SUCCESS!
  //...
}

To find out this problem, I performed some tests.
When I print both functions(jsFunc() and dartFunc()) to the console from Dart, like

Dart code:

...
js.context['dartFunc'] = dartFunc;
print(js.context['jsFunc']);
print(js.context['dartFunc']);
...

the results are below.

function jsFunc() {
  console.log("test");
}
function () {
  return func(Array.prototype.slice.apply(arguments));
} 

Apparently the result of print(js.context['dartFunc']) is odd.

Can anyone help?
Is it possible to define valid JavaScript’s functions from Dart?

Thanks for reading to the end 🙂

Solution

Js function are allowed to be called with not the same number of parameters as the declaration. This is not the same in Dart.

Basically the callback you defined (dartFunc) is called with at least one argument but the function does not support argument. You can simply add optionnal arguments to your Dart function. Thus the error should disappear.

void dartFunc([arg1,arg2,arg3]) {
  print("test");
}

Now the function can be called with 0 to 3 parameters.

Answered By – Alexandre Ardhuin

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.