get<T> method
Retrieves a configuration value using dot notation.
Supports nested access with dot notation (e.g., app.database.host).
Returns defaultValue if the key doesn't exist or has wrong type.
If caching is enabled, automatically reloads expired configurations.
final host = config.get<String>('database.host', 'localhost');
final port = config.get<int>('app.port', 3000);
final debug = config.get<bool>('app.debug', false);
Implementation
@override
T? get<T>(String key, [T? defaultValue]) {
// Check if cache is expired or if caching is disabled (always check file modification)
final parts = key.split('.');
final configName = parts.first;
if (_useCache) {
if (_cacheTimestamps.containsKey(configName)) {
final timestamp = _cacheTimestamps[configName]!;
if (DateTime.now().difference(timestamp) > _cacheTtl) {
// Cache expired, reload this config
_reloadConfig(configName);
}
}
} else {
// When caching is disabled, always reload from disk on access.
// This avoids relying on filesystem timestamp resolution.
final baseFile = File('$_configPath/$configName.json');
if (baseFile.existsSync() && !_runtimeDirtyConfigs.contains(configName)) {
_reloadConfig(configName);
}
}
// Continue with the rest of the method...
if (!_config.containsKey(configName)) {
return defaultValue;
}
var current = _config[configName];
for (var i = 1; i < parts.length; i++) {
if (current is! Map<String, dynamic>) {
return defaultValue;
}
if (!current.containsKey(parts[i])) {
return defaultValue;
}
current = current[parts[i]];
}
if (current is T) {
return current;
}
return defaultValue;
}