Environment Variables in Dart
Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in Dart.
import 'dart:io';
void main() {
// To set a key/value pair, use Platform.environment['KEY'] = 'value'.
// To get a value for a key, use Platform.environment['KEY'].
// This will return null if the key isn't present in the environment.
Platform.environment['FOO'] = '1';
print('FOO: ${Platform.environment['FOO']}');
print('BAR: ${Platform.environment['BAR']}');
// Use Platform.environment to access all key/value pairs in the
// environment. This returns a Map<String, String>.
// Here we print all the keys.
print('');
for (var key in Platform.environment.keys) {
print(key);
}
}
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is null.
$ dart run environment_variables.dart
FOO: 1
BAR: null
TERM_PROGRAM
PATH
SHELL
...
FOO
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
$ BAR=2 dart run environment_variables.dart
FOO: 1
BAR: 2
...
Note that in Dart, we use the Platform.environment
map to interact with environment variables. Setting environment variables programmatically is not directly supported in Dart for security reasons, so we simulate it by modifying the Platform.environment
map. In a real-world scenario, environment variables are typically set outside the Dart program.