Environment variables

suggest change

Environment variables are key-value strings that a process gets from whoever started it: your shell, an IDE, Docker, Kubernetes, systemd or a CI runner. They are the standard way to configure a program without changing its code: which port to listen on, which database to connect to, API keys, log levels.

In Dart (on the VM and in native executables) the environment is available as Platform.environment from dart:io. This article covers:

The examples were run with Dart 3.13 on Windows and Linux. Shell commands use bash syntax unless noted.

Reading a variable

Platform.environment is a Map<String, String>. A missing variable is simply a missing key, so lookups return null:

import 'dart:io';

void main() {
  final env = Platform.environment;

  print('PATH is set: ${env.containsKey('PATH')}');
  print('APP_MODE: ${env['APP_MODE']}');
  print('LOG_LEVEL: ${env['LOG_LEVEL'] ?? 'info'}');
  print('variables: ${env.length}');
}

Setting a variable for a single run in bash puts it in front of the command:

$ APP_MODE=production dart run bin/read.dart
PATH is set: true
APP_MODE: production
LOG_LEVEL: info
variables: 120
$ dart run bin/read.dart
PATH is set: true
APP_MODE: null
LOG_LEVEL: info
variables: 119

The same in other shells:

# PowerShell: sets it for the rest of the session
$env:APP_MODE = "production"
dart run bin/read.dart
Remove-Item Env:APP_MODE
:: cmd.exe: no spaces around =
set APP_MODE=production
dart run bin/read.dart

Values are always strings. A variable can also be set to the empty string (APP_MODE= dart run ...), which is different from not being set at all. In practice it's best to treat empty and missing the same way, as the helpers below do.

The map is read-only

Platform.environment is a snapshot taken when the process starts, and it can't be modified:

import 'dart:io';

void main() {
  try {
    Platform.environment['APP_MODE'] = 'test';
  } on UnsupportedError catch (e) {
    print(e);
  }

  // Make a modifiable copy instead.
  final env = Map<String, String>.of(Platform.environment);
  env['APP_MODE'] = 'test';
  print(env['APP_MODE']);
  print(Platform.environment['APP_MODE']);
}
Unsupported operation: Cannot modify unmodifiable map
test
null

dart:io has no setenv(). There is no way to change the environment of the running Dart process, so if code needs "different environment variables", pass it a map instead of having it read Platform.environment directly. That's also what makes configuration code testable, as shown later. To give a child process different variables, use the environment parameter of Process.run and Process.start.

Case sensitivity: Windows vs Unix

Variable names are case-sensitive on Linux and macOS but case-insensitive on Windows. Platform.environment follows the platform rules:

import 'dart:io';

void main() {
  final env = Platform.environment;
  print(Platform.operatingSystem);
  print('Path: ${env['Path'] != null}');
  print('PATH: ${env['PATH'] != null}');
  print('path: ${env['path'] != null}');

  final copy = Map<String, String>.of(env);
  print('copy path: ${copy['path'] != null}');
}

On Windows:

windows
Path: true
PATH: true
path: true
copy path: false

On Linux:

linux
Path: false
PATH: true
path: false
copy path: false

Note the last line on Windows: a copy made with Map.of is an ordinary, case-sensitive Map. The original key on Windows is Path, so copy['PATH'] would also be null. If you copy the environment on Windows and look things up in the copy, normalize the keys (for example with key.toUpperCase()). The simplest rule that works everywhere: use upper-case names for your own variables and spell them the same way everywhere.

Typed values and required variables

Everything in the environment is a string, so programs end up repeating the same parsing code. A small extension on Map<String, String> keeps it in one place and gives clear error messages:

import 'dart:io';

class EnvException implements Exception {
  final String message;
  EnvException(this.message);
  @override
  String toString() => 'EnvException: $message';
}

extension EnvReader on Map<String, String> {
  /// Returns the value, or null if the variable is missing or blank.
  String? str(String name) {
    final value = this[name]?.trim();
    return (value == null || value.isEmpty) ? null : value;
  }

  String require(String name) =>
      str(name) ?? (throw EnvException('$name is not set'));

