From 694a5a7dda87dd619eee4358055d28acf5c3ae04 Mon Sep 17 00:00:00 2001 From: Faris Armoush Date: Wed, 9 Apr 2025 12:32:44 +0300 Subject: [PATCH] Refactor GatewayModel.fromJson to use a loop for status parsing instead of firstWhere. --- .../gateway/model/gateway_model.dart | 43 +++++++++++-------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/lib/pages/device_managment/gateway/model/gateway_model.dart b/lib/pages/device_managment/gateway/model/gateway_model.dart index 8e8d00f9..b9600fd7 100644 --- a/lib/pages/device_managment/gateway/model/gateway_model.dart +++ b/lib/pages/device_managment/gateway/model/gateway_model.dart @@ -14,27 +14,36 @@ class GatewayModel { }); factory GatewayModel.fromJson(Map json) { - final status = json['status'] as List; + final status = json['status'] as List? ?? []; - final switchAlarmSound = status.firstWhere( - (item) => item['code'] == 'switch_alarm_sound', - )['value'] as bool; - final masterState = status.firstWhere( - (item) => item['code'] == 'master_state', - )['value'] as String; - final factoryReset = status.firstWhere( - (item) => item['code'] == 'factory_reset', - )['value'] as bool; - final alarmActive = status.firstWhere( - (item) => item['code'] == 'alarm_active', - )['value'] as String; + bool? switchAlarmSound; + String? masterState; + bool? factoryReset; + String? alarmActive; + + for (final item in status) { + switch (item['code']) { + case 'switch_alarm_sound': + switchAlarmSound = item['value'] as bool; + break; + case 'master_state': + 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( uuid: json['uuid'] as String, - switchAlarmSound: switchAlarmSound, - masterState: masterState, - factoryReset: factoryReset, - alarmActive: alarmActive, + switchAlarmSound: switchAlarmSound ?? false, + masterState: masterState ?? '', + factoryReset: factoryReset ?? false, + alarmActive: alarmActive ?? '', ); } }