get<T> static method

T get<T>(
  1. String key, [
  2. dynamic defaultValue
])

get env value

Env.get('APP_KEY');
Env.get('APP_KEY', 'with_default_value_if_null');
Env.get<int>('PORT', 3000); (This will return int type)
Env.get<num>('PORT', 3000); (This will return num type)
Env.get<bool>('DEBUG', false); (true/1/yes/on is true)
Env.get<String?>('APP_NAME'); (null when it is not set)

A missing or empty key gives the default. With no default:

  • a nullable type (String?, dynamic) gives null
  • String gives an empty string, never the text "null"
  • int, num, double and bool throw an ArgumentError

A real environment variable wins over the .env file, so a docker or systemd deploy can pass config without a .env file.

Implementation

static T get<T>(String key, [dynamic defaultValue]) {
  String? value = Platform.environment[key] ?? Env().env[key];
  if (value == null || value.isEmpty || value.toLowerCase() == 'null') {
    if (defaultValue == null) return _missing<T>(key);
    if (defaultValue is T) return defaultValue;
    value = defaultValue.toString();
  }
  return _cast<T>(key, value);
}