  int integer(String name, {required int orElse}) {
    final raw = str(name);
    if (raw == null) return orElse;
    return int.tryParse(raw) ??
        (throw EnvException('$name must be an integer, got "$raw"'));
  }

  bool flag(String name, {bool orElse = false}) {
    final raw = str(name)?.toLowerCase();
    if (raw == null) return orElse;
    if (const {'1', 'true', 'yes', 'on'}.contains(raw)) return true;
    if (const {'0', 'false', 'no', 'off'}.contains(raw)) return false;
    throw EnvException('$name must be true or false, got "$raw"');
  }

  Duration seconds(String name, {required Duration orElse}) {
    final raw = str(name);
    if (raw == null) return orElse;
    final n = num.tryParse(raw);
    if (n == null || n < 0) {
      throw EnvException('$name must be a number of seconds, got "$raw"');
    }
    return Duration(milliseconds: (n * 1000).round());
  }

  List<String> list(String name, {String separator = ','}) =>
      str(name)
          ?.split(separator)
          .map((s) => s.trim())
          .where((s) => s.isNotEmpty)
          .toList() ??
      const [];
}

void main() {
  final env = Platform.environment;
  try {
    print('port:    ${env.integer('PORT', orElse: 8080)}');
    print('debug:   ${env.flag('DEBUG')}');
    print('timeout: ${env.seconds('TIMEOUT', orElse: Duration(seconds: 30))}');
    print('hosts:   ${env.list('ALLOWED_HOSTS')}');
    print('db:      ${env.require('DATABASE_URL')}');
  } on EnvException catch (e) {
    stderr.writeln(e.message);
    exitCode = 2;
  }
}

With nothing set, the defaults are used and the required variable is reported:

$ dart run bin/typed.dart; echo "exit $?"
port:    8080
debug:   false
timeout: 0:00:30.000000
hosts:   []
DATABASE_URL is not set
exit 2

With values:

$ PORT=9000 DEBUG=yes TIMEOUT=2.5 ALLOWED_HOSTS="example.com, api.example.com," \
  DATABASE_URL=postgres://localhost/app dart run bin/typed.dart
port:    9000
debug:   true
timeout: 0:00:02.500000
hosts:   [example.com, api.example.com]
db:      postgres://localhost/app

And with a typo:

$ PORT=80a dart run bin/typed.dart; echo "exit $?"
PORT must be an integer, got "80a"
exit 2

Two details worth copying:

The extension works on any Map<String, String>, not just Platform.environment, which matters for testing. See Extension methods for more on extensions.

A configuration class

In a real application, read the environment once at startup into a typed, immutable configuration object, and pass that object around. Nothing else in the program should touch Platform.environment. Collecting all problems before failing saves a round trip for every misconfigured variable:

// lib/config.dart
import 'dart:io';

enum Mode { development, production }

class ConfigException implements Exception {
  final List<String> problems;
  ConfigException(this.problems);
  @override
  String toString() =>
      'Invalid configuration:\n${problems.map((p) => '  - $p').join('\n')}';
}

class Config {
  final Mode mode;
  final int port;
  final Uri databaseUrl;
  final String apiKey;

  const Config({
    required this.mode,
    required this.port,
    required this.databaseUrl,
    required this.apiKey,
  });

  /// Reads the configuration from [env] (defaults to the process environment)
  /// and reports every problem at once.
  factory Config.load([Map<String, String>? env]) {
    env ??= Platform.environment;
    final problems = <String>[];

    String? read(String name) {
      final v = env![name]?.trim();
      return (v == null || v.isEmpty) ? null : v;
    }

    final modeName = read('APP_MODE') ?? 'development';
    final mode = Mode.values.asNameMap()[modeName];
    if (mode == null) {
      problems.add('APP_MODE must be one of '
          '${Mode.values.map((m) => m.name).join(', ')}, got "$modeName"');
    }

    final portRaw = read('PORT') ?? '8080';
    final port = int.tryParse(portRaw);
    if (port == null || port < 1 || port > 65535) {
      problems.add('PORT must be 1-65535, got "$portRaw"');
    }

    final dbRaw = read('DATABASE_URL');
    final db = dbRaw == null ? null : Uri.tryParse(dbRaw);
    if (dbRaw == null) {
      problems.add('DATABASE_URL is required');
    } else if (db == null || !db.hasScheme) {
      problems.add('DATABASE_URL is not a valid URL');
    }

    final apiKey = read('API_KEY');
    if (apiKey == null && mode == Mode.production) {
      problems.add('API_KEY is required in production');
    }

    if (problems.isNotEmpty) throw ConfigException(problems);
    return Config(
      mode: mode!,
      port: port!,
      databaseUrl: db!,
      apiKey: apiKey ?? 'dev-key',
    );
  }

