Home > Mobile >  dart-define not working when running a standalone Dart program
dart-define not working when running a standalone Dart program

Time:01-04

I have a single file Dart program - let's say main.dart. I'm trying to provide some compile time environment values to it using --dart-define=env=env_value but in the Dart program, I'm always getting the default values.

This is what my Dart program looks like


void main() {
  const myValue = const String.fromEnvironment("MY_VALUE", defaultValue: "DEFAULT");
  print('My value: $myValue'); // Always prints "DEFAULT"

}

This is the command I'm using to run my program

dart main.dart --dart-define=MY_VALUE=SOME_VALUE

Now, when I include the exact same code from above in a Flutter app and run it with the below command, everything seems to work as expecetd but for some reason the above program always prints DEFAULT as the output on console.

flutter run --dart-define=MY_VALUE=SOME_VALUE

Is there something I'm missing when it comes to providing these values in a Dart program? I'm running macOS if that helps in any way.

CodePudding user response:

If you type:

dart --help --verbose

It will give you the list of supported flags.

Usage: dart [<vm-flags>] <dart-script-file> [<script-arguments>]

Executes the Dart script <dart-script-file> with the given list of <script-arguments>.

Supported options:
...
--define=<key>=<value> or -D<key>=<value>
  Define an environment declaration. To specify multiple declarations,
  use multiple instances of this option.
...

So it appears that the flag you want is --define or -D, rather than --dart-define. Also note that this is considered a "vm-flag" and must come before the file name in order to work.

Therefore the following command should work:

dart --define=MY_VALUE=SOME_VALUE main.dart 
  •  Tags:  
  • dart
  • Related