[英]Access --dart-define environment variables inside index.html
Is there any way to access Environment Variables defined by the --dart-define
command inside the index.html file of Flutter Web?有什么方法可以访问 Flutter Web 的 index.html 文件中
--dart-define
命令定义的环境变量?
I currently can access them inside iOS and Android native files but have not found a way to do so inside the html file我目前可以在 iOS 和 Android 本机文件中访问它们,但在 html 文件中没有找到这样做的方法
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.访问环境声明(这是最正确的名称,也在String.fromEnvironment()方法的文档中使用;另见dart-sdk issue #42136 - Clarify usage of -D/environment variables/environment declarations )是也可以从 javascript 代码。
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". String.fromEnvironment()
只能用const
调用(在 const 上下文中也是隐式的),而不能用“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.main.dart.js
脚本后立即执行,因此将 js 脚本(读取 dart 中声明的变量)紧跟在 main.dart.js 之后是不够的. It is therefore necessary to signal in some way to the js code when the dart code has been executed. 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
:在
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.