  @override
  String toString() => 'Config(mode: ${mode.name}, port: $port, '
      'databaseUrl: ${_redact(databaseUrl)}, apiKey: ${_mask(apiKey)})';
}

String _mask(String secret) =>
    secret.length <= 4 ? '****' : '${secret.substring(0, 4)}****';

Uri _redact(Uri uri) =>
    uri.userInfo.contains(':')
        ? uri.replace(userInfo: '${uri.userInfo.split(':').first}:****')
        : uri;

Mode.values.asNameMap() turns enum names into a lookup map, so an invalid mode becomes null instead of an exception (see Basic usage of enums).

The entry point loads the configuration and exits with a clear message if it's wrong:

// bin/server.dart
import 'dart:io';
import 'package:envart/config.dart';

void main() {
  final Config config;
  try {
    config = Config.load();
  } on ConfigException catch (e) {
    stderr.writeln(e);
    exit(78); // EX_CONFIG from sysexits.h
  }
  print('Starting with $config');
}
$ APP_MODE=prod PORT=99999 dart run bin/server.dart; echo "exit $?"
Invalid configuration:
  - APP_MODE must be one of development, production, got "prod"
  - PORT must be 1-65535, got "99999"
  - DATABASE_URL is required
exit 78
$ APP_MODE=production DATABASE_URL=postgres://app:s3cret@db:5432/app \
  API_KEY=sk_live_abc123 dart run bin/server.dart
Starting with Config(mode: production, port: 8080, databaseUrl: postgres://app:****@db:5432/app, apiKey: sk_l****)

Note that toString() masks the API key and the database password. Configuration objects tend to end up in log messages and error reports, so make the safe output the default.

Testing configuration code

Because Config.load accepts a map, tests don't need to manipulate the real environment (which isn't possible in Dart anyway):

// test/config_test.dart
import 'package:envart/config.dart';
import 'package:test/test.dart';

void main() {
  test('uses defaults in development', () {
    final config = Config.load({'DATABASE_URL': 'postgres://localhost/app'});
    expect(config.mode, Mode.development);
    expect(config.port, 8080);
    expect(config.apiKey, 'dev-key');
  });

  test('requires API_KEY in production', () {
    expect(
      () => Config.load({
        'APP_MODE': 'production',
        'DATABASE_URL': 'postgres://localhost/app',
      }),
      throwsA(isA<ConfigException>().having(
          (e) => e.problems, 'problems', ['API_KEY is required in production'])),
    );
  });
}
$ dart test
00:00 +2: All tests passed!

To test the whole program end to end with real environment variables, start it as a child process with Process.run and the environment parameter, described below.

.env files

During development it's convenient to keep settings in a .env file in the project root instead of exporting them in every terminal. The dotenv package reads such files:

dart pub add dotenv

A .env file:

# Local development settings. Do not commit this file.
APP_MODE=development
PORT=8081
DB_HOST=localhost
DATABASE_URL=postgres://app:devpass@${DB_HOST}:5432/app
GREETING="hello world"   # quotes are stripped
RAW='no $DB_HOST substitution in single quotes'
export API_KEY=dev-123

Reading it:

import 'package:dotenv/dotenv.dart';

