Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

flutter - 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?

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

question from:https://stackoverflow.com/questions/65647090/access-dart-define-environment-variables-inside-index-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...