Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Dart function from JavaScript

Tags:

dart

My company has a very buggy fat client application written in JavaScript. As usual with a large JavaScript application, the code is rapidly becoming unmanageable.

I personally believe that writing in Dart would be a much better solution. But the 'start again' approach to management will not work.

I known that one can call JavaScript code from Dart, but is it possible to call Dart code from JavaScript?

This would allow us to incrementally replace the more critical libraries with Dart versions and still be able to use the original code base.

like image 250
richard Avatar asked Apr 16 '14 08:04

richard


People also ask

Can JavaScript call darts?

The Dart web platform supports calling JavaScript using the js package, also known as package:js. For help using the js package, see the following: Documentation for the js package: pub.

How do you call a flutter function in JavaScript?

To make a Dart function callable from JavaScript by name, use a setter annotated with @JS() . Sample: @JS() library callable_function; import 'package:js/js. dart'; /// Allows assigning a function to be callable from `window.


2 Answers

You should try Dart's JS interop library.

You can define a callback function inside Dart and export it (in a way) to JavaScript.

Take a look at this example:

Dart code defines JS function

 context['javascriptFunctionName'] = (parameter) {
       //call any Dart method
    }

then call it from JavaScript:

javascriptFunctionName({'param': 'value'});
like image 176
Pawel Psztyc Avatar answered Sep 17 '22 06:09

Pawel Psztyc


With package js instead of dart:js it can be made available to JS this way:

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

void main() {
  setProperty(window, 'callDartFunc', allowInterop(dartFunc));
}

String dartFunc() => 'Hello World';

Thanks to Matan Lurey https://gitter.im/dart-lang/TALK-general?at=585b9b42db9cafe9183a3345

like image 27
Günter Zöchbauer Avatar answered Sep 21 '22 06:09

Günter Zöchbauer