Typed Config
Part of the Examples. Nested config sections read with getMap/getList, plus the scalar typed accessors, and the clear error a missing key produces.
Source: example/typed_config_example.dart
// Run this example from the package root:
// dart run example/typed_config_example.dart
// print() is fine in example scripts; avoid it in production code instead.
// ignore_for_file: avoid_print
import 'package:pdata/pdata.dart';
void main() {
final config = <String, dynamic>{
'server': {'host': '0.0.0.0', 'port': 8080, 'debug': false},
'database': {
'url': 'postgres://localhost/myapp',
'pool_size': 10,
},
'admins': ['alice', 'bob'],
};
pdataWriteFile('build/app_config.toml', config);
final loaded = pdataReadFile('build/app_config.toml') as Map<String, dynamic>;
// getMap/getList/getInt/etc. give a clear FormatException instead of a
// crash when a key is missing or the wrong shape.
final server = loaded.getMap('server');
print('Server: ${server.getString('host')}:${server.getInt('port')}');
print('Debug mode: ${server.getBool('debug')}');
final database = loaded.getMap('database');
print('Database URL: ${database.getString('url')}');
print('Pool size: ${database.getInt('pool_size', defaultValue: 5)}');
final admins = loaded.getList('admins');
print('Admins: ${admins.join(', ')}');
// A key that doesn't exist and has no default throws a clear error.
try {
server.getInt('max_connections');
} on FormatException catch (e) {
print('\nExpected error for a missing key: $e');
}
}
Run it from the package root:
dart run example/typed_config_example.dart