flutterdart

bool.fromEnvironment always return false


Here's a code:

const bool a = const bool.fromEnvironment("true");
print(a); // false

Yes, default value is false by default. What should I do that a will be true, without using default value? And what is the string parameter? is it a key maybe?


Solution

  • What are you trying to achieve? Setting a to true can be done as const a = true;.

    The bool.fromEnvironment function allows you to look up defined named string properties that can be added at the command line when compiling, or which may be defined by the platform you are compile for/running on. So does String.fromEnvironment and int.fromEnvironment.

    One set of such platform properties are dart.library.* which are set to true for each dart:* library that the platform supports.

    So, to print something other than false, you can do:

    print(const bool.fromEnvironment("dart.library.core"));
    

    That one is pretty boring since all platforms support dart:core. You can check the availability of other libraries as:

    const bool supportsMirrors = bool.fromEnvironment("dart.library.mirrors");
    const bool isJavaScript = bool.fromEnvironment("dart.library.js");
    

    Or, you can supply a value on the command line when compiling. Let's use the dart stand-alone VM as an example. Write the following script script.dart:

    void main() {
      print(const bool.fromEnvironment("my-fancy-thing"));
    }
    

    If you run it as dart script.dart it prints false. If you run it as dart -Dmy-fancy-thing=true script.dart it prints true.