跳到主要内容

使用编译环境声明配置应用

您可以在构建或运行 Dart 应用程序时指定编译环境声明。编译环境声明将配置选项指定为在编译时访问和评估的键值对。

您的应用可以使用环境声明的值来更改其功能或行为。Dart 编译器可以消除由于使用环境声明值进行控制流而无法访问的代码。

您可能会定义和使用环境声明来

  • 在调试期间添加功能,例如启用日志记录。
  • 创建应用程序的不同风格。
  • 配置应用程序行为,例如 HTTP 服务器的端口。
  • 启用应用程序的实验模式以进行测试。
  • 在测试和生产后端之间切换。

要在运行或编译 Dart 应用程序时指定环境声明,请使用 --define 选项或其缩写 -D。使用 <NAME>=<VALUE> 格式指定声明键值对

$ dart run --define=DEBUG=true -DFLAVOR=free

要了解如何使用其他工具设置这些声明,请查看本指南中的指定环境声明部分。该部分解释了声明语法,以及如何在命令行和 IDE 与编辑器中指定它们。

访问环境声明

#

要访问指定的环境声明值,请将 fromEnvironment 构造函数之一与 const 一起使用,或在常量上下文中使用。对于 truefalse 值,请使用 bool.fromEnvironment;对于整数值,请使用 int.fromEnvironment;对于任何其他值,请使用 String.fromEnvironment

每个 fromEnvironment 构造函数都需要环境声明的名称或键。它们还接受可选的 defaultValue 命名参数,以覆盖默认回退值。当未定义声明或指定值无法解析为预期类型时,将使用默认回退值。

例如,如果您只想在环境声明 DEBUG 设置为 true 时打印日志消息

dart
void log(String message) {
  // Log the debug message if the environment declaration 'DEBUG' is `true`.
  // If there was no value specified, do not log.
  if (const bool.fromEnvironment('DEBUG', defaultValue: false)) {
    print('Debug: $message');
  }
}

在此代码片段中,如果在编译期间将 DEBUG 设置为 false,或者根本未指定,则生产编译器可以完全删除条件及其主体。

当未指定声明或指定值无法解析时,fromEnvironment 构造函数会回退到默认值。因此,要专门检查是否已指定环境声明,请使用 bool.hasEnvironment 构造函数

dart
if (const bool.hasEnvironment('DEBUG')) {
  print('Debug behavior was configured!');
}

指定环境声明

#

Dart CLI

#

dart rundart compile 子命令都接受任意数量的 -D--define 选项来指定环境声明值。

$ dart run --define=DEBUG=true -DFLAVOR=free main.dart
$ dart compile exe --define=DEBUG=true -DFLAVOR=free main.dart
$ dart compile js --define=DEBUG=true -DFLAVOR=free main.dart
$ dart compile aot-snapshot --define=DEBUG=true -DFLAVOR=free main.dart
$ dart compile jit-snapshot --define=DEBUG=true -DFLAVOR=free main.dart
$ dart compile kernel --define=DEBUG=true -DFLAVOR=free main.dart

webdev

#

要了解有关配置 webdev 以将环境声明传递给开发和生产 Web 编译器的信息,请查看webdev 配置文档

Visual Studio Code

#

在您的启动配置 (launch.json) 的 configurations 下,添加一个新的 toolArgs 键,其中包含您所需的环境声明

json
"configurations": [
    {
        "name": "Dart",
        "request": "launch",
        "type": "dart",
        "toolArgs": [
          "--define=DEBUG=true"
        ]
    }
]

要了解更多信息,请查看 VS Code 启动配置的文档

JetBrains IDE

#

在您项目的运行/调试配置中,将您所需的环境声明添加到 VM 选项

Adding define option to Jetbrains IDE

要了解更多信息,请查看 JetBrains 关于Dart 运行/调试配置的文档。

Flutter

#

要为 Flutter 工具指定环境声明,请改用 --dart-define 选项

$ flutter run --dart-define=DEBUG=true