void main() {
  final env = DotEnv(includePlatformEnvironment: true)..load();

  for (final name in ['APP_MODE', 'PORT', 'DATABASE_URL', 'GREETING', 'RAW', 'API_KEY']) {
    print('$name=${env[name]}');
  }
  print('PATH from OS: ${env.isDefined('PATH')}');
  print('all required set: ${env.isEveryDefined(['DATABASE_URL', 'API_KEY'])}');
  print('LOG_LEVEL: ${env.getOrElse('LOG_LEVEL', () => 'info')}');
}
APP_MODE=development
PORT=8081
DATABASE_URL=postgres://app:devpass@localhost:5432/app
GREETING=hello world
RAW=no $DB_HOST substitution in single quotes
API_KEY=dev-123
PATH from OS: true
all required set: true
LOG_LEVEL: info

The parser supports comments, export prefixes, single and double quotes, and $VAR / ${VAR} substitution (not inside single quotes). isDefined treats empty values as not defined.

DotEnv does not change Platform.environment or the environment of child processes. It's a separate map that you read from.

Who wins: the file or the real environment?

With includePlatformEnvironment: true, load() adds the file's values on top of the process environment. So the file wins:

$ PORT=9999 dart run bin/dotenv_demo.dart | grep PORT
PORT=8081

That's usually the wrong way round. The convention (also followed by most dotenv libraries in other languages) is that .env provides defaults and a variable set in the real environment overrides it. That's what lets you write PORT=9999 dart run ... for a one-off change, or override a setting in CI. Get that behavior by loading the files first and adding the platform environment last:

import 'dart:io';
import 'package:dotenv/dotenv.dart';

void main() {
  // Defaults from .env first, then the real environment on top.
  final env = DotEnv(quiet: true)
    ..load(['.env', '.env.local'])
    ..addAll(Platform.environment);

  print('PORT=${env['PORT']}');
}
$ dart run bin/dotenv_order.dart
PORT=8081
$ PORT=9999 dart run bin/dotenv_order.dart
PORT=9999
$ echo "PORT=7000" > .env.local; dart run bin/dotenv_order.dart
PORT=7000

Later files override earlier ones, so .env.local (personal overrides) beats .env (shared defaults). quiet: true suppresses the warning that load() otherwise prints to stderr when a file doesn't exist.

Practical rules for .env files:

Environment of child processes

By default a child process started with Process.run or Process.start inherits the parent's environment. The environment parameter adds or overrides variables, and includeParentEnvironment: false starts from an empty environment instead. See Running OS commands for the rest of the process API.

A child script that prints a few variables:

// bin/child.dart
import 'dart:io';

void main() {
  final env = Platform.environment;
  print('  GREETING=${env['GREETING']}, API_KEY=${env['API_KEY']}, '
      'HOME=${env['HOME']}, ${env.length} variables');
}

And a parent that runs it three ways:

// bin/parent.dart
import 'dart:io';

Future<void> run(String label, Map<String, String> environment,
    {bool includeParent = true}) async {
  final result = await Process.run(
    Platform.resolvedExecutable, // the dart executable running us
    [Platform.script.resolve('child.dart').toFilePath()],
    environment: environment,
    includeParentEnvironment: includeParent,
  );
  print(label);
  stdout.write(result.stdout);
}

Future<void> main() async {
  await run('inherit + add:', {'GREETING': 'hello'});
  await run('only these:', {'GREETING': 'hi'}, includeParent: false);

  // To remove a variable, pass a filtered copy and don't inherit.
  final withoutSecret = Map.of(Platform.environment)..remove('API_KEY');
  await run('without API_KEY:', withoutSecret, includeParent: false);
}

On Linux:

$ API_KEY=secret dart bin/parent.dart
inherit + add:
  GREETING=hello, API_KEY=secret, HOME=/home/kjk, 29 variables
only these:
  GREETING=hi, API_KEY=null, HOME=null, 1 variables
without API_KEY:
  GREETING=null, API_KEY=null, HOME=/home/kjk, 27 variables

Things to keep in mind:

Compile-time defines vs environment variables

Dart has a second, unrelated mechanism with a confusingly similar name: String.fromEnvironment, int.fromEnvironment, bool.fromEnvironment and bool.hasEnvironment. They read compile-time declarations passed with -D, not the OS environment:

import 'dart:io';

