Is there any way to access Environment Variables defined by the --dart-define command inside the index.html file of Flutter Web?

I currently can access them inside iOS and Android native files but have not found a way to do so inside the html file


Solution 1: Mabsten

Access to the environment declarations (this is the most correct name, also used in the doc of the String.fromEnvironment() method; see also dart-sdk issue #42136 - Clarify usage of -D/environment variables/environment declarations), is also possible from the javascript code.

There are two details to keep in mind:

  • String.fromEnvironment() can only be invoked with const (also implicit, in const context) and never with "new".
  • In Flutter/web, the main() method is not executed immediately upon loading the main.dart.js script, so it is not sufficient to place the js script (which reads the variable declared in dart) immediately after main.dart.js. It is therefore necessary to signal in some way to the js code when the dart code has been executed. To solve this problem, I resort to a custom DOM event. If there are better solutions, I invite you to report them.

Example:

main.dart

import 'package:flutter/material.dart';

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

void main() {
  //To expone the dart variable to global js code
  js.context["my_dart_var"] = const String.fromEnvironment("my_dart_var");
  //Custom DOM event to signal to js the execution of the dart code
  html.document.dispatchEvent(html.CustomEvent("dart_loaded"));

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
   //...
}

In index.html:

  <script src="main.dart.js" type="application/javascript"></script>

  <script>

    //Here my_dart_var is undefined
    console.log(`my_dart_var: ${window.my_dart_var}`);

    document.addEventListener("dart_loaded", function (){
      //Here my_dart_var is defined
      console.log("dart_loaded event");
      console.log(`my_dart_var: ${window.my_dart_var}`);
    });
  </script>