AlarmSettings.fromJson constructor

AlarmSettings.fromJson(
  1. Map<String, dynamic> json
)

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')) {
    // Process volume settings for v4
    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;

    // Adjust `dateTime` field for v4
    if (json['dateTime'] != null) {
      if (json['dateTime'] is int) {
        final dateTimeValue = json['dateTime'] as int;
        // In v4, dateTime was stored in microseconds, convert to milliseconds
        json['dateTime'] = dateTimeValue ~/ 1000;
      } else if (json['dateTime'] is String) {
        // Parse ISO 8601 date string
        json['dateTime'] =
            DateTime.parse(json['dateTime'] as String).millisecondsSinceEpoch;
      } else {
        throw ArgumentError('Invalid dateTime value: ${json['dateTime']}');
      }
    } else {
      throw ArgumentError('dateTime is missing in the JSON data');
    }
  }
  // Parse using the default parser (v5)
  return _$AlarmSettingsFromJson(json);
}