跳至主要内容

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

在构建或运行 Dart 应用时,你可以指定编译环境声明。编译环境声明以键值对的形式指定配置选项,这些选项在编译时被访问和评估。

你的应用可以使用环境声明的值来改变其功能或行为。Dart 编译器可以根据环境声明的值,消除因控制流而无法到达的代码。

你可以定义和使用环境声明来

  • 在调试期间添加功能,例如启用日志记录。
  • 为你的应用创建不同的“风格”(flavors)。
  • 配置应用行为,例如 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 options 中。

Adding define option to Jetbrains IDE

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

Flutter

#

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

flutter run --dart-define=DEBUG=true