Refactor GatewayModel.fromJson to use a loop for status parsing instead of firstWhere.

This commit is contained in:
Faris Armoush
2025-04-09 12:32:44 +03:00
parent c90b9a1912
commit 694a5a7dda

View File

@ -14,27 +14,36 @@ class GatewayModel {
}); });
factory GatewayModel.fromJson(Map<String, dynamic> json) { factory GatewayModel.fromJson(Map<String, dynamic> json) {
final status = json['status'] as List<dynamic>; final status = json['status'] as List<dynamic>? ?? <dynamic>[];
final switchAlarmSound = status.firstWhere( bool? switchAlarmSound;
(item) => item['code'] == 'switch_alarm_sound', String? masterState;
)['value'] as bool; bool? factoryReset;
final masterState = status.firstWhere( String? alarmActive;
(item) => item['code'] == 'master_state',
)['value'] as String; for (final item in status) {
final factoryReset = status.firstWhere( switch (item['code']) {
(item) => item['code'] == 'factory_reset', case 'switch_alarm_sound':
)['value'] as bool; switchAlarmSound = item['value'] as bool;
final alarmActive = status.firstWhere( break;
(item) => item['code'] == 'alarm_active', case 'master_state':
)['value'] as String; masterState = item['value'] as String;
break;
case 'factory_reset':
factoryReset = item['value'] as bool;
break;
case 'alarm_active':
alarmActive = item['value'] as String;
break;
}
}
return GatewayModel( return GatewayModel(
uuid: json['uuid'] as String, uuid: json['uuid'] as String,
switchAlarmSound: switchAlarmSound, switchAlarmSound: switchAlarmSound ?? false,
masterState: masterState, masterState: masterState ?? '',
factoryReset: factoryReset, factoryReset: factoryReset ?? false,
alarmActive: alarmActive, alarmActive: alarmActive ?? '',
); );
} }
} }