How to call a JS function with the new js (0.6.0) package

Issue

index.html

<!doctype html>
<html>
  <head>
    <script>
      var testFunction = function() {return 'xxx'};
    </script>
  </head>
  <body>
    <script type="application/dart" src="index.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

index.dart

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

@Js() // about to being changed to @JS
external String testFunction();

main() {
  // fails: Exception: Uncaught Error: No top-level method 'testFunction' declared.
  print(testFunction()); 

  // works
  print((js.context['testFunction'] as js.JsFunction).apply([]));
}

Dart VM version: 1.13.0-edge.a598fea28cf26ed82b0a197e65af33a7edca5cac (Thu Oct 15 18:02:15 2015) on “linux_x64”

Solution

Works as expected.

I just had Dartium running during the Dart update and had still the old version running when I tried the example. After closing and reopening Dartium the code worked fine.

Answered By – Günter Zöchbauer

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

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