Issues with dart:js calls when compiled to JS


I have some severe issues with getting the context call from dart:js to function after having compiled the code to javascript dart2js.

Here’s a simple program I made to show my point, consisting of two files:


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

calledBack() async {
  querySelector('#output3').text = 'Called from JS';

void main() {
  querySelector('#output1').text = 'Started Dart';

  context['callMeFromJS'] = calledBack;



var App = function() {


App.prototype = {

    callMeFromDart: function(){
        var div = document.getElementById('output2');
        div.innerHTML = 'Called from Dart';

var app = new App();


<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="scaffolded-by" content="">
    <link rel="stylesheet" href="styles.css">
    <script async src="main.dart" type="application/dart"></script>
    <script async src="packages/browser/dart.js"></script>
    <script src="main.js"></script>


  <div id="output1"></div>
  <div id="output2"></div>
  <div id="output3"></div>


when I try running this using Dartium it works as intended. However if I compile it to JS and open it using Chromium it will only work about 50% of the time. At other times I get the following error:

Uncaught TypeError: Cannot set property 'textContent' of 
nulldart.main @ html_dart2js.dart:40598dart._IsolateContext.eval$1 @ isolate_helper.dart:460dart.startRootIsolate @ isolate_helper.dart:122(anonymous function) @ main.dart.js:7141(anonymous function) @ main.dart.js:7142init.currentScript @ main.dart.js:7122(anonymous function) @ main.dart.js:7133(anonymous function) @ main.dart.js:7145

I also have a larger project where a similar error happens. Here the error is the following:

Uncaught Uncaught Error: NullError: method not found: 'constructor' on null
Stack Trace:
TypeError: Cannot read property 'constructor' of undefined
    at J.T (
    at $Y (
    at yS.a (
    at yS.dart.yS.$1 (
    at R8.dart.R8.FI (
    at rq.dart.rq.$0 (
    at dart.vs.static.HZ (
    at vs.dart.vs.X2 (
    at eX.dart.eX.$0 (
    at OM.dart.OM.Ki (


It’s probably a timing issue.
Ensure that the JS is loaded before the Dart code (also when transpiled to JS) is executed.
The simple solution is to move the JS script tag before the Dart script tag.

If that isn’t sufficient, you can add some synchronization.
Create a public variable in JS and fire a custom event.
In Dart check if the global variable is set (using Dart-JS-interop) and if it is not already set, listen for the custom event before you continue.

Answered By – Günter Zöchbauer

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

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