Configuration files
suggest changeMost programs that run longer than a few seconds need settings: a port, a database URL, a log level, a list of enabled features. Short-lived or containerized programs often take them from environment variables and command-line arguments. Once there are more than a handful of settings, or they have structure, a configuration file is easier to read, review and keep in version control.
Dart has no configuration library in the SDK, but dart:io, dart:convert and a few small packages are all you need. This article builds a complete, testable loader and covers:
- JSON, YAML and TOML config files, parsed into plain Dart maps
- where config files belong on Windows, macOS and Linux
- finding the file:
--config, an environment variable, the project directory, the user's config directory - layering defaults, the file, environment variables and command-line overrides
- turning the merged map into a typed, validated configuration object, including typo detection and relative paths
- testing the loader, saving user settings safely, and reloading when the file changes
The examples were run with Dart 3.13, yaml 3.1.4, toml 0.18.0, args 2.7.0 and path 1.9.1, on Windows and Linux. Shell commands use bash syntax.
Choosing a format
| Format | Pros | Cons |
|---|---|---|
| JSON | built into dart:convert, every tool understands it |
no comments, no trailing commas, noisy to edit by hand |
| YAML | comments, compact, familiar from pubspec.yaml |
indentation-sensitive, surprising typing rules |
| TOML | comments, explicit types, hard to get wrong | needs a package, deep nesting is awkward |
A good default: YAML or TOML for files people edit, JSON for files your program writes itself (user preferences, caches, state). The YAML and JSON articles cover those formats in depth; here they are just a way to get a Map.
$ dart pub add yaml toml args path
Parsing any format into a map
Whatever the format, convert it to plain Dart maps and lists right away. The rest of the loader then doesn't care where the data came from:
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:toml/toml.dart';
import 'package:yaml/yaml.dart';
/// Parses a config file into plain Dart maps and lists, picking the
/// format from the file extension.
Map<String, Object?> parseConfig(String path, String text) {
final Object? data = switch (p.extension(path).toLowerCase()) {
'.json' => jsonDecode(text),
'.yaml' || '.yml' => _plain(loadYaml(text, sourceUrl: Uri.file(path))),
'.toml' => TomlDocument.parse(text).toMap(),
final ext => throw FormatException('unsupported config format "$ext"'),
};
// An empty YAML file is null; treat it as an empty config.
if (data == null) return {};
if (data is! Map) throw FormatException('$path: top level must be a map');
return data.cast<String, Object?>();
}
/// Converts read-only YamlMap/YamlList into ordinary maps and lists.
Object? _plain(Object? v) => switch (v) {
YamlMap m => {for (final e in m.entries) '${e.key}': _plain(e.value)},
YamlList l => [for (final e in l) _plain(e)],
_ => v,
};
void main() {
for (final name in ['app.json', 'app.yaml', 'app.toml']) {
final path = p.join('fmt', name);
final config = parseConfig(path, File(path).readAsStringSync());
print('$name: $config');
}
}
The same settings in the three formats:
{
"server": {"host": "0.0.0.0", "port": 8080},
"database": {"url": "postgres://localhost/app", "pool_size": 10},
"features": ["search", "export"]
}
# Settings for myapp
server:
host: 0.0.0.0
port: 8080
database:
url: postgres://localhost/app
pool_size: 10
features: [search, export]
# Settings for myapp
features = ["search", "export"]
[server]
host = "0.0.0.0"
port = 8080
[database]
url = "postgres://localhost/app"
pool_size = 10
All three produce the same data:
app.json: {server: {host: 0.0.0.0, port: 8080}, database: {url: postgres://localhost/app, pool_size: 10}, features: [search, export]}
app.yaml: {server: {host: 0.0.0.0, port: 8080}, database: {url: postgres://localhost/app, pool_size: 10}, features: [search, export]}
app.toml: {features: [search, export], server: {host: 0.0.0.0, port: 8080}, database: {url: postgres://localhost/app, pool_size: 10}}
Syntax errors differ by package. jsonDecode throws a FormatException with a character offset, loadYaml throws YamlException (a FormatException subclass whose message includes line and column), and the toml package throws TomlParserException for syntax errors but TomlRedefinitionException (not a FormatException) for a duplicate key, and only when toMap() is called. All of them extend TomlException, so catch that as well.
Where config files live
Each platform has a conventional directory for per-user settings:
| Platform | Directory |
|---|---|
| Windows | %APPDATA%\myapp (C:\Users\<name>\AppData\Roaming\myapp) |
| macOS | ~/Library/Application Support/myapp |
| Linux | $XDG_CONFIG_HOME/myapp, which defaults to ~/.config/myapp |
dart:io doesn't provide these paths, but they are easy to compute from the environment:
import 'dart:io';
import 'package:path/path.dart' as p;
/// Directory for per-user configuration files of [app].
String userConfigDir(String app, [Map<String, String>? env]) {
env ??= Platform.environment;
String? get(String name) {
final v = env![name];
return (v == null || v.isEmpty) ? null : v;
}
if (Platform.isWindows) {
// C:\Users\<name>\AppData\Roaming\<app>
final base =
get('APPDATA') ?? p.join(get('USERPROFILE')!, 'AppData', 'Roaming');
return p.join(base, app);
}
final home = get('HOME')!;
if (Platform.isMacOS) {
return p.join(home, 'Library', 'Application Support', app);
}
// Linux and other Unix systems: XDG Base Directory specification.
final base = get('XDG_CONFIG_HOME') ?? p.join(home, '.config');
return p.join(base, app);
}
void main() {
print(userConfigDir('myapp'));
}
On Windows:
C:\Users\kjk\AppData\Roaming\myapp
On Linux:
$ dart run bin/dirs.dart
/home/kjk/.config/myapp
$ XDG_CONFIG_HOME=/tmp/cfg dart run bin/dirs.dart
/tmp/cfg/myapp
Taking env as an optional parameter makes the function testable with a fake home directory. Server software on Linux traditionally also reads a system-wide file such as /etc/myapp/config.yaml; Flutter apps should use the path_provider package instead, since mobile platforms have their own rules.
Finding the config file
Tools like git, dart analyze and prettier look for their config in a fixed order. A common order is:
- a path given with
--config - a path in an environment variable (
MYAPP_CONFIG) myapp.yamlin the current directory or any parent directoryconfig.yamlin the user's config directory
import 'dart:io';
import 'package:path/path.dart' as p;
const fileNames = ['myapp.yaml', '.myapp.yaml'];
/// Returns the config file to use, or null if there is none.
File? findConfigFile({
String? explicit,
required Map<String, String> env,
required String cwd,
required String userDir,
}) {
// 1. --config on the command line, 2. MYAPP_CONFIG in the environment.
// The user asked for this file, so it's an error if it doesn't exist.
final requested = explicit ?? env['MYAPP_CONFIG'];
if (requested != null && requested.isNotEmpty) {
final f = File(p.normalize(p.absolute(cwd, requested)));
if (!f.existsSync()) {
throw FileSystemException('config file not found', f.path);
}
return f;
}
// 3. The current directory and its parents, like .gitignore or
// analysis_options.yaml.
var dir = p.absolute(cwd);
while (true) {
for (final name in fileNames) {
final f = File(p.join(dir, name));
if (f.existsSync()) return f;
}
final parent = p.dirname(dir);
if (parent == dir) break; // reached the root
dir = parent;
}
// 4. The per-user config directory.
final f = File(p.join(userDir, 'config.yaml'));
return f.existsSync() ? f : null;
}
void main() {
final root = Directory.systemTemp.createTempSync('find_demo');
final project = Directory(p.join(root.path, 'project', 'src', 'lib'))
..createSync(recursive: true);
final userDir = Directory(p.join(root.path, 'user'))..createSync();
String? show({String? explicit, Map<String, String> env = const {}}) {
try {
final f = findConfigFile(
explicit: explicit,
env: env,
cwd: project.path,
userDir: userDir.path,
);
return f == null ? 'none' : p.relative(f.path, from: root.path);
} on FileSystemException catch (e) {
return 'error: ${e.message}: ${p.relative(e.path!, from: root.path)}';
}
}
print('nothing: ${show()}');
File(p.join(userDir.path, 'config.yaml')).writeAsStringSync('');
print('user dir: ${show()}');
File(p.join(root.path, 'project', 'myapp.yaml')).writeAsStringSync('');
print('project: ${show()}');
print(
'env var: ${show(env: {'MYAPP_CONFIG': '../../../user/config.yaml'})}',
);
print('--config: ${show(explicit: 'prod.yaml')}');
root.deleteSync(recursive: true);
}
Output (on Windows, hence the backslashes):
nothing: none
user dir: user\config.yaml
project: project\myapp.yaml
env var: user\config.yaml
--config: error: config file not found: project\src\lib\prod.yaml
Two details matter here. A file the user explicitly asked for must exist: silently falling back to defaults when --config prod.yaml has a typo is a classic way to run production with development settings. And relative paths given by the user are resolved against the current directory, using p.absolute(cwd, ...) instead of Directory.current directly so that tests can pass any directory. The demo creates its files under Directory.systemTemp (see Temporary files).
Layering: defaults, file, environment, command line
Real deployments rarely use the file alone. The usual precedence, from lowest to highest, is:
- defaults in the code
- the config file
- environment variables (handy in Docker and CI)
- command-line overrides (handy for a one-off run)
With every layer as a nested map, combining them is a deep merge. Environment variables and --set key=value options are turned into nested maps first:
/// Returns a new map with [override] layered on top of [base].
/// Nested maps are merged key by key; everything else (including lists)
/// is replaced.
Map<String, Object?> deepMerge(
Map<String, Object?> base,
Map<String, Object?> override,
) {
final result = {...base};
for (final MapEntry(:key, :value) in override.entries) {
final old = result[key];
result[key] = (old is Map<String, Object?> && value is Map<String, Object?>)
? deepMerge(old, value)
: value;
}
return result;
}
/// Sets a value at a dotted path such as "server.port", creating
/// intermediate maps as needed.
void setPath(Map<String, Object?> map, String path, Object? value) {
final keys = path.split('.');
var current = map;
for (final key in keys.take(keys.length - 1)) {
final next = current[key];
current = next is Map<String, Object?>
? next
: (current[key] = <String, Object?>{});
}
current[keys.last] = value;
}
/// MYAPP_SERVER__PORT=9000 becomes {server: {port: "9000"}}.
/// A double underscore separates levels, so single underscores can
/// appear in key names (MYAPP_DATABASE__POOL_SIZE -> database.pool_size).
Map<String, Object?> envLayer(
Map<String, String> env, {
String prefix = 'MYAPP_',
}) {
final layer = <String, Object?>{};
for (final MapEntry(:key, :value) in env.entries) {
final upper = key.toUpperCase();
if (!upper.startsWith(prefix) || upper == '${prefix}CONFIG') continue;
final path = upper
.substring(prefix.length)
.toLowerCase()
.replaceAll('__', '.');
setPath(layer, path, value);
}
return layer;
}
/// --set server.port=9000 values from the command line.
Map<String, Object?> setLayer(List<String> assignments) {
final layer = <String, Object?>{};
for (final a in assignments) {
final i = a.indexOf('=');
if (i <= 0) throw FormatException('expected key=value, got "$a"');
setPath(layer, a.substring(0, i), a.substring(i + 1));
}
return layer;
}
void main() {
const defaults = <String, Object?>{
'server': {'host': '127.0.0.1', 'port': 8080},
'database': {'url': null, 'pool_size': 5},
'features': <Object?>[],
};
final file = <String, Object?>{
'server': {'host': '0.0.0.0'},
'database': {'url': 'postgres://localhost/app'},
'features': ['search', 'export'],
};
final env = envLayer({
'MYAPP_DATABASE__POOL_SIZE': '20',
'MYAPP_SERVER__PORT': '9000',
'HOME': '/home/me',
});
final cli = setLayer(['server.port=7000']);
print('env: $env');
print('cli: $cli');
final merged = [file, env, cli].fold(defaults, deepMerge);
print('merged: $merged');
print('defaults unchanged: $defaults');
}
env: {database: {pool_size: 20}, server: {port: 9000}}
cli: {server: {port: 7000}}
merged: {server: {host: 0.0.0.0, port: 7000}, database: {url: postgres://localhost/app, pool_size: 20}, features: [search, export]}
defaults unchanged: {server: {host: 127.0.0.1, port: 8080}, database: {url: null, pool_size: 5}, features: []}
Notes:
deepMergenever modifies its inputs, so the defaults can be aconstmap.foldapplies the layers in order, each on top of the previous result.- Lists are replaced, not appended. Appending sounds useful until someone needs to remove a default entry.
- The double-underscore convention for nesting is the one used by ASP.NET Core and many container platforms. Uppercasing the name first also makes it work with Windows, where environment variable names are case-insensitive.
- Values from the environment and the command line are strings (
"9000"), while the file gives anint. The typed layer below accepts both.
From maps to a typed configuration
The rest of the program should never see these maps. Convert the merged map once into an immutable object with real types, and report every problem at once rather than one per run:
// lib/app_config.dart
import 'package:path/path.dart' as p;
enum LogLevel { debug, info, warning, error }
class ConfigException implements Exception {
final String source;
final List<String> problems;
ConfigException(this.source, this.problems);
@override
String toString() =>
'Invalid configuration ($source):\n'
'${problems.map((e) => ' - $e').join('\n')}';
}
class AppConfig {
final String host;
final int port;
final Uri databaseUrl;
final int poolSize;
final LogLevel logLevel;
final String? logFile;
final List<String> features;
AppConfig._(
this.host,
this.port,
this.databaseUrl,
this.poolSize,
this.logLevel,
this.logFile,
this.features,
);
/// Builds a typed config from merged layers. [baseDir] is the directory
/// of the config file; relative paths in the file are resolved against it.
/// [source] names where the values came from, for error messages.
factory AppConfig.fromMap(
Map<String, Object?> map, {
required String baseDir,
String source = 'defaults',
}) {
final problems = <String>[];
final known = <String>{};
Object? lookup(String path) {
known.add(path);
Object? v = map;
for (final key in path.split('.')) {
v = v is Map ? v[key] : null;
}
return v;
}
String? str(String path, {bool required = false}) {
final v = lookup(path);
if (v == null || v == '') {
if (required) problems.add('$path is required');
return null;
}
if (v is String) return v;
if (v is num || v is bool) return '$v';
problems.add('$path must be a string, got ${v.runtimeType}');
return null;
}
// Numbers may be real numbers (from a file) or strings (from the
// environment or the command line).
int integer(String path, {required int min, required int max}) {
final v = lookup(path);
final n = switch (v) {
int i => i,
String s => int.tryParse(s.trim()),
_ => null,
};
if (n == null || n < min || n > max) {
problems.add('$path must be an integer $min..$max, got ${_show(v)}');
return min;
}
return n;
}
final host = str('server.host', required: true) ?? '';
final port = integer('server.port', min: 1, max: 65535);
final poolSize = integer('database.pool_size', min: 1, max: 100);
final dbText = str('database.url', required: true);
final db = dbText == null ? null : Uri.tryParse(dbText);
if (dbText != null && (db == null || !db.hasScheme)) {
problems.add('database.url is not a valid URL: "$dbText"');
}
final levelText = str('log.level') ?? 'info';
final level = LogLevel.values.asNameMap()[levelText];
if (level == null) {
problems.add(
'log.level must be one of '
'${LogLevel.values.map((l) => l.name).join(', ')}, got "$levelText"',
);
}
final logFileText = str('log.file');
final logFile = logFileText == null
? null
: p.normalize(p.absolute(baseDir, logFileText));
final featuresRaw = lookup('features') ?? const [];
final features = switch (featuresRaw) {
List l when l.every((e) => e is String) => List<String>.unmodifiable(l),
// "search,export" from an environment variable
String s => List<String>.unmodifiable(
s.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty),
),
_ => () {
problems.add('features must be a list of strings');
return const <String>[];
}(),
};
// Catch typos like "databse" or "server.prot".
for (final path in _leafPaths(map)) {
if (!known.contains(path)) problems.add('unknown setting "$path"');
}
if (problems.isNotEmpty) throw ConfigException(source, problems);
return AppConfig._(host, port, db!, poolSize, level!, logFile, features);
}
@override
String toString() =>
'AppConfig(\n'
' host: $host, port: $port,\n'
' databaseUrl: ${_redact(databaseUrl)}, poolSize: $poolSize,\n'
' logLevel: ${logLevel.name}, logFile: $logFile,\n'
' features: $features\n'
')';
}
String _show(Object? v) => v is String ? '"$v"' : '$v';
/// All dotted paths to non-map values: {a: {b: 1}} -> ["a.b"].
Iterable<String> _leafPaths(Map map, [String prefix = '']) sync* {
for (final MapEntry(:key, :value) in map.entries) {
final path = '$prefix$key';
if (value is Map) {
yield* _leafPaths(value, '$path.');
} else {
yield path;
}
}
}
Uri _redact(Uri uri) => uri.userInfo.contains(':')
? uri.replace(userInfo: '${uri.userInfo.split(':').first}:****')
: uri;
Three things in this class are easy to forget and painful to miss:
- Unknown keys are errors. Every
lookuprecords the path it read; any leaf in the map that was never read is a typo or an obsolete setting. Without this check,pool_szie: 50is silently ignored and the default is used. - Relative paths are resolved against the config file's directory, not the current directory.
log.file: logs/app.login/srv/myapp/myapp.yamlmeans/srv/myapp/logs/app.logno matter where the program was started from. - Secrets are masked in
toString(), because configuration objects end up in logs. Better still, keep secrets out of config files entirely (see the end of this article).
For bigger configs, the hand-written helpers can be replaced with generated code: json_serializable with @JsonSerializable(checked: true, disallowUnrecognizedKeys: true) produces a fromJson that works on maps from any of the three formats. See JSON and YAML.
Putting it together
lib/loader.dart contains userConfigDir, parseConfig, findConfigFile, deepMerge, envLayer and setLayer from the previous sections, plus the function that ties them together:
// lib/loader.dart (continued)
/// Loads the configuration: defaults < config file < environment < --set.
AppConfig loadConfig({
String? configPath,
List<String> overrides = const [],
Map<String, String>? env,
String? cwd,
}) {
env ??= Platform.environment;
cwd ??= Directory.current.path;
const defaults = <String, Object?>{
'server': {'host': '127.0.0.1', 'port': 8080},
'database': {'url': null, 'pool_size': 5},
'log': {'level': 'info'},
};
final file = findConfigFile(
explicit: configPath,
env: env,
cwd: cwd,
userDir: userConfigDir('myapp', env),
);
var fileLayer = <String, Object?>{};
if (file != null) {
try {
fileLayer = parseConfig(file.path, file.readAsStringSync());
} on YamlException catch (e) {
throw ConfigException(file.path, ['$e']); // includes line and column
} on FormatException catch (e) {
throw ConfigException(file.path, [_describe(e)]);
} on TomlException catch (e) {
throw ConfigException(file.path, [e.message]);
}
}
final merged = [
fileLayer,
envLayer(env),
setLayer(overrides),
].fold(defaults, deepMerge);
return AppConfig.fromMap(
merged,
baseDir: file == null ? cwd : file.parent.path,
source: file?.path ?? 'no config file',
);
}
/// jsonDecode reports a character offset; turn it into line:column.
String _describe(FormatException e) {
final source = e.source, offset = e.offset;
if (source is! String || offset == null) return e.message;
final before = source.substring(0, offset).split('\n');
return '${e.message} at line ${before.length}, column ${before.last.length + 1}';
}
The entry point uses the args package for --config and repeatable --set options, and exits with EX_CONFIG (78) on bad configuration:
// bin/myapp.dart
import 'dart:io';
import 'package:args/args.dart';
import 'package:myapp/app_config.dart';
import 'package:myapp/loader.dart';
void main(List<String> args) {
final parser = ArgParser()
..addOption('config', abbr: 'c', help: 'Path to the config file.')
..addMultiOption(
'set',
splitCommas: false,
help: 'Override a setting: --set server.port=9000',
);
try {
final r = parser.parse(args);
final config = loadConfig(
configPath: r.option('config'),
overrides: r.multiOption('set'),
);
print(config);
} on ConfigException catch (e) {
stderr.writeln(e);
exitCode = 78; // EX_CONFIG
} on FileSystemException catch (e) {
stderr.writeln('error: ${e.message}: ${e.path}');
exitCode = 78;
} on FormatException catch (e) {
stderr.writeln('error: ${e.message}\n${parser.usage}');
exitCode = 64; // EX_USAGE
}
}
splitCommas: false matters: without it, --set features=a,b would be split into two assignments.
The program was compiled with dart compile exe and run on Linux in /tmp/myapp-demo/project/src, one level below this config file:
# /tmp/myapp-demo/project/myapp.yaml
server:
host: 0.0.0.0
database:
url: postgres://app:s3cret@localhost/app
pool_size: 10
log:
file: logs/app.log
features: [search, export]
$ myapp
AppConfig(
host: 0.0.0.0, port: 8080,
databaseUrl: postgres://app:****@localhost/app, poolSize: 10,
logLevel: info, logFile: /tmp/myapp-demo/project/logs/app.log,
features: [search, export]
)
$ MYAPP_SERVER__PORT=9000 MYAPP_LOG__LEVEL=debug myapp --set database.pool_size=50
AppConfig(
host: 0.0.0.0, port: 9000,
databaseUrl: postgres://app:****@localhost/app, poolSize: 50,
logLevel: debug, logFile: /tmp/myapp-demo/project/logs/app.log,
features: [search, export]
)
$ MYAPP_FEATURES=search,admin myapp | grep features
features: [search, admin]
The file was found in the parent directory, and logs/app.log was resolved next to it rather than under src. Errors name the file and every problem:
$ myapp --set server.prot=80 --set log.level=verbose; echo "exit $?"
Invalid configuration (/tmp/myapp-demo/project/myapp.yaml):
- log.level must be one of debug, info, warning, error, got "verbose"
- unknown setting "server.prot"
exit 78
$ MYAPP_SERVER__PORT=http myapp; echo "exit $?"
Invalid configuration (/tmp/myapp-demo/project/myapp.yaml):
- server.port must be an integer 1..65535, got "http"
exit 78
$ myapp --config ../staging.json; echo "exit $?"
error: config file not found: /tmp/myapp-demo/project/staging.json
exit 78
Syntax errors point at the location. Here prod.json has a trailing comma, and myapp.yaml a mis-indented line:
$ myapp --config ../prod.json; echo "exit $?"
Invalid configuration (/tmp/myapp-demo/project/prod.json):
- Unexpected character at line 3, column 52
exit 78
$ myapp; echo "exit $?"
Invalid configuration (/tmp/myapp-demo/project/myapp.yaml):
- Error on line 3, column 2 of ../myapp.yaml: Expected a key while parsing a block mapping.
╷
3 │ port: 80
│ ^
╵
exit 78
Testing the loader
loadConfig takes the environment and working directory as parameters, so tests can run against a temporary directory and a fake environment. Setting HOME and APPDATA to the temp directory guarantees that the developer's real user config never leaks into a test:
// test/config_test.dart
import 'dart:io';
import 'package:myapp/app_config.dart';
import 'package:myapp/loader.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
void main() {
late Directory dir;
late Map<String, String> env;
setUp(() async {
dir = await Directory.systemTemp.createTemp('config_test');
// A fake home directory, so the real user config is never read.
env = {'HOME': dir.path, 'APPDATA': dir.path};
});
tearDown(() => dir.delete(recursive: true));
AppConfig load(String yaml, {List<String> set = const []}) {
File(p.join(dir.path, 'myapp.yaml')).writeAsStringSync(yaml);
return loadConfig(env: env, cwd: dir.path, overrides: set);
}
test('file values override defaults', () {
final c = load('database:\n url: sqlite:app.db\nserver:\n port: 9000\n');
expect(c.port, 9000);
expect(c.host, '127.0.0.1');
});
test('environment beats the file, --set beats both', () {
env['MYAPP_SERVER__PORT'] = '7000';
expect(
load('database: {url: "sqlite:x"}\nserver: {port: 9000}').port,
7000,
);
expect(
load('database: {url: "sqlite:x"}', set: ['server.port=6000']).port,
6000,
);
});
test('reports typos', () {
expect(
() => load('database: {url: "sqlite:x", poolsize: 3}'),
throwsA(
isA<ConfigException>().having((e) => e.problems, 'problems', [
'unknown setting "database.poolsize"',
]),
),
);
});
}
$ dart test
00:00 +3: All tests passed!
Saving user settings
Desktop and command-line tools often write settings back: a theme, recently opened files, a window size. Two rules:
- Write to a temporary file in the same directory and rename it over the old one. A rename within a directory is atomic, so a crash, a full disk or a second instance reading at the same moment never sees a half-written file.
File.renamereplaces an existing target on Windows too. - Use JSON, pretty-printed so a user can still inspect or fix it. Writing YAML while keeping the user's comments needs
yaml_edit, covered in the YAML article.
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
/// Writes [data] as pretty-printed JSON. The content goes to a temporary
/// file in the same directory first and is then renamed over the target,
/// so a crash or a full disk never leaves a half-written config behind.
Future<void> saveJson(String path, Map<String, Object?> data) async {
final file = File(path);
await file.parent.create(recursive: true);
final tmp = File('$path.tmp');
final text = '${const JsonEncoder.withIndent(' ').convert(data)}\n';
await tmp.writeAsString(text, flush: true);
await tmp.rename(path); // replaces the old file
}
Future<Map<String, Object?>> loadJson(String path) async {
final file = File(path);
if (!await file.exists()) return {};
return (jsonDecode(await file.readAsString()) as Map).cast();
}
Future<void> main() async {
final dir = await Directory.systemTemp.createTemp('prefs');
final path = p.join(dir.path, 'myapp', 'settings.json');
final prefs = await loadJson(path);
print('first run: $prefs');
prefs['theme'] = 'dark';
prefs['recent_files'] = ['notes.md', 'todo.txt'];
prefs['window'] = {'width': 1200, 'height': 800};
await saveJson(path, prefs);
print(await File(path).readAsString());
print('reloaded: ${await loadJson(path)}');
print(
await Directory(p.dirname(path))
.list()
.map((e) => p.basename(e.path))
.toList(),
);
await dir.delete(recursive: true);
}
first run: {}
{
"theme": "dark",
"recent_files": [
"notes.md",
"todo.txt"
],
"window": {
"width": 1200,
"height": 800
}
}
reloaded: {theme: dark, recent_files: [notes.md, todo.txt], window: {width: 1200, height: 800}}
[settings.json]
The last line shows that no .tmp file is left behind. In a real program, path would be p.join(userConfigDir('myapp'), 'settings.json'). Keep files the program writes separate from files the user edits: if the program rewrites the user's myapp.yaml, their comments and formatting are gone.
Reloading when the file changes
Long-running servers sometimes need to pick up a new log level or feature list without a restart. Directory.watch() reports file system changes (see Files and directories). Three practical details:
- Watch the directory and filter by file name. Many editors save by writing a new file and renaming it over the old one, which ends a watch on the file itself.
- A single save produces several events, so debounce: wait until events stop for a moment, then reload once.
- If the new file is invalid, keep the last good configuration and log the error. A typo in a config file should never take a running server down.
import 'dart:async';
import 'dart:io';
import 'package:myapp/app_config.dart';
import 'package:myapp/loader.dart';
import 'package:path/path.dart' as p;
/// Holds the current configuration and reloads it when the file changes.
class LiveConfig {
final String path;
AppConfig _current;
final _changes = StreamController<AppConfig>.broadcast();
StreamSubscription<FileSystemEvent>? _watch;
Timer? _debounce;
LiveConfig._(this.path, this._current);
static LiveConfig start(String path) {
final live = LiveConfig._(path, loadConfig(configPath: path));
// Watch the directory, not the file: many editors save by writing a
// new file and renaming it, which would end a watch on the old file.
live._watch = File(path).parent
.watch()
.where(
(e) =>
p.equals(e.path, path) ||
(e is FileSystemMoveEvent && p.equals(e.destination ?? '', path)),
)
.listen((_) => live._schedule());
return live;
}
AppConfig get current => _current;
Stream<AppConfig> get changes => _changes.stream;
// One save often produces several events; reload once they settle.
void _schedule() {
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 200), _reload);
}
void _reload() {
try {
_current = loadConfig(configPath: path);
_changes.add(_current);
} on Exception catch (e) {
// Keep running with the last good configuration.
stderr.writeln('config reload failed, keeping old settings:\n$e');
}
}
Future<void> stop() async {
_debounce?.cancel();
await _watch?.cancel();
await _changes.close();
}
}
Future<void> main() async {
final dir = await Directory.systemTemp.createTemp('live');
final path = p.join(dir.path, 'myapp.yaml');
final file = File(path);
String yaml(String level) =>
'database:\n url: postgres://localhost/app\nlog:\n level: $level\n';
file.writeAsStringSync(yaml('info'));
final live = LiveConfig.start(path);
print('start: ${live.current.logLevel.name}');
live.changes.listen((c) => print('reloaded: ${c.logLevel.name}'));
Future<void> pause() => Future.delayed(const Duration(milliseconds: 500));
file.writeAsStringSync(yaml('debug'));
await pause();
file.writeAsStringSync(yaml('loud'));
await pause();
print('still: ${live.current.logLevel.name}');
// Save the way editors do: write elsewhere, then rename over the file.
File('$path.new')
..writeAsStringSync(yaml('warning'))
..renameSync(path);
await pause();
await live.stop();
await dir.delete(recursive: true);
}
Output on Linux (Windows prints the same, with a Windows temp path):
start: info
reloaded: debug
config reload failed, keeping old settings:
Invalid configuration (/tmp/liveJINHNL/myapp.yaml):
- log.level must be one of debug, info, warning, error, got "loud"
still: debug
reloaded: warning
Only settings that can change safely at runtime should be read from live.current on each use; a listening port or a database pool size usually can't change without a restart. On Unix, the traditional alternative to watching is reloading on SIGHUP, which lets the operator decide when the new file is ready. See Signals and graceful shutdown.
Secrets
Config files are copied, committed, attached to bug reports and printed in logs. Passwords and API keys don't belong in them:
- Commit a sample config (
myapp.example.yaml) with placeholder values and add the real file to.gitignore. - Pass secrets through the environment (
MYAPP_DATABASE__URLworks with the loader above) or through a file mounted by the platform, such as Docker or Kubernetes secrets. See Environment variables for the_FILEconvention. - If a file must hold a secret, make it readable only by its owner.
dart:iohas nochmod, so on Unix runProcess.run('chmod', ['600', path])after creating it (see Running OS commands). - Mask secrets in
toString()of the config object, asAppConfigdoes with the database password.
Summary
- Parse JSON (
dart:convert), YAML (yaml) or TOML (toml) into plain maps immediately, so the rest of the loader is format-independent. - Per-user config goes in
%APPDATA%on Windows,~/Library/Application Supporton macOS and$XDG_CONFIG_HOME(default~/.config) on Linux. - Search in a fixed order:
--config, an environment variable, the current directory and its parents, the user config directory. A file the user named explicitly must exist. - Layer defaults < file < environment < command line with a non-mutating deep merge; replace lists rather than appending.
- Convert the merged map once into an immutable typed object. Accept numbers as strings, collect all problems, reject unknown keys, resolve relative paths against the config file, and mask secrets.
- Pass the environment and working directory as parameters so tests can use a temp directory and a fake home.
- Write settings files atomically (temp file + rename), and keep files the program writes separate from files people edit.
- To reload at runtime, watch the directory, debounce, and keep the last good configuration when the new one is invalid.