int.fromEnvironment 构造函数

const int.fromEnvironment(
  1. String name,
  2. {int defaultValue = 0}
)

Integer value for name in the compilation configuration environment.

编译配置环境由编译或运行 Dart 程序的周围工具提供。环境是一组字符串键与其相关字符串值的映射。与 name 相关的字符串值,或者没有值,必须在与单个程序中的 String.fromEnvironmentint.fromEnvironmentbool.fromEnvironmentbool.hasEnvironment 的所有调用中保持一致。可以使用 String.fromEnvironment 直接访问字符串值。

This constructor looks up the string value for name, then attempts to parse it as an integer, using the same syntax rules as int.parse/int.tryParse. That is, it accepts decimal numerals and hexadecimal numerals with a 0x prefix, and it accepts a leading minus sign. If there is no value associated with name in the compilation configuration environment, or if the associated string value cannot be parsed as an integer, the value of the constructor invocation is the defaultValue integer, which defaults to the integer zero.

The result is effectively the same as that of

int.tryParse(const String.fromEnvironment(name, defaultValue: ""))
    ?? defaultValue

except that the constructor invocation can be a constant value.

示例

const defaultPort = int.fromEnvironment("defaultPort", defaultValue: 80);

In order to check whether a value is there at all, use bool.hasEnvironment. Example

const int? maybeDeclared = bool.hasEnvironment("defaultPort")
    ? int.fromEnvironment("defaultPort")
    : null;

The string value, or lack of a value, associated with a name must be consistent across all calls to String.fromEnvironment, int.fromEnvironment, bool.fromEnvironment and bool.hasEnvironment in a single program.

This constructor is only guaranteed to work when invoked as const. It may work as a non-constant invocation on some platforms which have access to compiler options at run-time, but most ahead-of-time compiled platforms will not have this information.

实现

external const factory int.fromEnvironment(String name,
    {int defaultValue = 0});