const flavorDefined = bool.hasEnvironment('FLAVOR');
const flavor = String.fromEnvironment('FLAVOR', defaultValue: 'dev');

void main() {
  print('compile-time FLAVOR: $flavor (defined: $flavorDefined)');
  print('runtime FLAVOR:      ${Platform.environment['FLAVOR']}');
}
$ FLAVOR=staging dart run bin/compile_vs_run.dart
compile-time FLAVOR: dev (defined: false)
runtime FLAVOR:      staging
$ dart run -DFLAVOR=prod bin/compile_vs_run.dart
compile-time FLAVOR: prod (defined: true)
runtime FLAVOR:      null
$ dart compile exe -DFLAVOR=prod bin/compile_vs_run.dart -o app
$ FLAVOR=staging ./app
compile-time FLAVOR: prod (defined: true)
runtime FLAVOR:      staging

The compiled executable keeps prod forever, whatever the environment says when it runs. When to use which:

-D / fromEnvironment Platform.environment
When it's set at compile time at process start
Can differ per deployment of the same binary no yes
Available on the web and in Flutter apps yes (--dart-define) no
Enables dead-code elimination yes (it's a const) no
Safe for secrets no, baked into the binary yes, if handled carefully
Good for version numbers, build flavors, feature flags ports, URLs, credentials, log levels

More on defines in Constants and Compiling to executables.

dart:io is not available when compiling for the web, so browser apps can't read environment variables at all. Flutter apps on mobile can't either, since phones don't give apps a meaningful environment. For those, pass build-time values with --dart-define=KEY=value or --dart-define-from-file=config.json, and don't put secrets there: anything in the app can be extracted.

Common variables

A few variables are useful in almost every command-line tool. Their names differ between Windows and Unix:

import 'dart:io';

String? homeDir() => Platform.isWindows
    ? Platform.environment['USERPROFILE']
    : Platform.environment['HOME'];

/// Finds [name] on the PATH, like `which` (Unix) or `where` (Windows).
String? which(String name) {
  final env = Platform.environment;
  final separator = Platform.isWindows ? ';' : ':';
  final dirs = (env['PATH'] ?? '').split(separator).where((d) => d.isNotEmpty);
  // On Windows, `git` can mean git.exe, git.cmd, ...
  final extensions = Platform.isWindows
      ? ['', ...(env['PATHEXT'] ?? '.EXE;.BAT;.CMD').toLowerCase().split(';')]
      : [''];
  for (final dir in dirs) {
    for (final ext in extensions) {
      final file = File('$dir${Platform.pathSeparator}$name$ext');
      if (file.existsSync()) return file.path;
    }
  }
  return null;
}

void main() {
  print('home:   ${homeDir()}');
  print('temp:   ${Directory.systemTemp.path}');
  print('user:   ${Platform.environment[Platform.isWindows ? 'USERNAME' : 'USER']}');
  print('dart:   ${which('dart')}');
  print('nope:   ${which('no-such-tool')}');
}

On Linux:

home:   /home/kjk
temp:   /tmp
user:   kjk
dart:   /home/kjk/tmp/dart-envvars/dart-sdk/bin/dart
nope:   null

On Windows:

home:   C:\Users\kjk
temp:   C:\Users\kjk\AppData\Local\Temp
user:   kjk
dart:   C:\Users\kjk\AppData\Local\Microsoft\WinGet\Packages\Google.DartSDK_Microsoft.Winget.Source_8wekyb3d8bbwe\dart-sdk\bin\dart.exe
nope:   null

Notes:

Secrets

Environment variables are the usual way to give a server its credentials, because they keep secrets out of source code and out of the compiled binary. They are not perfectly private, though:

For larger systems, platforms offer secret stores (Kubernetes Secrets, Docker secrets, cloud secret managers) that mount secrets as files. A common pattern is to support both: read API_KEY, or if API_KEY_FILE is set, read the secret from that file:

import 'dart:io';

String? secret(String name, [Map<String, String>? env]) {
  env ??= Platform.environment;
  final path = env['${name}_FILE'];
  if (path != null && path.isNotEmpty) {
    return File(path).readAsStringSync().trim();
  }
  return env[name];
}

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents