skip to Main Content

I’m trying to use –dart-define but it isn’t working.

I have tried flutter run --dart-define=ENV=Value

And also this vs code launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Dev",
            "program": "${workspaceFolder}/lib/main_development.dart",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--flavor",
                "development",
                "--dart-define",
                "ENV=development",
                "--target",
                "lib/main_development.dart",
                "-v"
            ],
        },
        {
            "name": "Qa",
            "program": "lib/main_qa.dart",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--flavor",
                "qa",
                "--dart-define",
                "ENV=qa",
                "--target",
                "lib/main_qa.dart",
                "-v"
            ],
        }
    ]
}

Then on the first run:

const env = String.fromEnvironment('ENV');

is always "".

I’m on mac 13.4.1 (c) (22F770820d). I need to do this because iOS seems to run main.dart on the first run, not main_development.dart/main_qa.dart. Waiting 5 seconds does not cause it to work. Hitting refresh causes main_development.dart/main_qa.dart to run, and also const env = String.fromEnvironment('ENV') to work.

The issue is not about syntax, because I changed my dev launch settings to @Riyan’s answer and kept my qa launch settings the same. And they both work, but only after an app refresh.

I am using both the iOS simulator and physical iOS device. It behaves the same in release mode.

2

Answers


  1. Found the dart guide for environment variables environment-declarations

    Code :

    print(const String.fromEnvironment('env'));
    print(const String.fromEnvironment('prod'));
    

    CLI:

    flutter run --dart-define="env=CLI" --dart-define=prod=true  
    

    CLI output

    Android Studio Run/Debug Configuration:

    Run/Debug Configuration

    AS output

    VS Code launch.json:

    launch.json

    enter image description here

    Login or Signup to reply.
  2. Additional to @Riyan answer,

    One interesting thing I found lately.

    print(const String.fromEnvironment('env')); // works
    print(String.fromEnvironment('env')); // empty string
    

    adding const somehow makes it work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search