AlarmSettings.fromJson constructor
Constructs an AlarmSettings
instance from the given JSON data.
This factory adds backward compatibility for v4 JSON structures by detecting the absence of certain fields and adjusting them.
Implementation
factory AlarmSettings.fromJson(Map<String, dynamic> json) {
// Check if 'volumeSettings' key is absent, indicating v4 data
if (!json.containsKey('volumeSettings')) {
_log
..fine('Detected v4 JSON data, applying backward compatibility.')
..fine('Data before adjustment: $json');
final volume = (json['volume'] as num?)?.toDouble();
final fadeDurationSeconds = (json['fadeDuration'] as num?)?.toDouble();
final fadeDurationMillis =
(fadeDurationSeconds != null && fadeDurationSeconds > 0)
? (fadeDurationSeconds * 1000).toInt()
: null;
final volumeEnforced = json['volumeEnforced'] as bool? ?? false;
json['volumeSettings'] = {
'volume': volume,
'fadeDuration': fadeDurationMillis,
'fadeSteps': <Map<String, dynamic>>[],
'volumeEnforced': volumeEnforced,
};
// Default `allowAlarmOverlap` to false for v4
json['allowAlarmOverlap'] = json['allowAlarmOverlap'] ?? false;
// Default `iOSBackgroundAudio` to true for v4
json['iOSBackgroundAudio'] = json['iOSBackgroundAudio'] ?? true;
// Convert dateTime to string so the default JSON parser can handle it
final dateTimeValue = json['dateTime'];
if (dateTimeValue == null) {
throw ArgumentError('dateTime is missing in the JSON data');
}
if (dateTimeValue is int) {
// Convert the int (milliseconds) into a DateTime and then to ISO string
final dt = DateTime.fromMillisecondsSinceEpoch(dateTimeValue ~/ 1000);
json['dateTime'] = dt.toIso8601String();
} else if (dateTimeValue is String) {
// Already a string, just ensure it's valid
// Optionally parse and reassign as an ISO 8601 string again
final dt = DateTime.parse(dateTimeValue);
json['dateTime'] = dt.toIso8601String();
} else {
throw ArgumentError('Invalid dateTime value: $dateTimeValue');
}
_log.fine('Adjusted data: $json');
}
return _$AlarmSettingsFromJson(json);
}