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
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".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.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>
TypeError: Cannot read property 'app' of undefinedapp property? --dart-define allows you to define only 'environment declarations' of primitive type (string, int, bool) so I guess it is not a property of the value you have assigned to an environment declaration.const inlined in the sources, so after compiling the final release they are visible in the .js files. Therefore should not be used for tokens to be kept secret (as mentioned above, the tokens to init Fb in index.html are not to be kept secret; you can verify this by deepening the subject with a google search). For secret tokens, web hosting services usually offer a special mechanism (very easy to use; I used Netlify), and maybe Firebase also offers a similar service (perhaps with Firebase Config, but I don't remember).