如何在 VS Code 中将命令行参数传递给 Web 调试会话

Bam*_*oUA 4 dart visual-studio-code flutter

在 flutter/dart 中编程时,我需要将参数传递给 VS Code 中的调试会话。launch.json我按照文档中的描述添加了以下数据。

{
  "configurations": {
    ..
    // Any custom environment variables to set when running the app with this
    // launch config.
    "env": {
      "DEBUG_MODE": true
    }

    // Arguments to be passed to the Dart or Flutter app.
    "args": [
        "--dart-define", 
        "DEBUG_VALUE=true",
    ],  
}

Run Code Online (Sandbox Code Playgroud)

并尝试读取该值:

void main(List<String> args) {
  final debugMode = String.fromEnvironment('DEBUG_MODE');
  final debugValue = String.fromEnvironment('DEBUG_VALUE');
  ...
}
Run Code Online (Sandbox Code Playgroud)

但变量是空的,args列表也是空的。所以请告诉我我做错了什么?

Dan*_*eny 7

const读取值的时候你确定使用了吗?由于我不完全理解的原因,这似乎只有在值为const

在我的 launch.json 中:

"toolArgs": [
    "--dart-define",
    "FOO=bar",
]
Run Code Online (Sandbox Code Playgroud)

代码如下:

final foo1 = String.fromEnvironment('FOO');
final foo2 = const String.fromEnvironment('FOO');
print('FOO: "$foo1" "$foo2"');
Run Code Online (Sandbox Code Playgroud)

输出是

flutter: FOO: "" "bar"
Run Code Online (Sandbox Code Playgroud)

因此,如果在非常量上下文中调用 String.fromEnvironment,它似乎不会返回该值。

编辑:实际上,在网络中,不使用会const导致异常。但使用const,它仍然按预期工作。