From 04250ebc98fc0b59b40711d75d0861a6552eed53 Mon Sep 17 00:00:00 2001 From: Faris Armoush Date: Thu, 12 Jun 2025 15:33:32 +0300 Subject: [PATCH] formatted all files. --- analysis_options.yaml | 5 + lib/common/dialog_dropdown.dart | 22 +- lib/common/edit_chip.dart | 13 +- lib/common/tag_dialog_textfield_dropdown.dart | 6 +- lib/common/widgets/custom_expansion_tile.dart | 3 +- lib/common/widgets/search_bar.dart | 6 +- lib/firebase_options_prod.dart | 3 +- lib/main.dart | 2 +- lib/main_dev.dart | 8 +- lib/main_staging.dart | 8 +- .../access_management/bloc/access_bloc.dart | 56 +- .../access_management/bloc/access_state.dart | 2 +- .../model/password_model.dart | 2 +- .../helpers/dashed_border_painter.dart | 17 +- .../helpers/get_month_name_from_int.dart | 2 +- .../models/air_quality_data_model.dart | 5 +- .../analytics/models/analytics_device.dart | 9 +- lib/pages/analytics/models/occupacy.dart | 3 +- .../models/occupancy_heat_map_model.dart | 3 +- .../air_quality_distribution_bloc.dart | 6 +- .../device_location/device_location_bloc.dart | 3 +- .../blocs/range_of_aqi/range_of_aqi_bloc.dart | 3 +- .../helpers/range_of_aqi_charts_helper.dart | 3 +- .../air_quality/widgets/aqi_device_info.dart | 3 +- .../widgets/aqi_distribution_chart.dart | 23 +- .../widgets/aqi_sub_value_widget.dart | 2 +- .../widgets/aqi_type_dropdown.dart | 3 +- .../widgets/range_of_aqi_chart.dart | 5 +- .../widgets/range_of_aqi_chart_box.dart | 3 +- .../analytics_devices_event.dart | 3 +- .../analytics_tab/analytics_tab_event.dart | 2 +- .../air_quality_data_loading_strategy.dart | 8 +- ...alytics_data_loading_strategy_factory.dart | 3 +- ...ergy_management_data_loading_strategy.dart | 6 +- .../occupancy_data_loading_strategy.dart | 5 +- .../analytics_communities_sidebar.dart | 3 +- .../widgets/analytics_date_filter_button.dart | 2 +- .../widgets/analytics_page_tab_button.dart | 9 +- .../widgets/month_picker_widget.dart | 37 +- .../sidebar/analytics_space_tree_view.dart | 20 +- .../analytics/widgets/year_picker_widget.dart | 13 +- .../energy_consumption_by_phases_bloc.dart | 15 +- .../energy_consumption_by_phases_event.dart | 6 +- .../energy_consumption_per_device_bloc.dart | 12 +- .../power_clamp_info_bloc.dart | 8 +- .../power_clamp_info_event.dart | 3 +- .../realtime_device_changes_event.dart | 2 +- .../total_energy_consumption_bloc.dart | 2 +- .../total_energy_consumption_event.dart | 6 +- .../energy_management_charts_helper.dart | 6 +- .../fetch_energy_management_data_helper.dart | 3 +- .../analytics_energy_management_view.dart | 3 +- .../widgets/analytics_device_dropdown.dart | 3 +- .../energy_consumption_by_phases_chart.dart | 11 +- ...nergy_consumption_by_phases_chart_box.dart | 3 +- .../energy_consumption_per_device_chart.dart | 1 - ...ergy_consumption_per_device_chart_box.dart | 6 +- .../power_clamp_energy_data_widget.dart | 12 +- .../power_clamp_phases_data_widget.dart | 12 +- .../total_energy_consumption_chart.dart | 1 - .../total_energy_consumption_chart_box.dart | 3 +- .../blocs/occupancy/occupancy_bloc.dart | 6 +- .../helpers/fetch_occupancy_data_helper.dart | 12 +- .../views/analytics_occupancy_view.dart | 9 +- .../occupancy/widgets/occupancy_chart.dart | 9 +- .../widgets/occupancy_chart_box.dart | 6 +- .../widgets/occupancy_heat_map_box.dart | 6 +- .../occupancy/widgets/occupancy_painter.dart | 28 +- ...fake_air_quality_distribution_service.dart | 6 +- ...mote_air_quality_distribution_service.dart | 3 +- .../analytics_devices_service_delagate.dart | 3 +- ..._management_analytics_devices_service.dart | 6 +- ...e_occupancy_analytics_devices_service.dart | 18 +- ...ce_location_details_service_decorator.dart | 2 +- ..._energy_consumption_by_phases_service.dart | 6 +- ...energy_consumption_per_device_service.dart | 9 +- .../occupacy/remote_occupancy_service.dart | 3 +- .../remote_occupancy_heat_map_service.dart | 9 +- .../remote_power_clamp_info_service.dart | 3 +- .../fake_range_of_aqi_service.dart | 22 +- .../range_of_aqi/range_of_aqi_service.dart | 2 +- .../realtime_device_service.dart | 2 +- ...mote_total_energy_consumption_service.dart | 6 +- .../widgets/analytics_sidebar_header.dart | 3 +- lib/pages/auth/bloc/auth_bloc.dart | 65 ++- lib/pages/auth/bloc/auth_event.dart | 3 +- lib/pages/auth/bloc/auth_state.dart | 5 +- .../auth/model/login_with_email_model.dart | 4 +- lib/pages/auth/model/token.dart | 18 +- lib/pages/auth/model/user_model.dart | 27 +- .../auth/view/forget_password_web_page.dart | 236 +++++--- lib/pages/auth/view/login_mobile_page.dart | 82 ++- lib/pages/auth/view/login_web_page.dart | 88 +-- lib/pages/common/access_device_table.dart | 96 ++-- lib/pages/common/buttons/cancel_button.dart | 14 +- lib/pages/common/buttons/default_button.dart | 2 +- lib/pages/common/curtain_toggle.dart | 4 +- lib/pages/common/custom_dialog.dart | 12 +- lib/pages/common/custom_table.dart | 23 +- lib/pages/common/filter/filter_widget.dart | 4 +- lib/pages/common/hour_picker_dialog.dart | 12 +- lib/pages/common/info_dialog.dart | 3 +- .../device_managment/ac/bloc/ac_bloc.dart | 38 +- .../device_managment/ac/bloc/ac_event.dart | 7 +- .../device_managment/ac/bloc/ac_state.dart | 3 +- .../device_managment/ac/model/ac_model.dart | 8 +- .../ac/view/ac_device_batch_control.dart | 10 +- .../ac/view/ac_device_control.dart | 2 +- .../batch_current_temp.dart | 63 +- .../ac/view/control_list/ac_toggle.dart | 2 +- .../ac/view/control_list/current_temp.dart | 19 +- .../device_managment_bloc.dart | 35 +- .../helper/route_controls_based_code.dart | 100 +++- .../all_devices/models/device_sub_space.dart | 7 +- .../all_devices/models/devices_model.dart | 48 +- .../models/factory_reset_model.dart | 5 +- .../widgets/device_managment_body.dart | 37 +- .../widgets/device_search_filters.dart | 4 +- .../ceiling_sensor/bloc/ceiling_bloc.dart | 11 +- .../ceiling_sensor/bloc/ceiling_event.dart | 2 - .../model/ceiling_sensor_model.dart | 67 ++- .../view/ceiling_sensor_batch_control.dart | 17 +- .../curtain/bloc/curtain_bloc.dart | 8 +- .../curtain/bloc/curtain_event.dart | 3 +- .../curtain/bloc/curtain_state.dart | 3 +- .../curtain/model/curtain_model.dart | 4 +- .../view/curtain_batch_status_view.dart | 7 +- .../bloc/setting_bloc_bloc.dart | 19 +- .../device_setting/device_settings_panel.dart | 32 +- .../settings_model/sub_space_model.dart | 4 +- .../device_setting/sub_space_dialog.dart | 8 +- .../door_lock/bloc/door_lock_bloc.dart | 12 +- .../door_lock/bloc/door_lock_state.dart | 1 - .../models/door_lock_status_model.dart | 2 +- .../view/door_lock_batch_control_view.dart | 3 +- .../door_lock/widget/door_button.dart | 2 +- .../flush_mounted_presence_sensor_bloc.dart | 18 +- .../flush_mounted_presence_sensor_event.dart | 3 +- .../flush_mounted_presence_sensor_state.dart | 12 +- ..._mounted_presence_sensor_bloc_factory.dart | 6 +- .../flush_mounted_presence_sensor_model.dart | 26 +- ...ed_presence_sensor_batch_control_view.dart | 49 +- ..._mounted_presence_sensor_control_view.dart | 53 +- .../garage_door/bloc/garage_door_bloc.dart | 48 +- .../helper/garage_door_helper.dart | 78 ++- .../garage_door/models/garage_door_model.dart | 4 +- .../view/garage_door_batch_control_view.dart | 8 +- .../opening_clsoing_time_dialog_body.dart | 4 +- .../widgets/schedule__garage_table.dart | 52 +- .../widgets/schedule_garage_managment_ui.dart | 2 +- .../schedule_garage_mode_selector.dart | 3 +- .../garage_door/widgets/seconds_picker.dart | 3 +- .../widgets/time_out_alarm_dialog_body.dart | 2 +- .../gateway/bloc/gate_way_bloc.dart | 9 +- .../gateway/view/gateway_batch_control.dart | 6 +- .../gateway/view/gateway_view.dart | 6 +- .../bloc/main_door_sensor_bloc.dart | 12 +- .../bloc/main_door_sensor_event.dart | 5 +- .../models/main_door_status_model.dart | 6 +- .../view/main_door_control_view.dart | 27 +- .../view/main_door_sensor_batch_view.dart | 3 +- .../widgets/notification_dialog.dart | 2 +- .../bloc/one_gang_glass_switch_bloc.dart | 18 +- .../models/once_gang_glass_status_model.dart | 5 +- .../one_gang_glass_batch_control_view.dart | 14 +- .../one_gang_glass_switch_control_view.dart | 11 +- .../bloc/wall_light_switch_bloc.dart | 14 +- .../models/wall_light_status_model.dart | 2 +- .../view/wall_light_batch_control.dart | 17 +- .../power_clamp/bloc/smart_power_bloc.dart | 86 +-- .../power_clamp/bloc/smart_power_event.dart | 10 +- .../power_clamp/models/device_event.dart | 3 +- .../models/power_clamp_batch_model.dart | 6 +- .../power_clamp/models/power_clamp_model.dart | 3 +- .../power_clamp/view/phase_widget.dart | 48 +- .../power_clamp/view/power_chart.dart | 22 +- .../view/power_clamp_batch_control_view.dart | 12 +- .../power_clamp/view/power_info_card.dart | 4 +- .../view/smart_power_device_control.dart | 9 +- .../shared/device_batch_control_dialog.dart | 39 +- .../shared/device_control_dialog.dart | 8 +- .../shared/device_controls_container.dart | 5 +- .../presence_display_data.dart | 13 +- .../sensors_widgets/presence_space_type.dart | 8 +- .../presence_static_widget.dart | 7 +- .../sensors_widgets/presence_status.dart | 8 +- .../sensors_widgets/presense_nobody_time.dart | 10 +- .../shared/table/report_table.dart | 36 +- .../shared/toggle_widget.dart | 39 +- .../sos/bloc/sos_device_bloc.dart | 35 +- .../sos/models/sos_status_model.dart | 2 +- .../sos/view/sos_device_control_view.dart | 7 +- .../sos/widgets/sos_notification_dialog.dart | 2 +- .../bloc/three_gang_glass_switch_bloc.dart | 15 +- .../models/three_gang_glass_switch.dart | 2 +- ..._gang_glass_switch_batch_control_view.dart | 20 +- .../three_gang_glass_switch_control_view.dart | 18 +- .../bloc/living_room_bloc.dart | 13 +- .../models/living_room_model.dart | 2 +- .../view/living_room_batch_controls.dart | 14 +- .../view/living_room_device_control.dart | 2 +- .../widgets/cieling_light.dart | 11 +- .../three_gang_switch/widgets/spot_light.dart | 11 +- .../three_gang_switch/widgets/wall_light.dart | 11 +- .../bloc/two_gang_glass_switch_bloc.dart | 16 +- .../models/two_gang_glass_status_model.dart | 2 +- ..._gang_glass_switch_batch_control_view.dart | 14 +- .../two_gang_glass_switch_control_view.dart | 5 +- .../bloc/two_gang_switch_bloc.dart | 10 +- .../bloc/two_gang_switch_state.dart | 2 +- .../models/two_gang_status_model.dart | 2 +- .../view/wall_light_batch_control.dart | 11 +- .../wall_sensor/bloc/wall_bloc.dart | 7 +- .../wall_sensor/model/wall_sensor_model.dart | 56 +- .../view/wall_sensor_batch_control.dart | 32 +- .../view/wall_sensor_conrtols.dart | 53 +- .../water_heater/bloc/water_heater_bloc.dart | 58 +- .../water_heater/bloc/water_heater_event.dart | 2 - .../helper/add_schedule_dialog_helper.dart | 43 +- .../water_heater/models/schedule_entry.dart | 8 +- .../water_heater/models/schedule_model.dart | 7 +- .../models/water_heater_status_model.dart | 14 +- .../view/water_heater_batch_control.dart | 3 +- .../view/water_heater_device_control.dart | 3 +- .../widgets/count_down_button.dart | 2 +- .../widgets/inching_mode_buttons.dart | 6 +- .../widgets/schedule_managment_ui.dart | 2 +- .../widgets/schedule_mode_selector.dart | 2 +- .../water_heater/widgets/schedule_table.dart | 7 +- .../water_leak/bloc/water_leak_bloc.dart | 23 +- .../view/water_leak_batch_control_view.dart | 12 +- .../view/water_leak_control_view.dart | 29 +- .../widgets/water_leak_notifi_dialog.dart | 5 +- lib/pages/home/bloc/home_bloc.dart | 16 +- .../view/agreement_and_privacy_dialog.dart | 12 +- lib/pages/home/view/home_page.dart | 2 +- lib/pages/home/view/home_page_mobile.dart | 12 +- lib/pages/home/view/home_page_web.dart | 4 +- lib/pages/home/view/tree_page.dart | 2 +- .../bloc/roles_permission_bloc.dart | 2 +- .../model/role_type_model.dart | 2 +- .../model/roles_user_model.dart | 8 +- .../add_user_dialog/bloc/users_bloc.dart | 107 ++-- .../add_user_dialog/bloc/users_event.dart | 2 +- .../model/permission_option_model.dart | 2 +- .../model/tree_node_model.dart | 2 +- .../add_user_dialog/view/add_user_dialog.dart | 62 +- .../add_user_dialog/view/basics_view.dart | 61 +- .../add_user_dialog/view/build_tree_view.dart | 7 +- .../view/delete_user_dialog.dart | 7 +- .../view/edit_user_dialog.dart | 68 ++- .../view/permission_management.dart | 77 ++- .../view/popup_menu_filter.dart | 17 +- .../add_user_dialog/view/role_dropdown.dart | 6 +- .../view/roles_and_permission.dart | 19 +- .../view/spaces_access_view.dart | 12 +- .../users_table/bloc/user_table_bloc.dart | 92 ++- .../users_table/bloc/user_table_event.dart | 12 +- .../users_table/bloc/user_table_state.dart | 2 + .../view/creation_date_filter.dart | 13 +- .../users_table/view/de_activate_filter.dart | 13 +- .../users_table/view/name_filter.dart | 13 +- .../users_table/view/user_table.dart | 18 +- .../users_table/view/users_page.dart | 223 ++++---- .../view/create_role_card.dart | 1 + .../roles_and_permission/view/role_card.dart | 5 +- .../view/roles_and_permission_page.dart | 9 +- .../roles_and_permission/view/roles_page.dart | 9 +- .../automation_status_update.dart | 17 +- .../create_routine_bloc.dart | 5 +- .../create_routine_event.dart | 3 +- .../create_routine_state.dart | 4 +- .../effective_period/effect_period_bloc.dart | 24 +- .../effective_period/effect_period_state.dart | 9 +- .../bloc/routine_bloc/routine_bloc.dart | 116 ++-- .../bloc/routine_bloc/routine_event.dart | 13 +- .../bloc/setting_bloc/setting_bloc.dart | 19 +- .../create_new_routines/commu_dropdown.dart | 4 +- .../create_new_routines.dart | 12 +- .../dropdown_menu_content.dart | 9 +- .../create_new_routines/space_dropdown.dart | 8 +- .../space_tree_dropdown_bloc.dart | 2 +- .../space_tree_dropdown_event.dart | 2 +- .../space_tree_dropdown_state.dart | 2 +- .../routines/helper/save_routine_helper.dart | 54 +- lib/pages/routines/models/ac/ac_function.dart | 43 +- .../ceiling_presence_sensor_functions.dart | 78 ++- .../create_scene_model.dart | 4 +- .../models/delay/delay_fucntions.dart | 2 +- .../models/flush/flush_functions.dart | 60 +- .../one_gang_switch/one_gang_switch.dart | 6 +- .../three_gang_switch/three_gang_switch.dart | 60 +- .../two_gang_switch/two_gang_switch.dart | 18 +- lib/pages/routines/models/gateway.dart | 15 +- .../models/pc/energy_clamp_functions.dart | 38 +- .../models/routine_details_model.dart | 17 +- lib/pages/routines/models/routine_model.dart | 34 +- .../water_heater/water_heater_functions.dart | 8 +- .../routines/models/wps/wps_functions.dart | 45 +- .../routines/view/effective_period_view.dart | 2 +- lib/pages/routines/view/routines_view.dart | 4 +- .../routines/widgets/condition_toggle.dart | 8 +- .../widgets/custom_routines_textbox.dart | 36 +- lib/pages/routines/widgets/delete_scene.dart | 13 +- lib/pages/routines/widgets/dragable_card.dart | 39 +- .../routines/widgets/function_slider.dart | 7 +- lib/pages/routines/widgets/if_container.dart | 2 +- .../fetch_routine_scenes_automation.dart | 11 +- .../main_routine_view/routine_view_card.dart | 90 +-- lib/pages/routines/widgets/period_option.dart | 20 +- lib/pages/routines/widgets/repeat_days.dart | 15 +- .../routines/widgets/routine_devices.dart | 8 +- .../widgets/routine_dialogs/ac_dialog.dart | 5 +- .../routine_dialogs/automation_dialog.dart | 13 +- .../cps_dialog_value_selector.dart | 3 +- .../ceiling_sensor/cps_functions_list.dart | 2 +- .../ceiling_sensor/cps_slider_helpers.dart | 8 +- .../widgets/routine_dialogs/delay_dialog.dart | 11 +- .../routine_dialogs/discard_dialog.dart | 6 +- .../effictive_period_dialog.dart | 29 +- .../flush_value_selector_widget.dart | 5 +- .../flush_presence_sensor/time_wheel.dart | 4 +- .../gateway_dialog_value_selector.dart | 3 +- .../one_gang_switch_dialog.dart | 7 +- .../enargy_operational_values_list.dart | 2 - .../energy_value_selector_widget.dart | 12 +- .../routine_dialogs/setting_dialog.dart | 236 +++++--- .../three_gang_switch_dialog.dart | 3 +- .../two_gang_switch_dialog.dart | 11 +- .../wall_sensor/time_wheel.dart | 4 +- .../wall_sensor/wall_presence_sensor.dart | 3 +- .../wps_operational_values_list.dart | 6 +- .../water_heater_operational_values_list.dart | 1 - .../water_heater_value_selector_widget.dart | 17 +- .../widgets/routine_search_and_buttons.dart | 140 +++-- .../widgets/scenes_and_automations.dart | 6 +- .../widgets/search_bar_condition_title.dart | 3 +- .../routines/widgets/then_container.dart | 231 ++++---- lib/pages/routines/widgets/value_display.dart | 2 +- .../space_tree/bloc/space_tree_bloc.dart | 141 ++--- .../space_tree/bloc/space_tree_state.dart | 7 +- .../bloc/add_device_model_bloc.dart | 2 +- .../bloc/add_device_type_model_event.dart | 3 +- .../views/add_device_type_widget.dart | 7 +- .../bloc/space_management_bloc.dart | 146 +++-- .../bloc/space_management_event.dart | 4 +- .../bloc/space_management_state.dart | 5 +- .../all_spaces/model/base_tag.dart | 2 +- .../all_spaces/model/community_model.dart | 11 +- .../all_spaces/model/product_model.dart | 3 +- .../model/selected_product_model.dart | 8 +- .../all_spaces/model/space_model.dart | 16 +- .../model/space_response_model.dart | 3 +- .../all_spaces/model/subspace_model.dart | 3 +- .../all_spaces/model/tag.dart | 19 +- .../view/spaces_management_page.dart | 4 +- .../widgets/add_device_type_widget.dart | 30 +- .../widgets/blank_community_widget.dart | 4 +- ...munity_structure_header_action_button.dart | 8 +- .../community_structure_header_widget.dart | 2 +- .../widgets/community_structure_widget.dart | 112 ++-- .../all_spaces/widgets/counter_widget.dart | 17 +- .../devices_part_widget.dart | 141 +++-- .../icon_choose_part_widget.dart | 4 +- .../space_model_linking_widget.dart | 128 ++--- .../space_name_textfield_widget.dart | 2 +- .../sub_space_part_widget.dart | 136 ++--- .../widgets/curved_line_painter.dart | 10 +- .../widgets/dialogs/create_space_dialog.dart | 27 +- .../widgets/dialogs/delete_dialogue.dart | 34 +- .../dialogs/duplicate_process_dialog.dart | 9 +- .../dialogs/icon_selection_dialog.dart | 12 +- .../gradient_canvas_border_widget.dart | 2 +- .../all_spaces/widgets/hoverable_button.dart | 13 +- .../widgets/loaded_space_widget.dart | 78 +-- .../selected_products_button_widget.dart | 8 +- .../all_spaces/widgets/sidebar_widget.dart | 33 +- .../all_spaces/widgets/space_card_widget.dart | 2 +- .../widgets/space_container_widget.dart | 2 +- .../all_spaces/widgets/space_widget.dart | 2 +- .../assign_tag/bloc/assign_tag_bloc.dart | 6 +- .../assign_tag/bloc/assign_tag_event.dart | 2 +- .../assign_tag/bloc/assign_tag_state.dart | 3 +- .../assign_tag/views/assign_tag_dialog.dart | 5 +- .../widgets/save_add_device_row_widget.dart | 9 +- .../bloc/assign_tag_model_bloc.dart | 48 +- .../bloc/assign_tag_model_event.dart | 2 +- .../views/assign_tag_models_dialog.dart | 12 +- .../views/widgets/RowOfCancelSaveWidget.dart | 25 +- .../widgets/assign_tags_tables_widget.dart | 7 +- .../bloc/community_dialog_bloc.dart | 7 +- .../view/create_community_dialog.dart | 12 +- .../create_subspace/bloc/subspace_bloc.dart | 7 +- .../views/create_subspace_model_dialog.dart | 5 +- .../widgets/ok_cancel_sub_space_widget.dart | 9 +- .../textfield_sub_space_dialog_widget.dart | 13 +- .../bloc/subspace_model_bloc.dart | 4 +- .../widgets/subspace_chip.dart | 3 +- .../helper/space_helper.dart | 44 +- .../spaces_management/helper/tag_helper.dart | 58 +- .../bloc/link_space_to_model_bloc.dart | 20 +- .../bloc/link_space_to_model_state.dart | 2 +- .../view/link_space_model_dialog.dart | 13 +- .../bloc/create_space_model_bloc.dart | 78 ++- .../bloc/create_space_model_event.dart | 12 +- .../bloc/create_space_model_state.dart | 4 +- .../space_model/bloc/space_model_bloc.dart | 23 +- .../models/space_template_model.dart | 13 +- .../space_model/view/space_model_page.dart | 21 +- .../widgets/add_space_model_widget.dart | 2 +- .../widgets/button_content_widget.dart | 4 +- .../widgets/dialog/confirm_merge_dialog.dart | 4 +- .../dialog/confirm_overwrite_dialog.dart | 4 +- .../dialog/create_space_model_dialog.dart | 124 ++-- .../widgets/dialog/custom_loading_dialog.dart | 25 +- .../dialog/delete_space_model_dialog.dart | 11 +- .../link_space_model_spaces_dialog.dart | 29 +- .../dialog/linking_attention_dialog.dart | 4 +- .../widgets/dialog/overwrite_dialog.dart | 10 +- .../widgets/dynamic_product_widget.dart | 26 +- .../widgets/dynamic_room_widget.dart | 29 +- .../widgets/ellipsis_item_widget.dart | 4 +- .../widgets/flexible_item_widget.dart | 4 +- .../space_model/widgets/room_name_widget.dart | 2 +- .../widgets/space_model_card_widget.dart | 92 +-- .../widgets/subspace_chip_widget.dart | 4 +- .../widgets/subspace_model_create_widget.dart | 10 +- .../widgets/subspace_name_label_widget.dart | 4 +- .../widgets/tag_chips_display_widget.dart | 3 +- .../bloc/center_body_bloc.dart | 2 +- .../bloc/center_body_event.dart | 2 +- .../view/center_body_widget.dart | 8 +- .../bloc/add_device_type_model_event.dart | 3 +- .../views/add_device_type_model_widget.dart | 22 +- .../widgets/scrollable_grid_view_widget.dart | 13 +- .../bloc/visitor_password_bloc.dart | 79 ++- .../bloc/visitor_password_event.dart | 2 +- .../visitor_password/model/device_model.dart | 4 +- .../model/failed_operation.dart | 5 - .../view/add_device_dialog.dart | 28 +- .../visitor_password/view/repeat_widget.dart | 4 +- .../view/visitor_password_dialog.dart | 537 +++++++++++------- lib/services/access_mang_api.dart | 64 ++- lib/services/api/http_interceptor.dart | 28 +- lib/services/api/http_service.dart | 4 +- lib/services/api/network_exception.dart | 28 +- lib/services/auth_api.dart | 6 +- .../batch_control_devices_service.dart | 3 +- lib/services/devices_mang_api.dart | 18 +- lib/services/locator.dart | 2 +- lib/services/product_api.dart | 4 +- lib/services/routines_api.dart | 31 +- lib/services/space_mana_api.dart | 33 +- lib/services/space_model_mang_api.dart | 6 +- lib/services/user_permission.dart | 69 +-- lib/utils/color_manager.dart | 12 +- lib/utils/constants/api_const.dart | 2 +- lib/utils/constants/app_enum.dart | 38 +- lib/utils/constants/assets.dart | 290 +++++----- lib/utils/constants/strings_manager.dart | 18 +- lib/utils/enum/device_types.dart | 26 +- lib/utils/extension/build_context_x.dart | 103 ++-- lib/utils/format_date_time.dart | 4 +- lib/utils/helpers/decodeBase64.dart | 2 +- .../helpers/shared_preferences_helper.dart | 18 +- lib/utils/navigation_service.dart | 3 - lib/utils/snack_bar.dart | 22 +- lib/utils/style.dart | 14 +- lib/utils/theme/theme.dart | 2 +- lib/utils/user_drop_down_menu.dart | 12 +- lib/web_layout/default_container.dart | 2 +- lib/web_layout/web_app_bar.dart | 13 +- lib/web_layout/web_scaffold.dart | 3 +- test/widget_test.dart | 1 + 474 files changed, 5425 insertions(+), 4338 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 611cf313..cfae8a7e 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -25,3 +25,8 @@ linter: prefer_int_literals: false sort_constructors_first: false avoid_redundant_argument_values: false + always_put_required_named_parameters_first: false + unnecessary_breaks: false + avoid_catches_without_on_clauses: false + cascade_invocations: false + overridden_fields: false diff --git a/lib/common/dialog_dropdown.dart b/lib/common/dialog_dropdown.dart index 7274b3c0..2d1c3f43 100644 --- a/lib/common/dialog_dropdown.dart +++ b/lib/common/dialog_dropdown.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/utils/color_manager.dart'; +import 'package:syncrow_web/utils/extension/build_context_x.dart'; class DialogDropdown extends StatefulWidget { final List items; @@ -7,14 +8,14 @@ class DialogDropdown extends StatefulWidget { final String? selectedValue; const DialogDropdown({ - Key? key, + super.key, required this.items, required this.onSelected, this.selectedValue, - }) : super(key: key); + }); @override - _DialogDropdownState createState() => _DialogDropdownState(); + State createState() => _DialogDropdownState(); } class _DialogDropdownState extends State { @@ -46,16 +47,14 @@ class _DialogDropdownState extends State { } OverlayEntry _createOverlayEntry() { - final renderBox = context.findRenderObject() as RenderBox; + final renderBox = context.findRenderObject()! as RenderBox; final size = renderBox.size; final offset = renderBox.localToGlobal(Offset.zero); return OverlayEntry( builder: (context) { return GestureDetector( - onTap: () { - _closeDropdown(); - }, + onTap: _closeDropdown, behavior: HitTestBehavior.translucent, child: Stack( children: [ @@ -87,12 +86,9 @@ class _DialogDropdownState extends State { child: ListTile( title: Text( item, - style: Theme.of(context) - .textTheme - .bodyMedium - ?.copyWith( - color: ColorsManager.textPrimaryColor, - ), + style: context.textTheme.bodyMedium?.copyWith( + color: ColorsManager.textPrimaryColor, + ), ), onTap: () { widget.onSelected(item); diff --git a/lib/common/edit_chip.dart b/lib/common/edit_chip.dart index 1643b414..ecda643e 100644 --- a/lib/common/edit_chip.dart +++ b/lib/common/edit_chip.dart @@ -10,24 +10,25 @@ class EditChip extends StatelessWidget { final double borderRadius; const EditChip({ - Key? key, + super.key, this.label = 'Edit', required this.onTap, this.labelColor = ColorsManager.spaceColor, this.backgroundColor = ColorsManager.whiteColors, this.borderColor = ColorsManager.spaceColor, this.borderRadius = 16.0, - }) : super(key: key); + }); @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Chip( - label: Text( - label, - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: labelColor) - ), + label: Text(label, + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: labelColor)), backgroundColor: backgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(borderRadius), diff --git a/lib/common/tag_dialog_textfield_dropdown.dart b/lib/common/tag_dialog_textfield_dropdown.dart index 9fa85284..45d05614 100644 --- a/lib/common/tag_dialog_textfield_dropdown.dart +++ b/lib/common/tag_dialog_textfield_dropdown.dart @@ -9,12 +9,12 @@ class TagDialogTextfieldDropdown extends StatefulWidget { final String product; const TagDialogTextfieldDropdown({ - Key? key, + super.key, required this.items, required this.onSelected, this.initialValue, required this.product, - }) : super(key: key); + }); @override _DialogTextfieldDropdownState createState() => @@ -79,7 +79,7 @@ class _DialogTextfieldDropdownState extends State { } OverlayEntry _createOverlayEntry() { - final renderBox = context.findRenderObject() as RenderBox; + final renderBox = context.findRenderObject()! as RenderBox; final size = renderBox.size; final offset = renderBox.localToGlobal(Offset.zero); diff --git a/lib/common/widgets/custom_expansion_tile.dart b/lib/common/widgets/custom_expansion_tile.dart index 74151ca2..bbe6a074 100644 --- a/lib/common/widgets/custom_expansion_tile.dart +++ b/lib/common/widgets/custom_expansion_tile.dart @@ -10,7 +10,8 @@ class CustomExpansionTile extends StatefulWidget { final ValueChanged? onExpansionChanged; // Notify when expansion changes final VoidCallback? onItemSelected; // Callback for selecting the item - CustomExpansionTile({ + const CustomExpansionTile({ + super.key, required this.title, this.children, this.initiallyExpanded = false, diff --git a/lib/common/widgets/search_bar.dart b/lib/common/widgets/search_bar.dart index a99ac510..a706f155 100644 --- a/lib/common/widgets/search_bar.dart +++ b/lib/common/widgets/search_bar.dart @@ -7,7 +7,7 @@ class CustomSearchBar extends StatefulWidget { final TextEditingController? controller; final String hintText; final String? searchQuery; - final Function(String)? onSearchChanged; // Callback for search input changes + final void Function(String)? onSearchChanged; const CustomSearchBar({ super.key, @@ -37,7 +37,7 @@ class _CustomSearchBarState extends State { color: ColorsManager.whiteColors, boxShadow: [ BoxShadow( - color: Colors.black.withOpacity(0.2), + color: Colors.black.withValues(alpha: 0.2), spreadRadius: 0, blurRadius: 8, offset: const Offset(0, 4), @@ -57,7 +57,7 @@ class _CustomSearchBarState extends State { style: const TextStyle( color: Colors.black, ), - onChanged: widget.onSearchChanged, // Call the callback on text change + onChanged: widget.onSearchChanged, decoration: InputDecoration( filled: true, fillColor: ColorsManager.textFieldGreyColor, diff --git a/lib/firebase_options_prod.dart b/lib/firebase_options_prod.dart index 485696b8..0d9ac673 100644 --- a/lib/firebase_options_prod.dart +++ b/lib/firebase_options_prod.dart @@ -1,7 +1,8 @@ // File generated by FlutterFire CLI. // ignore_for_file: type=lint import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; -import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// diff --git a/lib/main.dart b/lib/main.dart index 8eb6ce38..f875cc04 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -40,7 +40,7 @@ class MyApp extends StatelessWidget { initialLocation: RoutesConst.auth, routes: AppRoutes.getRoutes(), redirect: (context, state) async { - String checkToken = await AuthBloc.getTokenAndValidate(); + final checkToken = await AuthBloc.getTokenAndValidate(); final loggedIn = checkToken == 'Success'; final goingToLogin = state.uri.toString() == RoutesConst.auth; diff --git a/lib/main_dev.dart b/lib/main_dev.dart index 578b2c30..81c71a5f 100644 --- a/lib/main_dev.dart +++ b/lib/main_dev.dart @@ -21,7 +21,8 @@ import 'package:syncrow_web/utils/theme/theme.dart'; Future main() async { try { - const environment = String.fromEnvironment('FLAVOR', defaultValue: 'development'); + const environment = + String.fromEnvironment('FLAVOR', defaultValue: 'development'); await dotenv.load(fileName: '.env.$environment'); WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( @@ -39,7 +40,7 @@ class MyApp extends StatelessWidget { initialLocation: RoutesConst.auth, routes: AppRoutes.getRoutes(), redirect: (context, state) async { - String checkToken = await AuthBloc.getTokenAndValidate(); + final checkToken = await AuthBloc.getTokenAndValidate(); final loggedIn = checkToken == 'Success'; final goingToLogin = state.uri.toString() == RoutesConst.auth; @@ -57,7 +58,8 @@ class MyApp extends StatelessWidget { BlocProvider( create: (context) => CreateRoutineBloc(), ), - BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())), + BlocProvider( + create: (context) => HomeBloc()..add(const FetchUserInfo())), BlocProvider( create: (context) => VisitorPasswordBloc(), ), diff --git a/lib/main_staging.dart b/lib/main_staging.dart index e7f95c57..afccae74 100644 --- a/lib/main_staging.dart +++ b/lib/main_staging.dart @@ -21,7 +21,8 @@ import 'package:syncrow_web/utils/theme/theme.dart'; Future main() async { try { - const environment = String.fromEnvironment('FLAVOR', defaultValue: 'staging'); + const environment = + String.fromEnvironment('FLAVOR', defaultValue: 'staging'); await dotenv.load(fileName: '.env.$environment'); WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( @@ -39,7 +40,7 @@ class MyApp extends StatelessWidget { initialLocation: RoutesConst.auth, routes: AppRoutes.getRoutes(), redirect: (context, state) async { - String checkToken = await AuthBloc.getTokenAndValidate(); + final checkToken = await AuthBloc.getTokenAndValidate(); final loggedIn = checkToken == 'Success'; final goingToLogin = state.uri.toString() == RoutesConst.auth; @@ -57,7 +58,8 @@ class MyApp extends StatelessWidget { BlocProvider( create: (context) => CreateRoutineBloc(), ), - BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())), + BlocProvider( + create: (context) => HomeBloc()..add(const FetchUserInfo())), BlocProvider( create: (context) => VisitorPasswordBloc(), ), diff --git a/lib/pages/access_management/bloc/access_bloc.dart b/lib/pages/access_management/bloc/access_bloc.dart index dd82d739..8b216f04 100644 --- a/lib/pages/access_management/bloc/access_bloc.dart +++ b/lib/pages/access_management/bloc/access_bloc.dart @@ -11,7 +11,7 @@ import 'package:syncrow_web/utils/constants/app_enum.dart'; import 'package:syncrow_web/utils/snack_bar.dart'; class AccessBloc extends Bloc { - AccessBloc() : super((AccessInitial())) { + AccessBloc() : super(AccessInitial()) { on(_onFetchTableData); on(selectTime); on(_filterData); @@ -43,12 +43,12 @@ class AccessBloc extends Bloc { } void updateTabsCount() { - int toBeEffectiveCount = data + final toBeEffectiveCount = data .where((item) => item.passwordStatus.value == 'To be effective') .length; - int effectiveCount = + final effectiveCount = data.where((item) => item.passwordStatus.value == 'Effective').length; - int expiredCount = + final expiredCount = data.where((item) => item.passwordStatus.value == 'Expired').length; tabs[1] = 'To Be Effective ($toBeEffectiveCount)'; tabs[2] = 'Effective ($effectiveCount)'; @@ -81,7 +81,7 @@ class AccessBloc extends Bloc { Emitter emit, ) async { emit(AccessLoaded()); - final DateTime? picked = await showDatePicker( + final picked = await showDatePicker( context: event.context, initialDate: DateTime.now(), firstDate: DateTime.now().add(const Duration(days: -5095)), @@ -89,7 +89,7 @@ class AccessBloc extends Bloc { builder: (BuildContext context, Widget? child) { return Theme( data: ThemeData.light().copyWith( - colorScheme: ColorScheme.light( + colorScheme: const ColorScheme.light( primary: ColorsManager.blackColor, onPrimary: Colors.white, onSurface: ColorsManager.grayColor, @@ -105,20 +105,20 @@ class AccessBloc extends Bloc { }, ); if (picked != null) { - final TimeOfDay? timePicked = await showHourPicker( + final timePicked = await showHourPicker( context: event.context, initialTime: TimeOfDay.now(), ); if (timePicked != null) { - final DateTime selectedDateTime = DateTime( + final selectedDateTime = DateTime( picked.year, picked.month, picked.day, timePicked.hour, timePicked.minute, ); - final int selectedTimestamp = + final selectedTimestamp = selectedDateTime.millisecondsSinceEpoch ~/ 1000; if (event.isStart) { if (expirationTimeTimeStamp != null && @@ -152,39 +152,35 @@ class AccessBloc extends Bloc { final searchText = event.passwordName?.toLowerCase() ?? ''; final searchEmailText = event.emailAuthorizer?.toLowerCase() ?? ''; filteredData = data.where((item) { - bool matchesCriteria = true; + var matchesCriteria = true; // Convert timestamp to DateTime and extract date component - DateTime effectiveDate = DateTime.fromMillisecondsSinceEpoch( + final effectiveDate = DateTime.fromMillisecondsSinceEpoch( int.parse(item.effectiveTime.toString()) * 1000) .toUtc() .toLocal(); - DateTime invalidDate = DateTime.fromMillisecondsSinceEpoch( + final invalidDate = DateTime.fromMillisecondsSinceEpoch( int.parse(item.invalidTime.toString()) * 1000) .toUtc() .toLocal(); - DateTime effectiveDateAndTime = DateTime( + final effectiveDateAndTime = DateTime( effectiveDate.year, effectiveDate.month, effectiveDate.day, effectiveDate.hour, effectiveDate.minute); - DateTime invalidDateAndTime = DateTime( - invalidDate.year, - invalidDate.month, - invalidDate.day, - invalidDate.hour, - invalidDate.minute); + final invalidDateAndTime = DateTime(invalidDate.year, invalidDate.month, + invalidDate.day, invalidDate.hour, invalidDate.minute); // Filter by password name, making the search case-insensitive if (searchText.isNotEmpty) { - final bool matchesName = + final matchesName = item.passwordName.toString().toLowerCase().contains(searchText); if (!matchesName) { matchesCriteria = false; } } if (searchEmailText.isNotEmpty) { - final bool matchesName = item.authorizerEmail + final matchesName = item.authorizerEmail .toString() .toLowerCase() .contains(searchEmailText); @@ -194,7 +190,7 @@ class AccessBloc extends Bloc { } // Filter by start date only if (event.startTime != null && event.endTime == null) { - DateTime startDateTime = + var startDateTime = DateTime.fromMillisecondsSinceEpoch(event.startTime! * 1000) .toUtc() .toLocal(); @@ -206,7 +202,7 @@ class AccessBloc extends Bloc { } // Filter by end date only if (event.endTime != null && event.startTime == null) { - DateTime startDateTime = + var startDateTime = DateTime.fromMillisecondsSinceEpoch(event.endTime! * 1000) .toUtc() .toLocal(); @@ -219,11 +215,11 @@ class AccessBloc extends Bloc { // Filter by both start date and end date if (event.startTime != null && event.endTime != null) { - DateTime startDateTime = + var startDateTime = DateTime.fromMillisecondsSinceEpoch(event.startTime! * 1000) .toUtc() .toLocal(); - DateTime endDateTime = + var endDateTime = DateTime.fromMillisecondsSinceEpoch(event.endTime! * 1000) .toUtc() .toLocal(); @@ -258,7 +254,7 @@ class AccessBloc extends Bloc { } } - resetSearch(ResetSearch event, Emitter emit) async { + Future resetSearch(ResetSearch event, Emitter emit) async { emit(AccessLoaded()); startTime = 'Start Time'; endTime = 'End Time'; @@ -272,7 +268,7 @@ class AccessBloc extends Bloc { } String timestampToDate(dynamic timestamp) { - DateTime dateTime = + final dateTime = DateTime.fromMillisecondsSinceEpoch(int.parse(timestamp) * 1000); return "${dateTime.year}/${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')} " " ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}"; @@ -289,17 +285,17 @@ class AccessBloc extends Bloc { break; case 1: // To Be Effective filteredData = data - .where((item) => item.passwordStatus.value == "To Be Effective") + .where((item) => item.passwordStatus.value == 'To Be Effective') .toList(); break; case 2: // Effective filteredData = data - .where((item) => item.passwordStatus.value == "Effective") + .where((item) => item.passwordStatus.value == 'Effective') .toList(); break; case 3: // Expired filteredData = data - .where((item) => item.passwordStatus.value == "Expired") + .where((item) => item.passwordStatus.value == 'Expired') .toList(); break; default: diff --git a/lib/pages/access_management/bloc/access_state.dart b/lib/pages/access_management/bloc/access_state.dart index 0790a735..122e16ad 100644 --- a/lib/pages/access_management/bloc/access_state.dart +++ b/lib/pages/access_management/bloc/access_state.dart @@ -15,7 +15,7 @@ class AccessLoaded extends AccessState {} class FailedState extends AccessState { final String message; - FailedState(this.message); + const FailedState(this.message); @override List get props => [message]; diff --git a/lib/pages/access_management/model/password_model.dart b/lib/pages/access_management/model/password_model.dart index 0ce4426a..ccff1cb8 100644 --- a/lib/pages/access_management/model/password_model.dart +++ b/lib/pages/access_management/model/password_model.dart @@ -36,7 +36,7 @@ class PasswordModel { effectiveTime: json['effectiveTime'], passwordCreated: json['passwordCreated'], createdTime: json['createdTime'], - passwordName: json['passwordName']??'No Name', + passwordName: json['passwordName'] ?? 'No Name', passwordStatus: AccessStatusExtension.fromString(json['passwordStatus']), passwordType: AccessTypeExtension.fromString(json['passwordType']), deviceUuid: json['deviceUuid'], diff --git a/lib/pages/analytics/helpers/dashed_border_painter.dart b/lib/pages/analytics/helpers/dashed_border_painter.dart index 410cadfd..f32741fc 100644 --- a/lib/pages/analytics/helpers/dashed_border_painter.dart +++ b/lib/pages/analytics/helpers/dashed_border_painter.dart @@ -1,5 +1,3 @@ -import 'dart:ui'; - import 'package:flutter/material.dart'; class DashedBorderPainter extends CustomPainter { @@ -20,27 +18,28 @@ class DashedBorderPainter extends CustomPainter { ..strokeWidth = 0.5 ..style = PaintingStyle.stroke; - final Path topPath = Path() + final topPath = Path() ..moveTo(0, 0) ..lineTo(size.width, 0); - final Path bottomPath = Path() + final bottomPath = Path() ..moveTo(0, size.height) ..lineTo(size.width, size.height); final dashedTopPath = _createDashedPath(topPath, dashWidth, dashSpace); - final dashedBottomPath = _createDashedPath(bottomPath, dashWidth, dashSpace); + final dashedBottomPath = + _createDashedPath(bottomPath, dashWidth, dashSpace); canvas.drawPath(dashedTopPath, paint); canvas.drawPath(dashedBottomPath, paint); } Path _createDashedPath(Path source, double dashWidth, double dashSpace) { - final Path dashedPath = Path(); - for (PathMetric pathMetric in source.computeMetrics()) { - double distance = 0.0; + final dashedPath = Path(); + for (final pathMetric in source.computeMetrics()) { + var distance = 0.0; while (distance < pathMetric.length) { - final double nextDistance = distance + dashWidth; + final nextDistance = distance + dashWidth; dashedPath.addPath( pathMetric.extractPath(distance, nextDistance), Offset.zero, diff --git a/lib/pages/analytics/helpers/get_month_name_from_int.dart b/lib/pages/analytics/helpers/get_month_name_from_int.dart index 54b0fa87..0ee35a38 100644 --- a/lib/pages/analytics/helpers/get_month_name_from_int.dart +++ b/lib/pages/analytics/helpers/get_month_name_from_int.dart @@ -16,4 +16,4 @@ extension GetMonthNameFromNumber on num { _ => 'N/A' }; } -} \ No newline at end of file +} diff --git a/lib/pages/analytics/models/air_quality_data_model.dart b/lib/pages/analytics/models/air_quality_data_model.dart index 2eab2ddb..95de21c2 100644 --- a/lib/pages/analytics/models/air_quality_data_model.dart +++ b/lib/pages/analytics/models/air_quality_data_model.dart @@ -15,7 +15,8 @@ class AirQualityDataModel extends Equatable { return AirQualityDataModel( date: DateTime.parse(json['date'] as String), data: (json['data'] as List) - .map((e) => AirQualityPercentageData.fromJson(e as Map)) + .map((e) => + AirQualityPercentageData.fromJson(e as Map)) .toList(), ); } @@ -46,7 +47,7 @@ class AirQualityPercentageData extends Equatable { factory AirQualityPercentageData.fromJson(Map json) { return AirQualityPercentageData( - type: json['type'] as String? ?? '', + type: json['type'] as String? ?? '', name: json['name'] as String? ?? '', percentage: (json['percentage'] as num?)?.toDouble() ?? 0, ); diff --git a/lib/pages/analytics/models/analytics_device.dart b/lib/pages/analytics/models/analytics_device.dart index 3340a41d..0a36362a 100644 --- a/lib/pages/analytics/models/analytics_device.dart +++ b/lib/pages/analytics/models/analytics_device.dart @@ -36,11 +36,14 @@ class AnalyticsDevice { deviceTuyaUuid: json['deviceTuyaUuid'] as String?, isActive: json['isActive'] as bool?, productDevice: json['productDevice'] != null - ? ProductDevice.fromJson(json['productDevice'] as Map) + ? ProductDevice.fromJson( + json['productDevice'] as Map) : null, spaceUuid: json['spaceUuid'] as String?, - latitude: json['lat'] != null ? double.parse(json['lat'] as String) : null, - longitude: json['lon'] != null ? double.parse(json['lon'] as String) : null, + latitude: + json['lat'] != null ? double.parse(json['lat'] as String) : null, + longitude: + json['lon'] != null ? double.parse(json['lon'] as String) : null, ); } } diff --git a/lib/pages/analytics/models/occupacy.dart b/lib/pages/analytics/models/occupacy.dart index b4b8dac9..1d158869 100644 --- a/lib/pages/analytics/models/occupacy.dart +++ b/lib/pages/analytics/models/occupacy.dart @@ -15,7 +15,8 @@ class Occupacy extends Equatable { factory Occupacy.fromJson(Map json) { return Occupacy( - date: DateTime.parse(json['event_date'] as String? ?? '${DateTime.now()}'), + date: + DateTime.parse(json['event_date'] as String? ?? '${DateTime.now()}'), occupancy: (json['occupancy_percentage'] ?? 0).toString(), spaceUuid: json['space_uuid'] as String? ?? '', occupiedSeconds: json['occupied_seconds'] as int? ?? 0, diff --git a/lib/pages/analytics/models/occupancy_heat_map_model.dart b/lib/pages/analytics/models/occupancy_heat_map_model.dart index 73e7d5d7..a5fa3ba7 100644 --- a/lib/pages/analytics/models/occupancy_heat_map_model.dart +++ b/lib/pages/analytics/models/occupancy_heat_map_model.dart @@ -19,7 +19,8 @@ class OccupancyHeatMapModel extends Equatable { eventDate: DateTime.parse( json['event_date'] as String? ?? '${DateTime.now()}', ), - countTotalPresenceDetected: json['count_total_presence_detected'] as int? ?? 0, + countTotalPresenceDetected: + json['count_total_presence_detected'] as int? ?? 0, ); } diff --git a/lib/pages/analytics/modules/air_quality/blocs/air_quality_distribution/air_quality_distribution_bloc.dart b/lib/pages/analytics/modules/air_quality/blocs/air_quality_distribution/air_quality_distribution_bloc.dart index fb7e2352..6d9f1c52 100644 --- a/lib/pages/analytics/modules/air_quality/blocs/air_quality_distribution/air_quality_distribution_bloc.dart +++ b/lib/pages/analytics/modules/air_quality/blocs/air_quality_distribution/air_quality_distribution_bloc.dart @@ -33,7 +33,8 @@ class AirQualityDistributionBloc state.copyWith( status: AirQualityDistributionStatus.success, chartData: result, - filteredChartData: _arrangeChartDataByType(result, state.selectedAqiType), + filteredChartData: + _arrangeChartDataByType(result, state.selectedAqiType), ), ); } catch (e) { @@ -61,7 +62,8 @@ class AirQualityDistributionBloc emit( state.copyWith( selectedAqiType: event.aqiType, - filteredChartData: _arrangeChartDataByType(state.chartData, event.aqiType), + filteredChartData: + _arrangeChartDataByType(state.chartData, event.aqiType), ), ); } diff --git a/lib/pages/analytics/modules/air_quality/blocs/device_location/device_location_bloc.dart b/lib/pages/analytics/modules/air_quality/blocs/device_location/device_location_bloc.dart index 4f41eb0c..9bac8120 100644 --- a/lib/pages/analytics/modules/air_quality/blocs/device_location/device_location_bloc.dart +++ b/lib/pages/analytics/modules/air_quality/blocs/device_location/device_location_bloc.dart @@ -7,7 +7,8 @@ import 'package:syncrow_web/pages/analytics/services/device_location/device_loca part 'device_location_event.dart'; part 'device_location_state.dart'; -class DeviceLocationBloc extends Bloc { +class DeviceLocationBloc + extends Bloc { DeviceLocationBloc( this._deviceLocationService, ) : super(const DeviceLocationState()) { diff --git a/lib/pages/analytics/modules/air_quality/blocs/range_of_aqi/range_of_aqi_bloc.dart b/lib/pages/analytics/modules/air_quality/blocs/range_of_aqi/range_of_aqi_bloc.dart index 88c3715e..cb959051 100644 --- a/lib/pages/analytics/modules/air_quality/blocs/range_of_aqi/range_of_aqi_bloc.dart +++ b/lib/pages/analytics/modules/air_quality/blocs/range_of_aqi/range_of_aqi_bloc.dart @@ -53,7 +53,8 @@ class RangeOfAqiBloc extends Bloc { emit( state.copyWith( selectedAqiType: event.aqiType, - filteredRangeOfAqi: _arrangeChartDataByType(state.rangeOfAqi, event.aqiType), + filteredRangeOfAqi: + _arrangeChartDataByType(state.rangeOfAqi, event.aqiType), ), ); } diff --git a/lib/pages/analytics/modules/air_quality/helpers/range_of_aqi_charts_helper.dart b/lib/pages/analytics/modules/air_quality/helpers/range_of_aqi_charts_helper.dart index 21cb2a9e..889936c4 100644 --- a/lib/pages/analytics/modules/air_quality/helpers/range_of_aqi_charts_helper.dart +++ b/lib/pages/analytics/modules/air_quality/helpers/range_of_aqi_charts_helper.dart @@ -105,7 +105,8 @@ abstract final class RangeOfAqiChartsHelper { tooltipRoundedRadius: 16, showOnTopOfTheChartBoxArea: false, tooltipPadding: const EdgeInsets.all(8), - getTooltipItems: (touchedSpots) => RangeOfAqiChartsHelper.getTooltipItems( + getTooltipItems: (touchedSpots) => + RangeOfAqiChartsHelper.getTooltipItems( touchedSpots, chartData, ), diff --git a/lib/pages/analytics/modules/air_quality/widgets/aqi_device_info.dart b/lib/pages/analytics/modules/air_quality/widgets/aqi_device_info.dart index ebe88614..634c86ab 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/aqi_device_info.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/aqi_device_info.dart @@ -81,7 +81,8 @@ class AqiDeviceInfo extends StatelessWidget { aqiLevel: status .firstWhere( (e) => e.code == 'air_quality_index', - orElse: () => Status(code: 'air_quality_index', value: ''), + orElse: () => + Status(code: 'air_quality_index', value: ''), ) .value .toString(), diff --git a/lib/pages/analytics/modules/air_quality/widgets/aqi_distribution_chart.dart b/lib/pages/analytics/modules/air_quality/widgets/aqi_distribution_chart.dart index 373e36ca..36346cb6 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/aqi_distribution_chart.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/aqi_distribution_chart.dart @@ -36,23 +36,25 @@ class AqiDistributionChart extends StatelessWidget { ); } - List _buildBarGroups(List sortedData) { + List _buildBarGroups( + List sortedData) { return List.generate(sortedData.length, (index) { final data = sortedData[index]; final stackItems = []; double currentY = 0; - bool isFirstElement = true; + var isFirstElement = true; // Sort data by type to ensure consistent order - final sortedPercentageData = List.from(data.data) - ..sort((a, b) => a.type.compareTo(b.type)); + final sortedPercentageData = + List.from(data.data) + ..sort((a, b) => a.type.compareTo(b.type)); for (final percentageData in sortedPercentageData) { stackItems.add( BarChartRodData( fromY: currentY, - toY: currentY + percentageData.percentage , - color: AirQualityDataModel.metricColors[percentageData.name]!, + toY: currentY + percentageData.percentage, + color: AirQualityDataModel.metricColors[percentageData.name], borderRadius: isFirstElement ? const BorderRadius.only( topLeft: Radius.circular(22), @@ -84,9 +86,9 @@ class AqiDistributionChart extends StatelessWidget { tooltipRoundedRadius: 16, tooltipPadding: const EdgeInsets.all(8), getTooltipItem: (group, groupIndex, rod, rodIndex) { - final data = chartData[group.x.toInt()]; + final data = chartData[group.x]; - final List children = []; + final children = []; final textStyle = context.textTheme.bodySmall?.copyWith( color: ColorsManager.blackColor, @@ -94,8 +96,9 @@ class AqiDistributionChart extends StatelessWidget { ); // Sort data by type to ensure consistent order - final sortedPercentageData = List.from(data.data) - ..sort((a, b) => a.type.compareTo(b.type)); + final sortedPercentageData = + List.from(data.data) + ..sort((a, b) => a.type.compareTo(b.type)); for (final percentageData in sortedPercentageData) { children.add(TextSpan( diff --git a/lib/pages/analytics/modules/air_quality/widgets/aqi_sub_value_widget.dart b/lib/pages/analytics/modules/air_quality/widgets/aqi_sub_value_widget.dart index 5a8e6e6c..6f2eb198 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/aqi_sub_value_widget.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/aqi_sub_value_widget.dart @@ -49,7 +49,7 @@ class AqiSubValueWidget extends StatelessWidget { int _getActiveSegmentByRange(double value, (double min, double max) range) { final ranges = _getRangesForValue(range); - for (int i = 0; i < ranges.length; i++) { + for (var i = 0; i < ranges.length; i++) { if (value <= ranges[i].max) return i; } return ranges.length - 1; diff --git a/lib/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart b/lib/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart index 60a686ff..242c5d4b 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart @@ -29,7 +29,8 @@ class AqiTypeDropdown extends StatefulWidget { class _AqiTypeDropdownState extends State { AqiType? _selectedItem = AqiType.aqi; - void _updateSelectedItem(AqiType? item) => setState(() => _selectedItem = item); + void _updateSelectedItem(AqiType? item) => + setState(() => _selectedItem = item); @override Widget build(BuildContext context) { diff --git a/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart.dart b/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart.dart index fc63e413..a392dc2e 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart.dart @@ -63,7 +63,7 @@ class RangeOfAqiChart extends StatelessWidget { gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, - stops: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], + stops: const [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], colors: RangeOfAqiChartsHelper.gradientData.map((e) { final (color, _) = e; return color.withValues(alpha: 0.6); @@ -99,7 +99,8 @@ class RangeOfAqiChart extends StatelessWidget { }) { const invisibleDot = FlDotData(show: false); return LineChartBarData( - spots: List.generate(values.length, (i) => FlSpot(i.toDouble(), values[i])), + spots: + List.generate(values.length, (i) => FlSpot(i.toDouble(), values[i])), isCurved: true, color: color, barWidth: 4, diff --git a/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart_box.dart b/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart_box.dart index 6548c696..3885ffc2 100644 --- a/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart_box.dart +++ b/lib/pages/analytics/modules/air_quality/widgets/range_of_aqi_chart_box.dart @@ -32,7 +32,8 @@ class RangeOfAqiChartBox extends StatelessWidget { const SizedBox(height: 10), const Divider(), const SizedBox(height: 20), - Expanded(child: RangeOfAqiChart(chartData: state.filteredRangeOfAqi)), + Expanded( + child: RangeOfAqiChart(chartData: state.filteredRangeOfAqi)), ], ), ); diff --git a/lib/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_event.dart b/lib/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_event.dart index fb61e73b..723df1c3 100644 --- a/lib/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_event.dart +++ b/lib/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_event.dart @@ -8,7 +8,8 @@ sealed class AnalyticsDevicesEvent extends Equatable { } final class LoadAnalyticsDevicesEvent extends AnalyticsDevicesEvent { - const LoadAnalyticsDevicesEvent({required this.param, required this.onSuccess}); + const LoadAnalyticsDevicesEvent( + {required this.param, required this.onSuccess}); final GetAnalyticsDevicesParam param; final void Function(AnalyticsDevice device) onSuccess; diff --git a/lib/pages/analytics/modules/analytics/blocs/analytics_tab/analytics_tab_event.dart b/lib/pages/analytics/modules/analytics/blocs/analytics_tab/analytics_tab_event.dart index 0ae7d8c5..20eddb43 100644 --- a/lib/pages/analytics/modules/analytics/blocs/analytics_tab/analytics_tab_event.dart +++ b/lib/pages/analytics/modules/analytics/blocs/analytics_tab/analytics_tab_event.dart @@ -7,7 +7,7 @@ sealed class AnalyticsTabEvent extends Equatable { List get props => []; } -class UpdateAnalyticsTabEvent extends AnalyticsTabEvent { +class UpdateAnalyticsTabEvent extends AnalyticsTabEvent { const UpdateAnalyticsTabEvent(this.analyticsTab); final AnalyticsPageTab analyticsTab; diff --git a/lib/pages/analytics/modules/analytics/strategies/air_quality_data_loading_strategy.dart b/lib/pages/analytics/modules/analytics/strategies/air_quality_data_loading_strategy.dart index 8b1802af..2614ea28 100644 --- a/lib/pages/analytics/modules/analytics/strategies/air_quality_data_loading_strategy.dart +++ b/lib/pages/analytics/modules/analytics/strategies/air_quality_data_loading_strategy.dart @@ -8,7 +8,8 @@ import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; -final class AirQualityDataLoadingStrategy implements AnalyticsDataLoadingStrategy { +final class AirQualityDataLoadingStrategy + implements AnalyticsDataLoadingStrategy { @override void onCommunitySelected( BuildContext context, @@ -25,7 +26,8 @@ final class AirQualityDataLoadingStrategy implements AnalyticsDataLoadingStrateg SpaceModel space, ) { final spaceTreeBloc = context.read(); - final isSpaceSelected = spaceTreeBloc.state.selectedSpaces.contains(space.uuid); + final isSpaceSelected = + spaceTreeBloc.state.selectedSpaces.contains(space.uuid); final hasSelectedSpaces = spaceTreeBloc.state.selectedSpaces.isNotEmpty; if (hasSelectedSpaces) clearData(context); @@ -34,7 +36,7 @@ final class AirQualityDataLoadingStrategy implements AnalyticsDataLoadingStrateg spaceTreeBloc ..add(const SpaceTreeClearSelectionEvent()) - ..add(OnSpaceSelected(community, space.uuid ?? '', [])); + ..add(OnSpaceSelected(community, space.uuid ?? '', const [])); FetchAirQualityDataHelper.loadAirQualityData( context, diff --git a/lib/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy_factory.dart b/lib/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy_factory.dart index 19b0aff2..f48fd7f2 100644 --- a/lib/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy_factory.dart +++ b/lib/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy_factory.dart @@ -8,7 +8,8 @@ abstract final class AnalyticsDataLoadingStrategyFactory { const AnalyticsDataLoadingStrategyFactory._(); static AnalyticsDataLoadingStrategy getStrategy(AnalyticsPageTab tab) { return switch (tab) { - AnalyticsPageTab.energyManagement => EnergyManagementDataLoadingStrategy(), + AnalyticsPageTab.energyManagement => + EnergyManagementDataLoadingStrategy(), AnalyticsPageTab.occupancy => OccupancyDataLoadingStrategy(), AnalyticsPageTab.airQuality => AirQualityDataLoadingStrategy(), }; diff --git a/lib/pages/analytics/modules/analytics/strategies/energy_management_data_loading_strategy.dart b/lib/pages/analytics/modules/analytics/strategies/energy_management_data_loading_strategy.dart index 757b2a9a..14e27515 100644 --- a/lib/pages/analytics/modules/analytics/strategies/energy_management_data_loading_strategy.dart +++ b/lib/pages/analytics/modules/analytics/strategies/energy_management_data_loading_strategy.dart @@ -7,7 +7,8 @@ import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; -class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrategy { +class EnergyManagementDataLoadingStrategy + implements AnalyticsDataLoadingStrategy { @override void onCommunitySelected( BuildContext context, @@ -31,7 +32,8 @@ class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrateg SpaceModel space, ) { final spaceTreeBloc = context.read(); - final isSpaceSelected = spaceTreeBloc.state.selectedSpaces.contains(space.uuid); + final isSpaceSelected = + spaceTreeBloc.state.selectedSpaces.contains(space.uuid); final hasSelectedSpaces = spaceTreeBloc.state.selectedSpaces.isNotEmpty; if (isSpaceSelected) { diff --git a/lib/pages/analytics/modules/analytics/strategies/occupancy_data_loading_strategy.dart b/lib/pages/analytics/modules/analytics/strategies/occupancy_data_loading_strategy.dart index 9bffe3b4..e7055b61 100644 --- a/lib/pages/analytics/modules/analytics/strategies/occupancy_data_loading_strategy.dart +++ b/lib/pages/analytics/modules/analytics/strategies/occupancy_data_loading_strategy.dart @@ -24,7 +24,8 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy { SpaceModel space, ) { final spaceTreeBloc = context.read(); - final isSpaceSelected = spaceTreeBloc.state.selectedSpaces.contains(space.uuid); + final isSpaceSelected = + spaceTreeBloc.state.selectedSpaces.contains(space.uuid); final hasSelectedSpaces = spaceTreeBloc.state.selectedSpaces.isNotEmpty; if (hasSelectedSpaces) clearData(context); @@ -33,7 +34,7 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy { spaceTreeBloc ..add(const SpaceTreeClearSelectionEvent()) - ..add(OnSpaceSelected(community, space.uuid ?? '', [])); + ..add(OnSpaceSelected(community, space.uuid ?? '', const [])); FetchOccupancyDataHelper.loadOccupancyData( context, diff --git a/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart b/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart index ab07737a..a8b43943 100644 --- a/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart +++ b/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart @@ -10,7 +10,8 @@ class AnalyticsCommunitiesSidebar extends StatelessWidget { @override Widget build(BuildContext context) { final selectedTab = context.watch().state; - final strategy = AnalyticsDataLoadingStrategyFactory.getStrategy(selectedTab); + final strategy = + AnalyticsDataLoadingStrategyFactory.getStrategy(selectedTab); return Expanded( child: AnalyticsSpaceTreeView( diff --git a/lib/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart b/lib/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart index af70cd86..ab41c7d7 100644 --- a/lib/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart +++ b/lib/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart @@ -20,7 +20,7 @@ class AnalyticsDateFilterButton extends StatefulWidget { final void Function(DateTime)? onDateSelected; final DatePickerType datePickerType; - static final _color = ColorsManager.blackColor.withValues(alpha: 0.8); + static final Color _color = ColorsManager.blackColor.withValues(alpha: 0.8); @override State createState() => diff --git a/lib/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart b/lib/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart index 9ff98ef2..abc688fc 100644 --- a/lib/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart +++ b/lib/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart @@ -21,8 +21,8 @@ class AnalyticsPageTabButton extends StatelessWidget { onPressed: () { AnalyticsDataLoadingStrategyFactory.getStrategy(tab).clearData(context); context.read().add( - UpdateAnalyticsTabEvent(tab), - ); + UpdateAnalyticsTabEvent(tab), + ); }, child: Text( tab.title, @@ -33,8 +33,9 @@ class AnalyticsPageTabButton extends StatelessWidget { style: TextStyle( fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400, fontSize: 16, - color: - isSelected ? ColorsManager.slidingBlueColor : ColorsManager.textGray, + color: isSelected + ? ColorsManager.slidingBlueColor + : ColorsManager.textGray, ), ), ); diff --git a/lib/pages/analytics/modules/analytics/widgets/month_picker_widget.dart b/lib/pages/analytics/modules/analytics/widgets/month_picker_widget.dart index 57133b02..41dcd108 100644 --- a/lib/pages/analytics/modules/analytics/widgets/month_picker_widget.dart +++ b/lib/pages/analytics/modules/analytics/widgets/month_picker_widget.dart @@ -21,18 +21,18 @@ class _MonthPickerWidgetState extends State { int? _selectedMonth; static const _monthNames = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December', ]; @override @@ -189,14 +189,19 @@ class _MonthPickerWidgetState extends State { final isFutureMonth = isCurrentYear && index > currentDate.month - 1; return InkWell( - onTap: isFutureMonth ? null : () => setState(() => _selectedMonth = index), + onTap: isFutureMonth + ? null + : () => setState(() => _selectedMonth = index), child: DecoratedBox( decoration: BoxDecoration( color: const Color(0xFFEDF2F7), borderRadius: BorderRadius.only( - topLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero, - bottomLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero, - topRight: index % 3 == 2 ? const Radius.circular(16) : Radius.zero, + topLeft: + index % 3 == 0 ? const Radius.circular(16) : Radius.zero, + bottomLeft: + index % 3 == 0 ? const Radius.circular(16) : Radius.zero, + topRight: + index % 3 == 2 ? const Radius.circular(16) : Radius.zero, bottomRight: index % 3 == 2 ? const Radius.circular(16) : Radius.zero, ), diff --git a/lib/pages/analytics/modules/analytics/widgets/sidebar/analytics_space_tree_view.dart b/lib/pages/analytics/modules/analytics/widgets/sidebar/analytics_space_tree_view.dart index f900a040..9521ab24 100644 --- a/lib/pages/analytics/modules/analytics/widgets/sidebar/analytics_space_tree_view.dart +++ b/lib/pages/analytics/modules/analytics/widgets/sidebar/analytics_space_tree_view.dart @@ -53,7 +53,8 @@ class _AnalyticsSpaceTreeViewState extends State { @override Widget build(BuildContext context) { - return BlocBuilder(builder: (context, state) { + return BlocBuilder( + builder: (context, state) { final communities = state.searchQuery.isNotEmpty ? state.filteredCommunity : state.communityList; @@ -76,9 +77,10 @@ class _AnalyticsSpaceTreeViewState extends State { ), ), CustomSearchBar( - onSearchChanged: (query) => context.read().add( - SearchQueryEvent(query), - ), + onSearchChanged: (query) => + context.read().add( + SearchQueryEvent(query), + ), ), const SizedBox(height: 16), Expanded( @@ -113,7 +115,8 @@ class _AnalyticsSpaceTreeViewState extends State { isExpanded: state.expandedCommunities.contains( communities[index].uuid, ), - onItemSelected: () => widget.onSelectCommunity?.call( + onItemSelected: () => + widget.onSelectCommunity?.call( communities[index], communities[index].spaces, ), @@ -121,8 +124,8 @@ class _AnalyticsSpaceTreeViewState extends State { (space) { return CustomExpansionTileSpaceTree( title: space.name, - isExpanded: - state.expandedSpaces.contains(space.uuid), + isExpanded: state.expandedSpaces + .contains(space.uuid), onItemSelected: () => widget.onSelectSpace?.call( communities[index], @@ -153,7 +156,8 @@ class _AnalyticsSpaceTreeViewState extends State { }, ), ), - if (state.paginationIsLoading) const CircularProgressIndicator(), + if (state.paginationIsLoading) + const CircularProgressIndicator(), ], ), ); diff --git a/lib/pages/analytics/modules/analytics/widgets/year_picker_widget.dart b/lib/pages/analytics/modules/analytics/widgets/year_picker_widget.dart index 22eb6646..711d1ccd 100644 --- a/lib/pages/analytics/modules/analytics/widgets/year_picker_widget.dart +++ b/lib/pages/analytics/modules/analytics/widgets/year_picker_widget.dart @@ -19,9 +19,9 @@ class YearPickerWidget extends StatefulWidget { class _YearPickerWidgetState extends State { late int _currentYear; - static final years = List.generate( + static final List years = List.generate( DateTime.now().year - (DateTime.now().year - 5) + 1, - (index) => (2020 + index), + (index) => 2020 + index, ).where((year) => year <= DateTime.now().year).toList(); @override @@ -123,9 +123,12 @@ class _YearPickerWidgetState extends State { decoration: BoxDecoration( color: const Color(0xFFEDF2F7), borderRadius: BorderRadius.only( - topLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero, - bottomLeft: index % 3 == 0 ? const Radius.circular(16) : Radius.zero, - topRight: index % 3 == 2 ? const Radius.circular(16) : Radius.zero, + topLeft: + index % 3 == 0 ? const Radius.circular(16) : Radius.zero, + bottomLeft: + index % 3 == 0 ? const Radius.circular(16) : Radius.zero, + topRight: + index % 3 == 2 ? const Radius.circular(16) : Radius.zero, bottomRight: index % 3 == 2 ? const Radius.circular(16) : Radius.zero, ), diff --git a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_bloc.dart b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_bloc.dart index 1acf7df5..a3f21f44 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_bloc.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_bloc.dart @@ -8,13 +8,15 @@ import 'package:syncrow_web/services/api/api_exception.dart'; part 'energy_consumption_by_phases_event.dart'; part 'energy_consumption_by_phases_state.dart'; -class EnergyConsumptionByPhasesBloc - extends Bloc { +class EnergyConsumptionByPhasesBloc extends Bloc { EnergyConsumptionByPhasesBloc( this._energyConsumptionByPhasesService, ) : super(const EnergyConsumptionByPhasesState()) { - on(_onLoadEnergyConsumptionByPhasesEvent); - on(_onClearEnergyConsumptionByPhasesEvent); + on( + _onLoadEnergyConsumptionByPhasesEvent); + on( + _onClearEnergyConsumptionByPhasesEvent); } final EnergyConsumptionByPhasesService _energyConsumptionByPhasesService; @@ -25,7 +27,8 @@ class EnergyConsumptionByPhasesBloc ) async { emit(state.copyWith(status: EnergyConsumptionByPhasesStatus.loading)); try { - final chartData = await _energyConsumptionByPhasesService.load(event.param); + final chartData = + await _energyConsumptionByPhasesService.load(event.param); emit( state.copyWith( status: EnergyConsumptionByPhasesStatus.loaded, @@ -49,7 +52,7 @@ class EnergyConsumptionByPhasesBloc } } - void _onClearEnergyConsumptionByPhasesEvent( + Future _onClearEnergyConsumptionByPhasesEvent( ClearEnergyConsumptionByPhasesEvent event, Emitter emit, ) async { diff --git a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_event.dart b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_event.dart index 87bcf447..0c1248ae 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_event.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_by_phases/energy_consumption_by_phases_event.dart @@ -7,7 +7,8 @@ sealed class EnergyConsumptionByPhasesEvent extends Equatable { List get props => []; } -class LoadEnergyConsumptionByPhasesEvent extends EnergyConsumptionByPhasesEvent { +class LoadEnergyConsumptionByPhasesEvent + extends EnergyConsumptionByPhasesEvent { const LoadEnergyConsumptionByPhasesEvent({ required this.param, }); @@ -18,6 +19,7 @@ class LoadEnergyConsumptionByPhasesEvent extends EnergyConsumptionByPhasesEvent List get props => [param]; } -final class ClearEnergyConsumptionByPhasesEvent extends EnergyConsumptionByPhasesEvent { +final class ClearEnergyConsumptionByPhasesEvent + extends EnergyConsumptionByPhasesEvent { const ClearEnergyConsumptionByPhasesEvent(); } diff --git a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_per_device/energy_consumption_per_device_bloc.dart b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_per_device/energy_consumption_per_device_bloc.dart index 97d182c5..3f0806a1 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_per_device/energy_consumption_per_device_bloc.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/energy_consumption_per_device/energy_consumption_per_device_bloc.dart @@ -8,12 +8,13 @@ import 'package:syncrow_web/services/api/api_exception.dart'; part 'energy_consumption_per_device_event.dart'; part 'energy_consumption_per_device_state.dart'; -class EnergyConsumptionPerDeviceBloc - extends Bloc { +class EnergyConsumptionPerDeviceBloc extends Bloc< + EnergyConsumptionPerDeviceEvent, EnergyConsumptionPerDeviceState> { EnergyConsumptionPerDeviceBloc( this._energyConsumptionPerDeviceService, ) : super(const EnergyConsumptionPerDeviceState()) { - on(_onLoadEnergyConsumptionPerDeviceEvent); + on( + _onLoadEnergyConsumptionPerDeviceEvent); on( _onClearEnergyConsumptionPerDeviceEvent); } @@ -26,7 +27,8 @@ class EnergyConsumptionPerDeviceBloc ) async { emit(state.copyWith(status: EnergyConsumptionPerDeviceStatus.loading)); try { - final chartData = await _energyConsumptionPerDeviceService.load(event.param); + final chartData = + await _energyConsumptionPerDeviceService.load(event.param); emit( state.copyWith( status: EnergyConsumptionPerDeviceStatus.loaded, @@ -50,7 +52,7 @@ class EnergyConsumptionPerDeviceBloc } } - void _onClearEnergyConsumptionPerDeviceEvent( + Future _onClearEnergyConsumptionPerDeviceEvent( ClearEnergyConsumptionPerDeviceEvent event, Emitter emit, ) async { diff --git a/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_bloc.dart b/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_bloc.dart index 2aefd798..aa37078b 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_bloc.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_bloc.dart @@ -8,7 +8,8 @@ import 'package:syncrow_web/services/api/api_exception.dart'; part 'power_clamp_info_event.dart'; part 'power_clamp_info_state.dart'; -class PowerClampInfoBloc extends Bloc { +class PowerClampInfoBloc + extends Bloc { PowerClampInfoBloc( this._powerClampInfoService, ) : super(const PowerClampInfoState()) { @@ -25,7 +26,8 @@ class PowerClampInfoBloc extends Bloc ) async { emit(state.copyWith(status: PowerClampInfoStatus.loading)); try { - final powerClampModel = await _powerClampInfoService.getInfo(event.deviceId); + final powerClampModel = + await _powerClampInfoService.getInfo(event.deviceId); emit( state.copyWith( status: PowerClampInfoStatus.loaded, @@ -49,7 +51,7 @@ class PowerClampInfoBloc extends Bloc } } - void _onUpdatePowerClampStatusEvent( + Future _onUpdatePowerClampStatusEvent( UpdatePowerClampStatusEvent event, Emitter emit, ) async { diff --git a/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_event.dart b/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_event.dart index b69a2556..dc20f6f7 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_event.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/power_clamp_info/power_clamp_info_event.dart @@ -16,7 +16,6 @@ final class LoadPowerClampInfoEvent extends PowerClampInfoEvent { List get props => [deviceId]; } - final class UpdatePowerClampStatusEvent extends PowerClampInfoEvent { const UpdatePowerClampStatusEvent(this.statusList); @@ -28,4 +27,4 @@ final class UpdatePowerClampStatusEvent extends PowerClampInfoEvent { final class ClearPowerClampInfoEvent extends PowerClampInfoEvent { const ClearPowerClampInfoEvent(); -} \ No newline at end of file +} diff --git a/lib/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_event.dart b/lib/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_event.dart index 1eba8f7e..c56588b8 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_event.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_event.dart @@ -24,4 +24,4 @@ class _RealtimeDeviceChangesUpdated extends RealtimeDeviceChangesEvent { final List deviceStatusList; const _RealtimeDeviceChangesUpdated(this.deviceStatusList); -} \ No newline at end of file +} diff --git a/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_bloc.dart b/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_bloc.dart index f51d20cf..578899f9 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_bloc.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_bloc.dart @@ -49,7 +49,7 @@ class TotalEnergyConsumptionBloc } } - void _onClearTotalEnergyConsumptionEvent( + Future _onClearTotalEnergyConsumptionEvent( ClearTotalEnergyConsumptionEvent event, Emitter emit, ) async { diff --git a/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_event.dart b/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_event.dart index f9510737..7240b669 100644 --- a/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_event.dart +++ b/lib/pages/analytics/modules/energy_management/blocs/total_energy_consumption/total_energy_consumption_event.dart @@ -7,7 +7,8 @@ sealed class TotalEnergyConsumptionEvent extends Equatable { List get props => []; } -final class TotalEnergyConsumptionLoadEvent extends TotalEnergyConsumptionEvent { +final class TotalEnergyConsumptionLoadEvent + extends TotalEnergyConsumptionEvent { const TotalEnergyConsumptionLoadEvent({required this.param}); final GetTotalEnergyConsumptionParam param; @@ -16,6 +17,7 @@ final class TotalEnergyConsumptionLoadEvent extends TotalEnergyConsumptionEvent List get props => [param]; } -final class ClearTotalEnergyConsumptionEvent extends TotalEnergyConsumptionEvent { +final class ClearTotalEnergyConsumptionEvent + extends TotalEnergyConsumptionEvent { const ClearTotalEnergyConsumptionEvent(); } diff --git a/lib/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart b/lib/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart index 2ed68e76..6de1e278 100644 --- a/lib/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart +++ b/lib/pages/analytics/modules/energy_management/helpers/energy_management_charts_helper.dart @@ -69,7 +69,8 @@ abstract final class EnergyManagementChartsHelper { return labels.where((element) => element.isNotEmpty).join(', '); } - static List getTooltipItems(List touchedSpots) { + static List getTooltipItems( + List touchedSpots) { return touchedSpots.map((spot) { return LineTooltipItem( getToolTipLabel(spot.x, spot.y), @@ -85,7 +86,8 @@ abstract final class EnergyManagementChartsHelper { static LineTouchTooltipData lineTouchTooltipData() { return LineTouchTooltipData( getTooltipColor: (touchTooltipItem) => ColorsManager.whiteColors, - tooltipBorder: const BorderSide(color: ColorsManager.semiTransparentBlack), + tooltipBorder: + const BorderSide(color: ColorsManager.semiTransparentBlack), tooltipRoundedRadius: 16, showOnTopOfTheChartBoxArea: false, tooltipPadding: const EdgeInsets.all(8), diff --git a/lib/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart b/lib/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart index 8de92098..f2796671 100644 --- a/lib/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart +++ b/lib/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart @@ -122,7 +122,8 @@ abstract final class FetchEnergyManagementDataHelper { final selectedDevice = getSelectedDevice(context); context.read().add( - RealtimeDeviceChangesStarted(deviceUuid ?? selectedDevice?.uuid ?? ''), + RealtimeDeviceChangesStarted( + deviceUuid ?? selectedDevice?.uuid ?? ''), ); } diff --git a/lib/pages/analytics/modules/energy_management/views/analytics_energy_management_view.dart b/lib/pages/analytics/modules/energy_management/views/analytics_energy_management_view.dart index f88febcc..797821a4 100644 --- a/lib/pages/analytics/modules/energy_management/views/analytics_energy_management_view.dart +++ b/lib/pages/analytics/modules/energy_management/views/analytics_energy_management_view.dart @@ -51,7 +51,8 @@ class AnalyticsEnergyManagementView extends StatelessWidget { spacing: 20, children: [ Expanded(child: TotalEnergyConsumptionChartBox()), - Expanded(child: EnergyConsumptionPerDeviceChartBox()), + Expanded( + child: EnergyConsumptionPerDeviceChartBox()), ], ), ), diff --git a/lib/pages/analytics/modules/energy_management/widgets/analytics_device_dropdown.dart b/lib/pages/analytics/modules/energy_management/widgets/analytics_device_dropdown.dart index f7b33309..5d7f37a9 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/analytics_device_dropdown.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/analytics_device_dropdown.dart @@ -52,7 +52,8 @@ class AnalyticsDeviceDropdown extends StatelessWidget { ); } - Widget _buildDevicesDropdown(BuildContext context, AnalyticsDevicesState state) { + Widget _buildDevicesDropdown( + BuildContext context, AnalyticsDevicesState state) { final spaceUuid = state.selectedDevice?.spaceUuid; return DropdownButton( value: state.selectedDevice, diff --git a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart.dart b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart.dart index 52c6f591..e169d660 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart.dart @@ -18,7 +18,6 @@ class EnergyConsumptionByPhasesChart extends StatelessWidget { Widget build(BuildContext context) { return BarChart( BarChartData( - gridData: EnergyManagementChartsHelper.gridData().copyWith( checkToShowHorizontalLine: (value) => true, horizontalInterval: 250, @@ -100,11 +99,11 @@ class EnergyConsumptionByPhasesChart extends StatelessWidget { }) { final data = energyData; - final date = DateFormat('dd/MM/yyyy').format(data[group.x.toInt()].date); - final phaseA = data[group.x.toInt()].energyConsumedA; - final phaseB = data[group.x.toInt()].energyConsumedB; - final phaseC = data[group.x.toInt()].energyConsumedC; - final total = data[group.x.toInt()].energyConsumedKw; + final date = DateFormat('dd/MM/yyyy').format(data[group.x].date); + final phaseA = data[group.x].energyConsumedA; + final phaseB = data[group.x].energyConsumedB; + final phaseC = data[group.x].energyConsumedC; + final total = data[group.x].energyConsumedKw; return BarTooltipItem( '$date\n', diff --git a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart_box.dart b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart_box.dart index 1bd1ed9e..0c4e972d 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart_box.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_by_phases_chart_box.dart @@ -22,7 +22,8 @@ class EnergyConsumptionByPhasesChartBox extends StatelessWidget { children: [ AnalyticsErrorWidget(state.errorMessage), EnergyConsumptionByPhasesTitle( - isLoading: state.status == EnergyConsumptionByPhasesStatus.loading, + isLoading: + state.status == EnergyConsumptionByPhasesStatus.loading, ), const SizedBox(height: 20), Expanded( diff --git a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart.dart b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart.dart index 1e74ad31..4bed5682 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart.dart @@ -17,7 +17,6 @@ class EnergyConsumptionPerDeviceChart extends StatelessWidget { context, leftTitlesInterval: 250, ), - gridData: EnergyManagementChartsHelper.gridData().copyWith( checkToShowHorizontalLine: (value) => true, horizontalInterval: 250, diff --git a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart_box.dart b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart_box.dart index be5faf57..5fd6b8d6 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart_box.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart_box.dart @@ -46,7 +46,8 @@ class EnergyConsumptionPerDeviceChartBox extends StatelessWidget { flex: 2, child: EnergyConsumptionPerDeviceDevicesList( chartData: state.chartData, - devices: context.watch().state.devices, + devices: + context.watch().state.devices, ), ), ], @@ -55,7 +56,8 @@ class EnergyConsumptionPerDeviceChartBox extends StatelessWidget { const Divider(height: 0), const SizedBox(height: 20), Expanded( - child: EnergyConsumptionPerDeviceChart(chartData: state.chartData), + child: + EnergyConsumptionPerDeviceChart(chartData: state.chartData), ), ], ), diff --git a/lib/pages/analytics/modules/energy_management/widgets/power_clamp_energy_data_widget.dart b/lib/pages/analytics/modules/energy_management/widgets/power_clamp_energy_data_widget.dart index f95ff7d1..3feda916 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/power_clamp_energy_data_widget.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/power_clamp_energy_data_widget.dart @@ -43,11 +43,14 @@ class PowerClampEnergyDataWidget extends StatelessWidget { title: 'Smart Power Clamp', showSpaceUuidInDevicesDropdown: true, onChanged: (device) { - FetchEnergyManagementDataHelper.loadEnergyConsumptionByPhases( + FetchEnergyManagementDataHelper + .loadEnergyConsumptionByPhases( context, powerClampUuid: device.uuid, - selectedDate: - context.read().state.monthlyDate, + selectedDate: context + .read() + .state + .monthlyDate, ); }, ), @@ -91,7 +94,8 @@ class PowerClampEnergyDataWidget extends StatelessWidget { ), ), const SizedBox(height: 14), - const Expanded(flex: 3, child: EnergyConsumptionByPhasesChartBox()), + const Expanded( + flex: 3, child: EnergyConsumptionByPhasesChartBox()), ], ), ); diff --git a/lib/pages/analytics/modules/energy_management/widgets/power_clamp_phases_data_widget.dart b/lib/pages/analytics/modules/energy_management/widgets/power_clamp_phases_data_widget.dart index a96a7298..e1cc4238 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/power_clamp_phases_data_widget.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/power_clamp_phases_data_widget.dart @@ -140,9 +140,9 @@ class PowerClampPhasesDataWidget extends StatelessWidget { String _formatCurrentValue(String? value) { if (value == null) return '--'; - String str = value; + var str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp(r'[^0-9]'), ''); + str = str.replaceAll(RegExp('[^0-9]'), ''); if (str.isEmpty) return '--'; if (str.length == 1) return '${str[0]}.0'; return '${str[0]}.${str.substring(1)}'; @@ -150,9 +150,9 @@ class PowerClampPhasesDataWidget extends StatelessWidget { String _formatPowerFactor(String? value) { if (value == null) return '--'; - String str = value; + var str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp(r'[^0-9]'), ''); + str = str.replaceAll(RegExp('[^0-9]'), ''); if (str.isEmpty) return '--'; final intValue = int.tryParse(str); if (intValue == null) return '--'; @@ -162,9 +162,9 @@ class PowerClampPhasesDataWidget extends StatelessWidget { String _formatVoltage(String? value) { if (value == null) return '--'; - String str = value; + var str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp(r'[^0-9]'), ''); + str = str.replaceAll(RegExp('[^0-9]'), ''); if (str.isEmpty) return '--'; if (str.length == 1) return '0.${str[0]}'; return '${str.substring(0, str.length - 1)}.${str.substring(str.length - 1)}'; diff --git a/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart.dart b/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart.dart index 85b95c29..9ce6295b 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart.dart @@ -29,7 +29,6 @@ class TotalEnergyConsumptionChart extends StatelessWidget { ), duration: Duration.zero, curve: Curves.easeIn, - ), ); } diff --git a/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart_box.dart b/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart_box.dart index e197c297..7596c7d0 100644 --- a/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart_box.dart +++ b/lib/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart_box.dart @@ -25,7 +25,8 @@ class TotalEnergyConsumptionChartBox extends StatelessWidget { Row( children: [ ChartsLoadingWidget( - isLoading: state.status == TotalEnergyConsumptionStatus.loading, + isLoading: + state.status == TotalEnergyConsumptionStatus.loading, ), const Expanded( flex: 3, diff --git a/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart b/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart index 110f3c60..c6966c7e 100644 --- a/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart +++ b/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart @@ -23,9 +23,11 @@ class OccupancyBloc extends Bloc { emit(state.copyWith(status: OccupancyStatus.loading)); try { final chartData = await _occupacyService.load(event.param); - emit(state.copyWith(chartData: chartData, status: OccupancyStatus.loaded)); + emit( + state.copyWith(chartData: chartData, status: OccupancyStatus.loaded)); } on APIException catch (e) { - emit(state.copyWith(status: OccupancyStatus.failure, errorMessage: e.message)); + emit(state.copyWith( + status: OccupancyStatus.failure, errorMessage: e.message)); } catch (e) { emit(state.copyWith(status: OccupancyStatus.failure, errorMessage: '$e')); } diff --git a/lib/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart b/lib/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart index 0b01fda2..a56c0c9f 100644 --- a/lib/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart +++ b/lib/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart @@ -25,15 +25,18 @@ abstract final class FetchOccupancyDataHelper { final datePickerState = context.read().state; - loadAnalyticsDevices(context, communityUuid: communityId, spaceUuid: spaceId); - final selectedDevice = context.read().state.selectedDevice; + loadAnalyticsDevices(context, + communityUuid: communityId, spaceUuid: spaceId); + final selectedDevice = + context.read().state.selectedDevice; loadOccupancyChartData( context, spaceUuid: spaceId, date: datePickerState.monthlyDate, ); - loadHeatMapData(context, spaceUuid: spaceId, year: datePickerState.yearlyDate); + loadHeatMapData(context, + spaceUuid: spaceId, year: datePickerState.yearlyDate); if (selectedDevice case final AnalyticsDevice device) { context.read() @@ -64,7 +67,8 @@ abstract final class FetchOccupancyDataHelper { context.read().add( LoadOccupancyEvent( GetOccupancyParam( - monthDate: '${date.year}-${date.month.toString().padLeft(2, '0')}', + monthDate: + '${date.year}-${date.month.toString().padLeft(2, '0')}', spaceUuid: spaceUuid, ), ), diff --git a/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart b/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart index 679c9927..7db4f90c 100644 --- a/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart +++ b/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart @@ -20,9 +20,12 @@ class AnalyticsOccupancyView extends StatelessWidget { child: Column( spacing: 32, children: [ - SizedBox(height: height * 0.46, child: const OccupancyEndSideBar()), - SizedBox(height: height * 0.5, child: const OccupancyChartBox()), - SizedBox(height: height * 0.5, child: const OccupancyHeatMapBox()), + SizedBox( + height: height * 0.46, child: const OccupancyEndSideBar()), + SizedBox( + height: height * 0.5, child: const OccupancyChartBox()), + SizedBox( + height: height * 0.5, child: const OccupancyHeatMapBox()), ], ), ); diff --git a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart index 70087c46..d328b972 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart @@ -41,7 +41,8 @@ class OccupancyChart extends StatelessWidget { barRods: [ BarChartRodData( toY: 100.0, - fromY: occupancyValue == 0 ? occupancyValue : occupancyValue + 2.5, + fromY: + occupancyValue == 0 ? occupancyValue : occupancyValue + 2.5, color: ColorsManager.graysColor, width: _chartWidth, borderRadius: BorderRadius.circular(10), @@ -88,8 +89,8 @@ class OccupancyChart extends StatelessWidget { }) { final data = chartData; - final occupancyValue = double.parse(data[group.x.toInt()].occupancy); - final percentage = '${(occupancyValue).toStringAsFixed(0)}%'; + final occupancyValue = double.parse(data[group.x].occupancy); + final percentage = '${occupancyValue.toStringAsFixed(0)}%'; return BarTooltipItem( percentage, @@ -116,7 +117,7 @@ class OccupancyChart extends StatelessWidget { alignment: AlignmentDirectional.centerStart, fit: BoxFit.scaleDown, child: Text( - '${(value).toStringAsFixed(0)}%', + '${value.toStringAsFixed(0)}%', style: context.textTheme.bodySmall?.copyWith( fontSize: 12, color: ColorsManager.greyColor, diff --git a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart index 08f7223f..a950593d 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart @@ -44,13 +44,15 @@ class OccupancyChartBox extends StatelessWidget { child: AnalyticsDateFilterButton( onDateSelected: (DateTime value) { context.read().add( - UpdateAnalyticsDatePickerEvent(montlyDate: value), + UpdateAnalyticsDatePickerEvent( + montlyDate: value), ); if (spaceTreeState.selectedSpaces.isNotEmpty) { FetchOccupancyDataHelper.loadOccupancyChartData( context, spaceUuid: - spaceTreeState.selectedSpaces.firstOrNull ?? '', + spaceTreeState.selectedSpaces.firstOrNull ?? + '', date: value, ); } diff --git a/lib/pages/analytics/modules/occupancy/widgets/occupancy_heat_map_box.dart b/lib/pages/analytics/modules/occupancy/widgets/occupancy_heat_map_box.dart index c3b537e0..846b9d30 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_heat_map_box.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_heat_map_box.dart @@ -44,13 +44,15 @@ class OccupancyHeatMapBox extends StatelessWidget { child: AnalyticsDateFilterButton( onDateSelected: (DateTime value) { context.read().add( - UpdateAnalyticsDatePickerEvent(yearlyDate: value), + UpdateAnalyticsDatePickerEvent( + yearlyDate: value), ); if (spaceTreeState.selectedSpaces.isNotEmpty) { FetchOccupancyDataHelper.loadHeatMapData( context, spaceUuid: - spaceTreeState.selectedSpaces.firstOrNull ?? '', + spaceTreeState.selectedSpaces.firstOrNull ?? + '', year: value, ); } diff --git a/lib/pages/analytics/modules/occupancy/widgets/occupancy_painter.dart b/lib/pages/analytics/modules/occupancy/widgets/occupancy_painter.dart index 633b8c54..b57a73e1 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_painter.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_painter.dart @@ -28,11 +28,11 @@ class OccupancyPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final Paint fillPaint = Paint(); - final Paint borderPaint = Paint() + final fillPaint = Paint(); + final borderPaint = Paint() ..color = ColorsManager.grayBorder.withValues(alpha: 0.4) ..style = PaintingStyle.stroke; - final Paint hoveredBorderPaint = Paint() + final hoveredBorderPaint = Paint() ..color = Colors.black ..style = PaintingStyle.stroke ..strokeWidth = 1.5; @@ -66,24 +66,24 @@ class OccupancyPainter extends CustomPainter { ); canvas.drawLine(Offset(x, y), Offset(x, y + cellSize), borderPaint); - canvas.drawLine(Offset(x + cellSize, y), Offset(x + cellSize, y + cellSize), - borderPaint); + canvas.drawLine(Offset(x + cellSize, y), + Offset(x + cellSize, y + cellSize), borderPaint); } } } void _drawDashedLine(Canvas canvas, Offset start, Offset end, Paint paint) { - const double dashWidth = 2.0; - const double dashSpace = 4.0; - final double totalLength = (end - start).distance; - final Offset direction = (end - start) / (end - start).distance; + const dashWidth = 2.0; + const dashSpace = 4.0; + final totalLength = (end - start).distance; + final direction = (end - start) / (end - start).distance; - double currentLength = 0.0; + var currentLength = 0.0; while (currentLength < totalLength) { - final Offset dashStart = start + direction * currentLength; - final double nextLength = currentLength + dashWidth; - final Offset dashEnd = - start + direction * (nextLength < totalLength ? nextLength : totalLength); + final dashStart = start + direction * currentLength; + final nextLength = currentLength + dashWidth; + final dashEnd = start + + direction * (nextLength < totalLength ? nextLength : totalLength); canvas.drawLine(dashStart, dashEnd, paint); currentLength = nextLength + dashSpace; } diff --git a/lib/pages/analytics/services/air_quality_distribution/fake_air_quality_distribution_service.dart b/lib/pages/analytics/services/air_quality_distribution/fake_air_quality_distribution_service.dart index e0023f53..69189b60 100644 --- a/lib/pages/analytics/services/air_quality_distribution/fake_air_quality_distribution_service.dart +++ b/lib/pages/analytics/services/air_quality_distribution/fake_air_quality_distribution_service.dart @@ -5,7 +5,8 @@ import 'package:syncrow_web/pages/analytics/modules/air_quality/widgets/aqi_type import 'package:syncrow_web/pages/analytics/params/get_air_quality_distribution_param.dart'; import 'package:syncrow_web/pages/analytics/services/air_quality_distribution/air_quality_distribution_service.dart'; -class FakeAirQualityDistributionService implements AirQualityDistributionService { +class FakeAirQualityDistributionService + implements AirQualityDistributionService { final _random = Random(); @override @@ -43,7 +44,6 @@ class FakeAirQualityDistributionService implements AirQualityDistributionService name: 'poor', percentage: nonNullValues[2], type: AqiType.hcho.code, - ), AirQualityPercentageData( name: 'unhealthy', @@ -71,7 +71,7 @@ class FakeAirQualityDistributionService implements AirQualityDistributionService List nullMask, ) { double nonNullSum = 0; - for (int i = 0; i < originalValues.length; i++) { + for (var i = 0; i < originalValues.length; i++) { if (!nullMask[i]) { nonNullSum += originalValues[i]; } diff --git a/lib/pages/analytics/services/air_quality_distribution/remote_air_quality_distribution_service.dart b/lib/pages/analytics/services/air_quality_distribution/remote_air_quality_distribution_service.dart index dcf00600..7054c97b 100644 --- a/lib/pages/analytics/services/air_quality_distribution/remote_air_quality_distribution_service.dart +++ b/lib/pages/analytics/services/air_quality_distribution/remote_air_quality_distribution_service.dart @@ -3,7 +3,8 @@ import 'package:syncrow_web/pages/analytics/params/get_air_quality_distribution_ import 'package:syncrow_web/pages/analytics/services/air_quality_distribution/air_quality_distribution_service.dart'; import 'package:syncrow_web/services/api/http_service.dart'; -class RemoteAirQualityDistributionService implements AirQualityDistributionService { +class RemoteAirQualityDistributionService + implements AirQualityDistributionService { RemoteAirQualityDistributionService(this._httpService); final HTTPService _httpService; diff --git a/lib/pages/analytics/services/analytics_devices/analytics_devices_service_delagate.dart b/lib/pages/analytics/services/analytics_devices/analytics_devices_service_delagate.dart index 2d735df6..ee4fb431 100644 --- a/lib/pages/analytics/services/analytics_devices/analytics_devices_service_delagate.dart +++ b/lib/pages/analytics/services/analytics_devices/analytics_devices_service_delagate.dart @@ -16,7 +16,8 @@ class AnalyticsDevicesServiceDelegate implements AnalyticsDevicesService { GetAnalyticsDevicesParam param, ) { return switch (param.requestType) { - AnalyticsDeviceRequestType.occupancy => _occupancyService.getDevices(param), + AnalyticsDeviceRequestType.occupancy => + _occupancyService.getDevices(param), AnalyticsDeviceRequestType.energyManagement => _energyManagementService.getDevices(param), }; diff --git a/lib/pages/analytics/services/analytics_devices/remote_energy_management_analytics_devices_service.dart b/lib/pages/analytics/services/analytics_devices/remote_energy_management_analytics_devices_service.dart index 9ef711e9..62c0908b 100644 --- a/lib/pages/analytics/services/analytics_devices/remote_energy_management_analytics_devices_service.dart +++ b/lib/pages/analytics/services/analytics_devices/remote_energy_management_analytics_devices_service.dart @@ -14,7 +14,8 @@ final class RemoteEnergyManagementAnalyticsDevicesService static const _defaultErrorMessage = 'Failed to load analytics devices'; @override - Future> getDevices(GetAnalyticsDevicesParam param) async { + Future> getDevices( + GetAnalyticsDevicesParam param) async { try { final response = await _httpService.get( path: '/devices-space-community/recursive-child', @@ -37,7 +38,8 @@ final class RemoteEnergyManagementAnalyticsDevicesService final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { throw APIException('$_defaultErrorMessage: $e'); diff --git a/lib/pages/analytics/services/analytics_devices/remote_occupancy_analytics_devices_service.dart b/lib/pages/analytics/services/analytics_devices/remote_occupancy_analytics_devices_service.dart index 736b0804..37b9663c 100644 --- a/lib/pages/analytics/services/analytics_devices/remote_occupancy_analytics_devices_service.dart +++ b/lib/pages/analytics/services/analytics_devices/remote_occupancy_analytics_devices_service.dart @@ -6,7 +6,8 @@ import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/services/api/api_exception.dart'; import 'package:syncrow_web/services/api/http_service.dart'; -class RemoteOccupancyAnalyticsDevicesService implements AnalyticsDevicesService { +class RemoteOccupancyAnalyticsDevicesService + implements AnalyticsDevicesService { const RemoteOccupancyAnalyticsDevicesService(this._httpService); final HTTPService _httpService; @@ -14,7 +15,8 @@ class RemoteOccupancyAnalyticsDevicesService implements AnalyticsDevicesService static const _defaultErrorMessage = 'Failed to load analytics devices'; @override - Future> getDevices(GetAnalyticsDevicesParam param) async { + Future> getDevices( + GetAnalyticsDevicesParam param) async { try { final requests = await Future.wait>( param.deviceTypes.map((e) { @@ -34,15 +36,18 @@ class RemoteOccupancyAnalyticsDevicesService implements AnalyticsDevicesService final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { - final formattedErrorMessage = [_defaultErrorMessage, e.toString()].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, e.toString()].join(': '); throw APIException(formattedErrorMessage); } } - Future> _makeRequest(GetAnalyticsDevicesParam param) async { + Future> _makeRequest( + GetAnalyticsDevicesParam param) async { try { final projectUuid = await ProjectManager.getProjectUUID(); @@ -69,7 +74,8 @@ class RemoteOccupancyAnalyticsDevicesService implements AnalyticsDevicesService final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { throw APIException('$_defaultErrorMessage: $e'); diff --git a/lib/pages/analytics/services/device_location/device_location_details_service_decorator.dart b/lib/pages/analytics/services/device_location/device_location_details_service_decorator.dart index 0239bcb7..eb77fa5a 100644 --- a/lib/pages/analytics/services/device_location/device_location_details_service_decorator.dart +++ b/lib/pages/analytics/services/device_location/device_location_details_service_decorator.dart @@ -34,7 +34,7 @@ class DeviceLocationDetailsServiceDecorator implements DeviceLocationService { return deviceLocationInfo; } catch (e) { - throw Exception('Failed to load device location info: ${e.toString()}'); + throw Exception('Failed to load device location info: $e'); } } } diff --git a/lib/pages/analytics/services/energy_consumption_by_phases/remote_energy_consumption_by_phases_service.dart b/lib/pages/analytics/services/energy_consumption_by_phases/remote_energy_consumption_by_phases_service.dart index 17f9baff..5546bf65 100644 --- a/lib/pages/analytics/services/energy_consumption_by_phases/remote_energy_consumption_by_phases_service.dart +++ b/lib/pages/analytics/services/energy_consumption_by_phases/remote_energy_consumption_by_phases_service.dart @@ -11,7 +11,8 @@ final class RemoteEnergyConsumptionByPhasesService final HTTPService _httpService; - static const _defaultErrorMessage = 'Failed to load energy consumption per phase'; + static const _defaultErrorMessage = + 'Failed to load energy consumption per phase'; @override Future> load( @@ -36,7 +37,8 @@ final class RemoteEnergyConsumptionByPhasesService final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); diff --git a/lib/pages/analytics/services/energy_consumption_per_device/remote_energy_consumption_per_device_service.dart b/lib/pages/analytics/services/energy_consumption_per_device/remote_energy_consumption_per_device_service.dart index 82b21b1c..1845ac6e 100644 --- a/lib/pages/analytics/services/energy_consumption_per_device/remote_energy_consumption_per_device_service.dart +++ b/lib/pages/analytics/services/energy_consumption_per_device/remote_energy_consumption_per_device_service.dart @@ -13,7 +13,8 @@ class RemoteEnergyConsumptionPerDeviceService final HTTPService _httpService; - static const _defaultErrorMessage = 'Failed to load energy consumption per device'; + static const _defaultErrorMessage = + 'Failed to load energy consumption per device'; @override Future> load( @@ -31,7 +32,8 @@ class RemoteEnergyConsumptionPerDeviceService final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); @@ -59,7 +61,8 @@ abstract final class _EnergyConsumptionPerDeviceMapper { final energyJson = data as Map; return EnergyDataModel( date: DateTime.parse(energyJson['date'] as String), - value: double.parse(energyJson['total_energy_consumed_kw'] as String), + value: + double.parse(energyJson['total_energy_consumed_kw'] as String), ); }).toList(), ); diff --git a/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart b/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart index afd3f79e..149ae31c 100644 --- a/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart +++ b/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart @@ -33,7 +33,8 @@ final class RemoteOccupancyService implements OccupacyService { final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); diff --git a/lib/pages/analytics/services/occupancy_heat_map/remote_occupancy_heat_map_service.dart b/lib/pages/analytics/services/occupancy_heat_map/remote_occupancy_heat_map_service.dart index 0d7f6500..38865981 100644 --- a/lib/pages/analytics/services/occupancy_heat_map/remote_occupancy_heat_map_service.dart +++ b/lib/pages/analytics/services/occupancy_heat_map/remote_occupancy_heat_map_service.dart @@ -13,7 +13,8 @@ final class RemoteOccupancyHeatMapService implements OccupancyHeatMapService { static const _defaultErrorMessage = 'Failed to load occupancy heat map'; @override - Future> load(GetOccupancyHeatMapParam param) async { + Future> load( + GetOccupancyHeatMapParam param) async { try { final response = await _httpService.get( path: '/occupancy/heat-map/space/${param.spaceUuid}', @@ -24,7 +25,8 @@ final class RemoteOccupancyHeatMapService implements OccupancyHeatMapService { final dailyData = json['data'] as List? ?? []; final result = dailyData.map( - (json) => OccupancyHeatMapModel.fromJson(json as Map), + (json) => + OccupancyHeatMapModel.fromJson(json as Map), ); return result.toList(); @@ -36,7 +38,8 @@ final class RemoteOccupancyHeatMapService implements OccupancyHeatMapService { final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); diff --git a/lib/pages/analytics/services/power_clamp_info/remote_power_clamp_info_service.dart b/lib/pages/analytics/services/power_clamp_info/remote_power_clamp_info_service.dart index b4bc82c6..3930c252 100644 --- a/lib/pages/analytics/services/power_clamp_info/remote_power_clamp_info_service.dart +++ b/lib/pages/analytics/services/power_clamp_info/remote_power_clamp_info_service.dart @@ -28,7 +28,8 @@ final class RemotePowerClampInfoService implements PowerClampInfoService { final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); diff --git a/lib/pages/analytics/services/range_of_aqi/fake_range_of_aqi_service.dart b/lib/pages/analytics/services/range_of_aqi/fake_range_of_aqi_service.dart index 01ad6fa1..3140cae3 100644 --- a/lib/pages/analytics/services/range_of_aqi/fake_range_of_aqi_service.dart +++ b/lib/pages/analytics/services/range_of_aqi/fake_range_of_aqi_service.dart @@ -6,7 +6,7 @@ import 'package:syncrow_web/pages/analytics/services/range_of_aqi/range_of_aqi_s class FakeRangeOfAqiService implements RangeOfAqiService { @override Future> load(GetRangeOfAqiParam param) async { - return await Future.delayed(const Duration(milliseconds: 800), () { + return Future.delayed(const Duration(milliseconds: 800), () { final random = DateTime.now().millisecondsSinceEpoch; return List.generate(30, (index) { @@ -19,14 +19,20 @@ class FakeRangeOfAqiService implements RangeOfAqiService { final avg = (min + avgDelta).clamp(0.0, 301.0); final max = (avg + maxDelta).clamp(0.0, 301.0); - return RangeOfAqi( + return RangeOfAqi( data: [ - RangeOfAqiValue(type: AqiType.aqi.code, min: min, average: avg, max: max), - RangeOfAqiValue(type: AqiType.pm25.code, min: min, average: avg, max: max), - RangeOfAqiValue(type: AqiType.pm10.code, min: min, average: avg, max: max), - RangeOfAqiValue(type: AqiType.hcho.code, min: min, average: avg, max: max), - RangeOfAqiValue(type: AqiType.tvoc.code, min: min, average: avg, max: max), - RangeOfAqiValue(type: AqiType.co2.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.aqi.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.pm25.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.pm10.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.hcho.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.tvoc.code, min: min, average: avg, max: max), + RangeOfAqiValue( + type: AqiType.co2.code, min: min, average: avg, max: max), ], date: date, ); diff --git a/lib/pages/analytics/services/range_of_aqi/range_of_aqi_service.dart b/lib/pages/analytics/services/range_of_aqi/range_of_aqi_service.dart index 9e1657e3..6f5f00b1 100644 --- a/lib/pages/analytics/services/range_of_aqi/range_of_aqi_service.dart +++ b/lib/pages/analytics/services/range_of_aqi/range_of_aqi_service.dart @@ -3,4 +3,4 @@ import 'package:syncrow_web/pages/analytics/params/get_range_of_aqi_param.dart'; abstract interface class RangeOfAqiService { Future> load(GetRangeOfAqiParam param); -} \ No newline at end of file +} diff --git a/lib/pages/analytics/services/realtime_device_service/realtime_device_service.dart b/lib/pages/analytics/services/realtime_device_service/realtime_device_service.dart index 7afece6a..92c152ca 100644 --- a/lib/pages/analytics/services/realtime_device_service/realtime_device_service.dart +++ b/lib/pages/analytics/services/realtime_device_service/realtime_device_service.dart @@ -2,4 +2,4 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/device_sta abstract interface class RealtimeDeviceService { Stream> subscribe(String deviceId); -} \ No newline at end of file +} diff --git a/lib/pages/analytics/services/total_energy_consumption/remote_total_energy_consumption_service.dart b/lib/pages/analytics/services/total_energy_consumption/remote_total_energy_consumption_service.dart index 838cc5e7..42cdadbf 100644 --- a/lib/pages/analytics/services/total_energy_consumption/remote_total_energy_consumption_service.dart +++ b/lib/pages/analytics/services/total_energy_consumption/remote_total_energy_consumption_service.dart @@ -5,7 +5,8 @@ import 'package:syncrow_web/pages/analytics/services/total_energy_consumption/to import 'package:syncrow_web/services/api/api_exception.dart'; import 'package:syncrow_web/services/api/http_service.dart'; -class RemoteTotalEnergyConsumptionService implements TotalEnergyConsumptionService { +class RemoteTotalEnergyConsumptionService + implements TotalEnergyConsumptionService { const RemoteTotalEnergyConsumptionService(this._httpService); final HTTPService _httpService; @@ -29,7 +30,8 @@ class RemoteTotalEnergyConsumptionService implements TotalEnergyConsumptionServi final message = e.response?.data as Map?; final error = message?['error'] as Map?; final errorMessage = error?['error'] as String? ?? ''; - final formattedErrorMessage = [_defaultErrorMessage, errorMessage].join(': '); + final formattedErrorMessage = + [_defaultErrorMessage, errorMessage].join(': '); throw APIException(formattedErrorMessage); } catch (e) { final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': '); diff --git a/lib/pages/analytics/widgets/analytics_sidebar_header.dart b/lib/pages/analytics/widgets/analytics_sidebar_header.dart index 5ff1d042..33f59032 100644 --- a/lib/pages/analytics/widgets/analytics_sidebar_header.dart +++ b/lib/pages/analytics/widgets/analytics_sidebar_header.dart @@ -75,7 +75,8 @@ class AnalyticsSidebarHeader extends StatelessWidget { ), const SizedBox(height: 6), SelectableText( - context.watch().state.selectedDevice?.uuid ?? 'N/A', + context.watch().state.selectedDevice?.uuid ?? + 'N/A', style: context.textTheme.bodySmall?.copyWith( color: ColorsManager.blackColor, fontWeight: FontWeight.w400, diff --git a/lib/pages/auth/bloc/auth_bloc.dart b/lib/pages/auth/bloc/auth_bloc.dart index 58950089..c2774263 100644 --- a/lib/pages/auth/bloc/auth_bloc.dart +++ b/lib/pages/auth/bloc/auth_bloc.dart @@ -36,7 +36,8 @@ class AuthBloc extends Bloc { ////////////////////////////// forget password ////////////////////////////////// final TextEditingController forgetEmailController = TextEditingController(); - final TextEditingController forgetPasswordController = TextEditingController(); + final TextEditingController forgetPasswordController = + TextEditingController(); final TextEditingController forgetOtp = TextEditingController(); final forgetFormKey = GlobalKey(); final forgetEmailKey = GlobalKey(); @@ -53,7 +54,8 @@ class AuthBloc extends Bloc { return; } _remainingTime = 1; - add(UpdateTimerEvent(remainingTime: _remainingTime, isButtonEnabled: false)); + add(UpdateTimerEvent( + remainingTime: _remainingTime, isButtonEnabled: false)); try { forgetEmailValidate = ''; _remainingTime = (await AuthenticationAPI.sendOtp( @@ -62,7 +64,7 @@ class AuthBloc extends Bloc { } on DioException catch (e) { if (e.response!.statusCode == 400) { final errorData = e.response!.data; - String errorMessage = errorData['message']; + final String errorMessage = errorData['message']; if (errorMessage == 'User not found') { validate = 'Invalid Credential'; emit(AuthInitialState()); @@ -90,7 +92,8 @@ class AuthBloc extends Bloc { _timer?.cancel(); add(const UpdateTimerEvent(remainingTime: 0, isButtonEnabled: true)); } else { - add(UpdateTimerEvent(remainingTime: _remainingTime, isButtonEnabled: false)); + add(UpdateTimerEvent( + remainingTime: _remainingTime, isButtonEnabled: false)); } }); } @@ -100,11 +103,11 @@ class AuthBloc extends Bloc { emit(const TimerState(isButtonEnabled: true, remainingTime: 0)); } -Future changePassword( + Future changePassword( ChangePasswordEvent event, Emitter emit) async { emit(LoadingForgetState()); try { - var response = await AuthenticationAPI.verifyOtp( + final response = await AuthenticationAPI.verifyOtp( email: forgetEmailController.text, otpCode: forgetOtp.text); if (response == true) { await AuthenticationAPI.forgetPassword( @@ -122,7 +125,6 @@ Future changePassword( } } - String? validateCode(String? value) { if (value == null || value.isEmpty) { return 'Code is required'; @@ -131,7 +133,9 @@ Future changePassword( } void _onUpdateTimer(UpdateTimerEvent event, Emitter emit) { - emit(TimerState(isButtonEnabled: event.isButtonEnabled, remainingTime: event.remainingTime)); + emit(TimerState( + isButtonEnabled: event.isButtonEnabled, + remainingTime: event.remainingTime)); } ///////////////////////////////////// login ///////////////////////////////////// @@ -151,8 +155,7 @@ Future changePassword( static UserModel? user; bool showValidationMessage = false; - - void _login(LoginButtonPressed event, Emitter emit) async { + Future _login(LoginButtonPressed event, Emitter emit) async { emit(AuthLoading()); if (isChecked) { try { @@ -179,7 +182,7 @@ Future changePassword( } if (token.accessTokenIsNotEmpty) { - FlutterSecureStorage storage = const FlutterSecureStorage(); + const storage = FlutterSecureStorage(); await storage.write( key: Token.loginAccessTokenKey, value: token.accessToken); const FlutterSecureStorage().write( @@ -197,8 +200,7 @@ Future changePassword( } } - - checkBoxToggle( + void checkBoxToggle( CheckBoxEvent event, Emitter emit, ) { @@ -277,12 +279,12 @@ Future changePassword( if (value == null || value.isEmpty) { return 'Please enter your password'; } - List validationErrors = []; + final validationErrors = []; - if (!RegExp(r'^(?=.*[a-z])').hasMatch(value)) { + if (!RegExp('^(?=.*[a-z])').hasMatch(value)) { validationErrors.add(' - one lowercase letter'); } - if (!RegExp(r'^(?=.*[A-Z])').hasMatch(value)) { + if (!RegExp('^(?=.*[A-Z])').hasMatch(value)) { validationErrors.add(' - one uppercase letter'); } if (!RegExp(r'^(?=.*\d)').hasMatch(value)) { @@ -304,7 +306,7 @@ Future changePassword( String? fullNameValidator(String? value) { if (value == null) return 'Full name is required'; - final withoutExtraSpaces = value.replaceAll(RegExp(r"\s+"), ' ').trim(); + final withoutExtraSpaces = value.replaceAll(RegExp(r'\s+'), ' ').trim(); if (withoutExtraSpaces.length < 2 || withoutExtraSpaces.length > 30) { return 'Full name must be between 2 and 30 characters long'; } @@ -339,12 +341,14 @@ Future changePassword( static Future getTokenAndValidate() async { try { const storage = FlutterSecureStorage(); - final firstLaunch = - await SharedPreferencesHelper.readBoolFromSP(StringsManager.firstLaunch) ?? true; + final firstLaunch = await SharedPreferencesHelper.readBoolFromSP( + StringsManager.firstLaunch) ?? + true; if (firstLaunch) { storage.deleteAll(); } - await SharedPreferencesHelper.saveBoolToSP(StringsManager.firstLaunch, false); + await SharedPreferencesHelper.saveBoolToSP( + StringsManager.firstLaunch, false); final value = await storage.read(key: Token.loginAccessTokenKey) ?? ''; if (value.isEmpty) { return 'Token not found'; @@ -366,7 +370,8 @@ Future changePassword( } } - void _fetchRegion(RegionInitialEvent event, Emitter emit) async { + Future _fetchRegion( + RegionInitialEvent event, Emitter emit) async { try { emit(AuthLoading()); regionList = await AuthenticationAPI.fetchRegion(); @@ -389,15 +394,17 @@ Future changePassword( } String formattedTime(int time) { - final int days = (time / 86400).floor(); // 86400 seconds in a day - final int hours = ((time % 86400) / 3600).floor(); - final int minutes = (((time % 86400) % 3600) / 60).floor(); - final int seconds = (((time % 86400) % 3600) % 60).floor(); + final days = (time / 86400).floor(); // 86400 seconds in a day + final hours = ((time % 86400) / 3600).floor(); + final minutes = (((time % 86400) % 3600) / 60).floor(); + final seconds = ((time % 86400) % 3600) % 60; - final String formattedTime = [ + final formattedTime = [ if (days > 0) '${days}d', // Append 'd' for days if (days > 0 || hours > 0) - hours.toString().padLeft(2, '0'), // Show hours if there are days or hours + hours + .toString() + .padLeft(2, '0'), // Show hours if there are days or hours minutes.toString().padLeft(2, '0'), seconds.toString().padLeft(2, '0'), ].join(':'); @@ -417,7 +424,7 @@ Future changePassword( return checkValidate; } - changeValidate( + void changeValidate( ChangeValidateEvent event, Emitter emit, ) { @@ -426,7 +433,7 @@ Future changePassword( emit(LoginInitial()); } - changeForgetValidate( + void changeForgetValidate( ChangeValidateEvent event, Emitter emit, ) { diff --git a/lib/pages/auth/bloc/auth_event.dart b/lib/pages/auth/bloc/auth_event.dart index 2b6a4eef..392270e3 100644 --- a/lib/pages/auth/bloc/auth_event.dart +++ b/lib/pages/auth/bloc/auth_event.dart @@ -46,7 +46,8 @@ class StopTimerEvent extends AuthEvent {} class UpdateTimerEvent extends AuthEvent { final int remainingTime; final bool isButtonEnabled; - const UpdateTimerEvent({required this.remainingTime, required this.isButtonEnabled}); + const UpdateTimerEvent( + {required this.remainingTime, required this.isButtonEnabled}); } class ChangePasswordEvent extends AuthEvent {} diff --git a/lib/pages/auth/bloc/auth_state.dart b/lib/pages/auth/bloc/auth_state.dart index f3a95157..05790a7b 100644 --- a/lib/pages/auth/bloc/auth_state.dart +++ b/lib/pages/auth/bloc/auth_state.dart @@ -56,7 +56,8 @@ class TimerState extends AuthState { final bool isButtonEnabled; final int remainingTime; - const TimerState({required this.isButtonEnabled, required this.remainingTime}); + const TimerState( + {required this.isButtonEnabled, required this.remainingTime}); @override List get props => [isButtonEnabled, remainingTime]; @@ -80,7 +81,7 @@ class TimerUpdated extends AuthState { final String formattedTime; final bool isButtonEnabled; - TimerUpdated({ + const TimerUpdated({ required this.formattedTime, required this.isButtonEnabled, }); diff --git a/lib/pages/auth/model/login_with_email_model.dart b/lib/pages/auth/model/login_with_email_model.dart index dca3f8f9..fcde9f17 100644 --- a/lib/pages/auth/model/login_with_email_model.dart +++ b/lib/pages/auth/model/login_with_email_model.dart @@ -21,9 +21,9 @@ class LoginWithEmailModel { return { 'email': email, 'password': password, - "platform": "web" + 'platform': 'web' // 'regionUuid': regionUuid, }; } } -//tst@tst.com \ No newline at end of file +//tst@tst.com diff --git a/lib/pages/auth/model/token.dart b/lib/pages/auth/model/token.dart index 53c6f401..24ee46f2 100644 --- a/lib/pages/auth/model/token.dart +++ b/lib/pages/auth/model/token.dart @@ -11,6 +11,14 @@ class Token { final int iat; final int exp; + Token( + this.accessToken, + this.refreshToken, + this.sessionId, + this.iat, + this.exp, + ); + Token.emptyConstructor() : accessToken = '', refreshToken = '', @@ -24,14 +32,6 @@ class Token { bool get isNotEmpty => accessToken.isNotEmpty && refreshToken.isNotEmpty; - Token( - this.accessToken, - this.refreshToken, - this.sessionId, - this.iat, - this.exp, - ); - Token.refreshToken(this.refreshToken) : accessToken = '', sessionId = '', @@ -40,7 +40,7 @@ class Token { factory Token.fromJson(Map json) { //save token to secure storage - var storage = const FlutterSecureStorage(); + const storage = FlutterSecureStorage(); storage.write( key: loginAccessTokenKey, value: json[loginAccessTokenKey] ?? ''); storage.write( diff --git a/lib/pages/auth/model/user_model.dart b/lib/pages/auth/model/user_model.dart index 267d0b3e..98da8bd3 100644 --- a/lib/pages/auth/model/user_model.dart +++ b/lib/pages/auth/model/user_model.dart @@ -55,22 +55,21 @@ class UserModel { //from token factory UserModel.fromToken(Token token) { - Map tempJson = Token.decodeToken(token.accessToken); + final tempJson = Token.decodeToken(token.accessToken); return UserModel( - hasAcceptedWebAgreement: null, - role: null, - webAgreementAcceptedAt: null, - uuid: tempJson['uuid'].toString(), - email: tempJson['email'], - firstName: null, - lastName: null, - photoUrl: null, - phoneNumber: null, - isEmailVerified: null, - isAgreementAccepted: null, - project: null - ); + hasAcceptedWebAgreement: null, + role: null, + webAgreementAcceptedAt: null, + uuid: tempJson['uuid'].toString(), + email: tempJson['email'], + firstName: null, + lastName: null, + photoUrl: null, + phoneNumber: null, + isEmailVerified: null, + isAgreementAccepted: null, + project: null); } Map toJson() { diff --git a/lib/pages/auth/view/forget_password_web_page.dart b/lib/pages/auth/view/forget_password_web_page.dart index 7686ea8f..b32644db 100644 --- a/lib/pages/auth/view/forget_password_web_page.dart +++ b/lib/pages/auth/view/forget_password_web_page.dart @@ -36,20 +36,18 @@ class ForgetPasswordWebPage extends StatelessWidget { ); } }, - builder: (context, state) { - return _buildForm(context, state); - }, + builder: _buildForm, ), ), ); } Widget _buildForm(BuildContext context, AuthState state) { - late ScrollController _scrollController; - _scrollController = ScrollController(); - void _scrollToCenter() { - final double middlePosition = _scrollController.position.maxScrollExtent / 2; - _scrollController.animateTo( + late ScrollController scrollController; + scrollController = ScrollController(); + void scrollToCenter() { + final middlePosition = scrollController.position.maxScrollExtent / 2; + scrollController.animateTo( middlePosition, duration: const Duration(seconds: 1), curve: Curves.easeInOut, @@ -57,24 +55,25 @@ class ForgetPasswordWebPage extends StatelessWidget { } WidgetsBinding.instance.addPostFrameCallback((_) { - _scrollToCenter(); + scrollToCenter(); }); final forgetBloc = BlocProvider.of(context); - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; return FirstLayer( second: Center( child: Stack( children: [ - if (state is AuthLoading) const Center(child: CircularProgressIndicator()), + if (state is AuthLoading) + const Center(child: CircularProgressIndicator()), ListView( shrinkWrap: true, - controller: _scrollController, + controller: scrollController, children: [ Container( padding: EdgeInsets.all(size.width * 0.02), margin: EdgeInsets.all(size.width * 0.09), decoration: BoxDecoration( - color: Colors.black.withOpacity(0.3), + color: Colors.black.withValues(alpha: 0.3), borderRadius: const BorderRadius.all(Radius.circular(20)), ), child: Center( @@ -94,17 +93,22 @@ class ForgetPasswordWebPage extends StatelessWidget { flex: 3, child: Container( decoration: BoxDecoration( - color: Colors.white.withOpacity(0.1), - borderRadius: const BorderRadius.all(Radius.circular(30)), - border: Border.all(color: ColorsManager.graysColor.withOpacity(0.2)), + color: Colors.white.withValues(alpha: 0.1), + borderRadius: + const BorderRadius.all(Radius.circular(30)), + border: Border.all( + color: ColorsManager.graysColor + .withValues(alpha: 0.2)), ), child: Form( key: forgetBloc.forgetFormKey, child: Padding( padding: EdgeInsets.symmetric( - horizontal: size.width * 0.02, vertical: size.width * 0.003), + horizontal: size.width * 0.02, + vertical: size.width * 0.003), child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 10), @@ -121,7 +125,9 @@ class ForgetPasswordWebPage extends StatelessWidget { style: Theme.of(context) .textTheme .bodySmall! - .copyWith(fontSize: 14, fontWeight: FontWeight.w400), + .copyWith( + fontSize: 14, + fontWeight: FontWeight.w400), ), const SizedBox(height: 10), // Column( @@ -140,69 +146,90 @@ class ForgetPasswordWebPage extends StatelessWidget { Form( key: forgetBloc.forgetEmailKey, child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisAlignment: + MainAxisAlignment.start, children: [ Text( - "Account", - style: Theme.of(context).textTheme.bodySmall!.copyWith( - fontSize: 14, fontWeight: FontWeight.w400), + 'Account', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + fontSize: 14, + fontWeight: + FontWeight.w400), ), const SizedBox(height: 10), SizedBox( child: TextFormField( - controller: forgetBloc.forgetEmailController, - validator: forgetBloc.validateEmail, - decoration: textBoxDecoration()!.copyWith( + controller: forgetBloc + .forgetEmailController, + validator: + forgetBloc.validateEmail, + decoration: + textBoxDecoration()!.copyWith( hintText: 'Enter your email', hintStyle: Theme.of(context) .textTheme .bodySmall! .copyWith( - color: ColorsManager.grayColor, - fontWeight: FontWeight.w400), + color: ColorsManager + .grayColor, + fontWeight: + FontWeight.w400), ), - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), ), ), ], )), const SizedBox(height: 20.0), Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "One Time Password", + 'One Time Password', style: Theme.of(context) .textTheme .bodySmall! - .copyWith(fontSize: 14, fontWeight: FontWeight.w400), + .copyWith( + fontSize: 14, + fontWeight: FontWeight.w400), ), const SizedBox(height: 10), SizedBox( child: TextFormField( validator: forgetBloc.validateCode, - keyboardType: TextInputType.visiblePassword, + keyboardType: + TextInputType.visiblePassword, controller: forgetBloc.forgetOtp, - decoration: textBoxDecoration()!.copyWith( + decoration: + textBoxDecoration()!.copyWith( hintText: 'Enter Code', hintStyle: Theme.of(context) .textTheme .bodySmall! .copyWith( - color: ColorsManager.grayColor, - fontWeight: FontWeight.w400), + color: + ColorsManager.grayColor, + fontWeight: + FontWeight.w400), suffixIcon: SizedBox( width: 100, child: Center( child: InkWell( onTap: state is TimerState && - !state.isButtonEnabled && - state.remainingTime != 1 + !state + .isButtonEnabled && + state.remainingTime != + 1 ? null - : - () { + : () { if (forgetBloc .forgetEmailKey .currentState! @@ -211,27 +238,31 @@ class ForgetPasswordWebPage extends StatelessWidget { StartTimerEvent()); } }, - child: Text( 'Get Code ${state is TimerState && !state.isButtonEnabled && state.remainingTime != 1 ? "(${forgetBloc.formattedTime(state.remainingTime)}) " : ""}', style: TextStyle( - color: state is TimerState && - !state.isButtonEnabled + color: state + is TimerState && + !state + .isButtonEnabled ? Colors.grey - : ColorsManager.btnColor, + : ColorsManager + .btnColor, ), ), ), ), ), ), - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), ), ), if (forgetBloc.forgetValidate != '') // Check if there is a validation message Padding( - padding: const EdgeInsets.only(top: 8.0), + padding: + const EdgeInsets.only(top: 8.0), child: Text( forgetBloc.forgetValidate, style: const TextStyle( @@ -244,34 +275,44 @@ class ForgetPasswordWebPage extends StatelessWidget { ), const SizedBox(height: 20.0), Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Password", + 'Password', style: Theme.of(context) .textTheme .bodySmall! - .copyWith(fontSize: 14, fontWeight: FontWeight.w400), + .copyWith( + fontSize: 14, + fontWeight: FontWeight.w400), ), const SizedBox(height: 10), SizedBox( child: TextFormField( obscureText: forgetBloc.obscureText, - keyboardType: TextInputType.visiblePassword, - validator: forgetBloc.passwordValidator, - controller: forgetBloc.forgetPasswordController, - decoration: textBoxDecoration()!.copyWith( + keyboardType: + TextInputType.visiblePassword, + validator: + forgetBloc.passwordValidator, + controller: forgetBloc + .forgetPasswordController, + decoration: + textBoxDecoration()!.copyWith( suffixIcon: IconButton( onPressed: () { - forgetBloc.add(PasswordVisibleEvent( - newValue: forgetBloc.obscureText)); + forgetBloc.add( + PasswordVisibleEvent( + newValue: forgetBloc + .obscureText)); }, icon: SizedBox( child: SvgPicture.asset( forgetBloc.obscureText ? Assets.visiblePassword - : Assets.invisiblePassword, + : Assets + .invisiblePassword, height: 15, width: 15, ), @@ -282,10 +323,13 @@ class ForgetPasswordWebPage extends StatelessWidget { .textTheme .bodySmall! .copyWith( - color: ColorsManager.grayColor, - fontWeight: FontWeight.w400), + color: + ColorsManager.grayColor, + fontWeight: + FontWeight.w400), ), - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), ), ), ], @@ -295,23 +339,31 @@ class ForgetPasswordWebPage extends StatelessWidget { ), const SizedBox(height: 20.0), Row( - crossAxisAlignment: CrossAxisAlignment.center, + crossAxisAlignment: + CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: size.width * 0.2, child: DefaultButton( - backgroundColor: ColorsManager.btnColor, + backgroundColor: + ColorsManager.btnColor, child: const Text('Submit'), onPressed: () { - if (forgetBloc.forgetFormKey.currentState!.validate() || - forgetBloc.forgetEmailKey.currentState! + if (forgetBloc + .forgetFormKey.currentState! + .validate() || + forgetBloc.forgetEmailKey + .currentState! .validate()) { - if (forgetBloc.forgetEmailKey.currentState! + if (forgetBloc.forgetEmailKey + .currentState! .validate() && - forgetBloc.forgetFormKey.currentState! + forgetBloc.forgetFormKey + .currentState! .validate()) { - forgetBloc.add(ChangePasswordEvent()); + forgetBloc + .add(ChangePasswordEvent()); } } }, @@ -325,7 +377,8 @@ class ForgetPasswordWebPage extends StatelessWidget { child: Text( forgetBloc.validate, style: const TextStyle( - fontWeight: FontWeight.w700, color: ColorsManager.red), + fontWeight: FontWeight.w700, + color: ColorsManager.red), ), ), ), @@ -337,8 +390,9 @@ class ForgetPasswordWebPage extends StatelessWidget { child: Wrap( children: [ const Text( - "Do you have an account? ", - style: TextStyle(color: Colors.white), + 'Do you have an account? ', + style: + TextStyle(color: Colors.white), ), InkWell( onTap: () { @@ -346,7 +400,7 @@ class ForgetPasswordWebPage extends StatelessWidget { Navigator.pop(context); }, child: const Text( - "Sign in", + 'Sign in', ), ), ], @@ -372,14 +426,15 @@ class ForgetPasswordWebPage extends StatelessWidget { )); } - Widget _buildDropdownField(BuildContext context, AuthBloc loginBloc, Size size) { - final TextEditingController textEditingController = TextEditingController(); + Widget _buildDropdownField( + BuildContext context, AuthBloc loginBloc, Size size) { + final textEditingController = TextEditingController(); return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Country/Region", + 'Country/Region', style: Theme.of(context).textTheme.bodySmall!.copyWith( fontSize: 14, fontWeight: FontWeight.w400, @@ -398,10 +453,13 @@ class ForgetPasswordWebPage extends StatelessWidget { builder: (FormFieldState field) { return InputDecorator( decoration: InputDecoration( - contentPadding: const EdgeInsets.symmetric(horizontal: 2, vertical: 10), + contentPadding: + const EdgeInsets.symmetric(horizontal: 2, vertical: 10), errorText: field.errorText, - filled: true, // Ensure the dropdown is filled with the background color - fillColor: ColorsManager.boxColor, // Match the dropdown container color + filled: + true, // Ensure the dropdown is filled with the background color + fillColor: ColorsManager + .boxColor, // Match the dropdown container color border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide( @@ -412,14 +470,16 @@ class ForgetPasswordWebPage extends StatelessWidget { enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide( - color: field.hasError ? Colors.red : ColorsManager.grayColor, + color: + field.hasError ? Colors.red : ColorsManager.grayColor, width: 1.5, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide( - color: field.hasError ? Colors.red : ColorsManager.grayColor, + color: + field.hasError ? Colors.red : ColorsManager.grayColor, width: 1.5, ), ), @@ -446,10 +506,11 @@ class ForgetPasswordWebPage extends StatelessWidget { return DropdownMenuItem( value: region.id, child: Text( - style: Theme.of(context).textTheme.bodyMedium!.copyWith( - fontSize: 14, - fontWeight: FontWeight.w400, - ), + style: + Theme.of(context).textTheme.bodyMedium!.copyWith( + fontSize: 14, + fontWeight: FontWeight.w400, + ), region.name, overflow: TextOverflow.ellipsis, maxLines: 1, @@ -462,7 +523,8 @@ class ForgetPasswordWebPage extends StatelessWidget { onChanged: (String? value) { if (value != null) { loginBloc.add(SelectRegionEvent(val: value)); - field.didChange(value); // Notify the form field of the change + field.didChange( + value); // Notify the form field of the change } }, buttonStyleData: const ButtonStyleData( @@ -486,7 +548,8 @@ class ForgetPasswordWebPage extends StatelessWidget { searchInnerWidgetHeight: 50, searchInnerWidget: Container( height: 50, - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 4), child: TextFormField( style: const TextStyle(color: Colors.black), controller: textEditingController, @@ -500,7 +563,8 @@ class ForgetPasswordWebPage extends StatelessWidget { ), ), searchMatchFn: (item, searchValue) { - final regionName = (item.child as Text).data?.toLowerCase() ?? ''; + final regionName = + (item.child as Text).data?.toLowerCase() ?? ''; final search = searchValue.toLowerCase().trim(); return regionName.contains(search); }, diff --git a/lib/pages/auth/view/login_mobile_page.dart b/lib/pages/auth/view/login_mobile_page.dart index 4f001bc6..a32944dc 100644 --- a/lib/pages/auth/view/login_mobile_page.dart +++ b/lib/pages/auth/view/login_mobile_page.dart @@ -79,7 +79,7 @@ class LoginMobilePage extends StatelessWidget { child: Container( margin: const EdgeInsets.all(50), decoration: BoxDecoration( - color: Colors.black.withOpacity(0.3), + color: Colors.black.withValues(alpha: 0.3), borderRadius: const BorderRadius.all(Radius.circular(20))), child: Column( mainAxisSize: MainAxisSize.min, @@ -93,12 +93,15 @@ class LoginMobilePage extends StatelessWidget { ), ), Container( - margin: EdgeInsets.all(30), - padding: EdgeInsets.all(20), + margin: const EdgeInsets.all(30), + padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white.withOpacity(0.1), - borderRadius: const BorderRadius.all(Radius.circular(30)), - border: Border.all(color: ColorsManager.graysColor.withOpacity(0.2))), + color: Colors.white.withValues(alpha: 0.1), + borderRadius: + const BorderRadius.all(Radius.circular(30)), + border: Border.all( + color: ColorsManager.graysColor + .withValues(alpha: 0.2))), child: Form( key: loginBloc.loginFormKey, child: Column( @@ -109,7 +112,9 @@ class LoginMobilePage extends StatelessWidget { const Text( 'Login', style: TextStyle( - color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold), + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.bold), ), const SizedBox(height: 30), // Column( @@ -155,15 +160,15 @@ class LoginMobilePage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Email", + 'Email', style: Theme.of(context).textTheme.bodySmall, ), SizedBox( child: TextFormField( validator: loginBloc.validateEmail, controller: loginBloc.loginEmailController, - decoration: - textBoxDecoration()!.copyWith(hintText: 'Enter your email'), + decoration: textBoxDecoration()! + .copyWith(hintText: 'Enter your email'), style: const TextStyle(color: Colors.black), ), ), @@ -175,7 +180,7 @@ class LoginMobilePage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Password", + 'Password', style: Theme.of(context).textTheme.bodySmall, ), SizedBox( @@ -183,7 +188,8 @@ class LoginMobilePage extends StatelessWidget { validator: loginBloc.validatePassword, obscureText: loginBloc.obscureText, keyboardType: TextInputType.visiblePassword, - controller: loginBloc.loginPasswordController, + controller: + loginBloc.loginPasswordController, decoration: textBoxDecoration()!.copyWith( hintText: 'At least 8 characters', ), @@ -201,16 +207,19 @@ class LoginMobilePage extends StatelessWidget { children: [ InkWell( onTap: () { - Navigator.of(context).push(MaterialPageRoute( - builder: (context) => const ForgetPasswordPage(), + Navigator.of(context) + .push(MaterialPageRoute( + builder: (context) => + const ForgetPasswordPage(), )); }, child: Text( - "Forgot Password?", + 'Forgot Password?', style: Theme.of(context) .textTheme .bodySmall! - .copyWith(color: ColorsManager.blackColor), + .copyWith( + color: ColorsManager.blackColor), ), ), ], @@ -221,13 +230,15 @@ class LoginMobilePage extends StatelessWidget { Transform.scale( scale: 1.2, // Adjust the scale as needed child: Checkbox( - fillColor: MaterialStateProperty.all(Colors.white), + fillColor: WidgetStateProperty.all( + Colors.white), activeColor: Colors.white, value: loginBloc.isChecked, checkColor: Colors.black, shape: const CircleBorder(), onChanged: (bool? newValue) { - loginBloc.add(CheckBoxEvent(newValue: newValue)); + loginBloc.add( + CheckBoxEvent(newValue: newValue)); }, ), ), @@ -236,30 +247,37 @@ class LoginMobilePage extends StatelessWidget { child: RichText( text: TextSpan( text: 'Agree to ', - style: const TextStyle(color: Colors.white), + style: + const TextStyle(color: Colors.white), children: [ TextSpan( text: '(Terms of Service)', - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), recognizer: TapGestureRecognizer() ..onTap = () { - loginBloc.launchURL('https://example.com/terms'); + loginBloc.launchURL( + 'https://example.com/terms'); }, ), TextSpan( text: ' (Legal Statement)', - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), recognizer: TapGestureRecognizer() ..onTap = () { - loginBloc.launchURL('https://example.com/legal'); + loginBloc.launchURL( + 'https://example.com/legal'); }, ), TextSpan( text: ' (Privacy Statement)', - style: const TextStyle(color: Colors.black), + style: const TextStyle( + color: Colors.black), recognizer: TapGestureRecognizer() ..onTap = () { - loginBloc.launchURL('https://example.com/privacy'); + loginBloc.launchURL( + 'https://example.com/privacy'); }, ), ], @@ -276,11 +294,14 @@ class LoginMobilePage extends StatelessWidget { : ColorsManager.grayColor, child: const Text('Sign in'), onPressed: () { - if (loginBloc.loginFormKey.currentState!.validate()) { + if (loginBloc.loginFormKey.currentState! + .validate()) { loginBloc.add( LoginButtonPressed( - username: loginBloc.loginEmailController.text, - password: loginBloc.loginPasswordController.text, + username: + loginBloc.loginEmailController.text, + password: loginBloc + .loginPasswordController.text, ), ); } @@ -295,10 +316,11 @@ class LoginMobilePage extends StatelessWidget { Flexible( child: Text( "Don't you have an account? ", - style: TextStyle(color: Colors.white, fontSize: 13), + style: TextStyle( + color: Colors.white, fontSize: 13), )), Text( - "Sign up", + 'Sign up', ), ], ), diff --git a/lib/pages/auth/view/login_web_page.dart b/lib/pages/auth/view/login_web_page.dart index a6de87cf..d7416b67 100644 --- a/lib/pages/auth/view/login_web_page.dart +++ b/lib/pages/auth/view/login_web_page.dart @@ -24,7 +24,8 @@ class LoginWebPage extends StatefulWidget { State createState() => _LoginWebPageState(); } -class _LoginWebPageState extends State with HelperResponsiveLayout { +class _LoginWebPageState extends State + with HelperResponsiveLayout { @override Widget build(BuildContext context) { return Scaffold( @@ -42,9 +43,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout ); } }, - builder: (context, state) { - return _buildLoginForm(context, state); - }, + builder: _buildLoginForm, ), ), ); @@ -54,12 +53,12 @@ class _LoginWebPageState extends State with HelperResponsiveLayout final loginBloc = BlocProvider.of(context); final isSmallScreen = isSmallScreenSize(context); final isMediumScreen = isMediumScreenSize(context); - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; late ScrollController scrollController; scrollController = ScrollController(); void scrollToCenter() { - final double middlePosition = scrollController.position.maxScrollExtent / 2; + final middlePosition = scrollController.position.maxScrollExtent / 2; scrollController.animateTo( middlePosition, duration: const Duration(seconds: 1), @@ -84,7 +83,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout padding: EdgeInsets.all(size.width * 0.02), margin: EdgeInsets.all(size.width * 0.05), decoration: BoxDecoration( - color: Colors.black.withOpacity(0.3), + color: Colors.black.withValues(alpha: 0.3), borderRadius: const BorderRadius.all(Radius.circular(20)), ), child: Center( @@ -121,7 +120,8 @@ class _LoginWebPageState extends State with HelperResponsiveLayout const Spacer(), Expanded( flex: 2, - child: _buildLoginFormFields(context, loginBloc, size), + child: _buildLoginFormFields( + context, loginBloc, size), ), const Spacer(), ], @@ -132,23 +132,26 @@ class _LoginWebPageState extends State with HelperResponsiveLayout ), ), ), - if (state is AuthLoading) const Center(child: CircularProgressIndicator()) + if (state is AuthLoading) + const Center(child: CircularProgressIndicator()) ], ); } - Widget _buildLoginFormFields(BuildContext context, AuthBloc loginBloc, Size size) { + Widget _buildLoginFormFields( + BuildContext context, AuthBloc loginBloc, Size size) { return Container( decoration: BoxDecoration( - color: Colors.white.withOpacity(0.1), + color: Colors.white.withValues(alpha: 0.1), borderRadius: const BorderRadius.all(Radius.circular(30)), - border: Border.all(color: ColorsManager.graysColor.withOpacity(0.2)), + border: + Border.all(color: ColorsManager.graysColor.withValues(alpha: 0.2)), ), child: Form( key: loginBloc.loginFormKey, child: Padding( - padding: - EdgeInsets.symmetric(horizontal: size.width * 0.02, vertical: size.width * 0.003), + padding: EdgeInsets.symmetric( + horizontal: size.width * 0.02, vertical: size.width * 0.003), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, @@ -176,14 +179,15 @@ class _LoginWebPageState extends State with HelperResponsiveLayout ); } - Widget _buildDropdownField(BuildContext context, AuthBloc loginBloc, Size size) { - final TextEditingController textEditingController = TextEditingController(); + Widget _buildDropdownField( + BuildContext context, AuthBloc loginBloc, Size size) { + final textEditingController = TextEditingController(); return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Country/Region", + 'Country/Region', style: Theme.of(context).textTheme.bodySmall!.copyWith( fontSize: 14, fontWeight: FontWeight.w400, @@ -246,7 +250,8 @@ class _LoginWebPageState extends State with HelperResponsiveLayout searchInnerWidgetHeight: 50, searchInnerWidget: Container( height: 50, - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: TextFormField( style: const TextStyle(color: Colors.black), controller: textEditingController, @@ -261,7 +266,8 @@ class _LoginWebPageState extends State with HelperResponsiveLayout ), searchMatchFn: (item, searchValue) { // Use the item's child text (region name) for searching. - final regionName = (item.child as Text).data?.toLowerCase() ?? ''; + final regionName = + (item.child as Text).data?.toLowerCase() ?? ''; final search = searchValue.toLowerCase().trim(); // Debugging print statement to ensure values are captured correctly. // Return true if the region name contains the search term. @@ -286,7 +292,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Email", + 'Email', style: Theme.of(context) .textTheme .bodySmall! @@ -303,10 +309,9 @@ class _LoginWebPageState extends State with HelperResponsiveLayout decoration: textBoxDecoration()!.copyWith( errorStyle: const TextStyle(height: 0), hintText: 'Enter your email address', - hintStyle: Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: ColorsManager.grayColor, fontWeight: FontWeight.w400)), + hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith( + color: ColorsManager.grayColor, + fontWeight: FontWeight.w400)), style: const TextStyle(color: Colors.black), ), ), @@ -320,7 +325,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - "Password", + 'Password', style: Theme.of(context) .textTheme .bodySmall! @@ -338,7 +343,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout controller: loginBloc.loginPasswordController, onFieldSubmitted: (value) { if (loginBloc.loginFormKey.currentState!.validate()) { - loginBloc.add(LoginButtonPressed( + loginBloc.add(LoginButtonPressed( username: loginBloc.loginEmailController.text, password: value, )); @@ -348,17 +353,18 @@ class _LoginWebPageState extends State with HelperResponsiveLayout }, decoration: textBoxDecoration()!.copyWith( hintText: 'At least 8 characters', - hintStyle: Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: ColorsManager.grayColor, fontWeight: FontWeight.w400), + hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith( + color: ColorsManager.grayColor, fontWeight: FontWeight.w400), suffixIcon: IconButton( onPressed: () { - loginBloc.add(PasswordVisibleEvent(newValue: loginBloc.obscureText)); + loginBloc.add( + PasswordVisibleEvent(newValue: loginBloc.obscureText)); }, icon: SizedBox( child: SvgPicture.asset( - loginBloc.obscureText ? Assets.visiblePassword : Assets.invisiblePassword, + loginBloc.obscureText + ? Assets.visiblePassword + : Assets.invisiblePassword, height: 15, width: 15, ), @@ -385,11 +391,11 @@ class _LoginWebPageState extends State with HelperResponsiveLayout )); }, child: Text( - "Forgot Password?", - style: Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.w400), + 'Forgot Password?', + style: Theme.of(context).textTheme.bodySmall!.copyWith( + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.w400), ), ), ], @@ -453,7 +459,8 @@ class _LoginWebPageState extends State with HelperResponsiveLayout ); } - Widget _buildSignInButton(BuildContext context, AuthBloc loginBloc, Size size) { + Widget _buildSignInButton( + BuildContext context, AuthBloc loginBloc, Size size) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, @@ -467,7 +474,7 @@ class _LoginWebPageState extends State with HelperResponsiveLayout fontSize: 14, color: loginBloc.checkValidate ? ColorsManager.whiteColors - : ColorsManager.whiteColors.withOpacity(0.2), + : ColorsManager.whiteColors.withValues(alpha: 0.2), )), onPressed: () { if (loginBloc.loginFormKey.currentState!.validate()) { @@ -494,7 +501,8 @@ class _LoginWebPageState extends State with HelperResponsiveLayout SizedBox( child: Text( loginBloc.validate, - style: const TextStyle(fontWeight: FontWeight.w700, color: ColorsManager.red), + style: const TextStyle( + fontWeight: FontWeight.w700, color: ColorsManager.red), ), ) ], diff --git a/lib/pages/common/access_device_table.dart b/lib/pages/common/access_device_table.dart index 86d4a6b3..01aed542 100644 --- a/lib/pages/common/access_device_table.dart +++ b/lib/pages/common/access_device_table.dart @@ -108,66 +108,64 @@ class _DynamicTableState extends State { child: Row( children: [ if (widget.withCheckBox) _buildSelectAllCheckbox(), - ...widget.headers - .map((header) => _buildTableHeaderCell(header)), + ...widget.headers.map(_buildTableHeaderCell), ], ), ), - widget.isEmpty - ? Expanded( - child: Column( + if (widget.isEmpty) + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, + Column( children: [ - Column( - children: [ - SvgPicture.asset(Assets.emptyTable), - const SizedBox( - height: 15, - ), - Text( - // no password - widget.tableName == 'AccessManagement' - ? 'No Password ' - : 'No Devices', - style: Theme.of(context) - .textTheme - .bodySmall! - .copyWith( - color: ColorsManager.grayColor), - ) - ], + SvgPicture.asset(Assets.emptyTable), + const SizedBox( + height: 15, ), + Text( + // no password + widget.tableName == 'AccessManagement' + ? 'No Password ' + : 'No Devices', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: ColorsManager.grayColor), + ) ], ), ], ), - ) - : Expanded( - child: Container( - color: Colors.white, - child: ListView.builder( - shrinkWrap: true, - itemCount: widget.data.length, - itemBuilder: (context, index) { - final row = widget.data[index]; - return Row( - children: [ - if (widget.withCheckBox) - _buildRowCheckbox( - index, widget.size.height * 0.10), - ...row.map((cell) => _buildTableCell( - cell.toString(), - widget.size.height * 0.10)), - ], - ); - }, - ), - ), + ], + ), + ) + else + Expanded( + child: ColoredBox( + color: Colors.white, + child: ListView.builder( + shrinkWrap: true, + itemCount: widget.data.length, + itemBuilder: (context, index) { + final row = widget.data[index]; + return Row( + children: [ + if (widget.withCheckBox) + _buildRowCheckbox( + index, widget.size.height * 0.10), + ...row.map((cell) => _buildTableCell( + cell.toString(), widget.size.height * 0.10)), + ], + ); + }, ), + ), + ), ], ), ), @@ -245,7 +243,7 @@ class _DynamicTableState extends State { } Widget _buildTableCell(String content, double size) { - bool isBatteryLevel = content.endsWith('%'); + final isBatteryLevel = content.endsWith('%'); double? batteryLevel; if (isBatteryLevel) { diff --git a/lib/pages/common/buttons/cancel_button.dart b/lib/pages/common/buttons/cancel_button.dart index da6dcdc7..2147760e 100644 --- a/lib/pages/common/buttons/cancel_button.dart +++ b/lib/pages/common/buttons/cancel_button.dart @@ -22,17 +22,21 @@ class CancelButton extends StatelessWidget { return ElevatedButton( onPressed: onPressed, style: ButtonStyle( - backgroundColor: WidgetStateProperty.all(ColorsManager.boxColor), // White background - foregroundColor: WidgetStateProperty.all(Colors.black), // Black text color + backgroundColor: + WidgetStateProperty.all(ColorsManager.boxColor), // White background + foregroundColor: + WidgetStateProperty.all(Colors.black), // Black text color shape: WidgetStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(borderRadius ?? 10), - side: const BorderSide(color: ColorsManager.boxColor), // Black border + side: + const BorderSide(color: ColorsManager.boxColor), // Black border ), ), - fixedSize: WidgetStateProperty.all(Size(width ?? 50, height ?? 40)), // Set button height + fixedSize: WidgetStateProperty.all( + Size(width ?? 50, height ?? 40)), // Set button height ), child: Text(label), // Dynamic label ); } -} \ No newline at end of file +} diff --git a/lib/pages/common/buttons/default_button.dart b/lib/pages/common/buttons/default_button.dart index ecca6138..61012434 100644 --- a/lib/pages/common/buttons/default_button.dart +++ b/lib/pages/common/buttons/default_button.dart @@ -64,7 +64,7 @@ class DefaultButton extends StatelessWidget { (Set states) { return enabled ? backgroundColor ?? ColorsManager.primaryColor - : Colors.black.withOpacity(0.2); + : Colors.black.withValues(alpha: 0.2); }), shape: WidgetStateProperty.all( RoundedRectangleBorder( diff --git a/lib/pages/common/curtain_toggle.dart b/lib/pages/common/curtain_toggle.dart index 7b1551c5..a1c99355 100644 --- a/lib/pages/common/curtain_toggle.dart +++ b/lib/pages/common/curtain_toggle.dart @@ -34,7 +34,7 @@ class CurtainToggle extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipOval( - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.curtainIcon, @@ -52,7 +52,7 @@ class CurtainToggle extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, onChanged: onChanged, ), ), diff --git a/lib/pages/common/custom_dialog.dart b/lib/pages/common/custom_dialog.dart index 9899bda4..78c4a43e 100644 --- a/lib/pages/common/custom_dialog.dart +++ b/lib/pages/common/custom_dialog.dart @@ -12,7 +12,7 @@ Future showCustomDialog({ double? iconWidth, VoidCallback? onOkPressed, bool barrierDismissible = false, - List? actions, + List? actions, }) { return showDialog( context: context, @@ -40,14 +40,20 @@ Future showCustomDialog({ style: Theme.of(context) .textTheme .headlineLarge! - .copyWith(fontSize: 20, fontWeight: FontWeight.w400, color: Colors.black), + .copyWith( + fontSize: 20, + fontWeight: FontWeight.w400, + color: Colors.black), ), ), Padding( padding: const EdgeInsets.only(top: 8.0), child: Text( message, - style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: Colors.black), + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(color: Colors.black), textAlign: TextAlign.center, ), ), diff --git a/lib/pages/common/custom_table.dart b/lib/pages/common/custom_table.dart index f23daa45..de6da949 100644 --- a/lib/pages/common/custom_table.dart +++ b/lib/pages/common/custom_table.dart @@ -20,8 +20,8 @@ class DynamicTable extends StatefulWidget { final void Function(int, bool, dynamic)? onRowSelected; final List? initialSelectedIds; final int uuidIndex; - final Function(dynamic selectedRows)? onSelectionChanged; - final Function(int rowIndex)? onSettingsPressed; + final void Function(dynamic selectedRows)? onSelectionChanged; + final void Function(int rowIndex)? onSettingsPressed; const DynamicTable({ super.key, required this.headers, @@ -79,10 +79,10 @@ class _DynamicTableState extends State { // Check if the old and new lists are the same if (oldList.length != newList.length) return false; - for (int i = 0; i < oldList.length; i++) { + for (var i = 0; i < oldList.length; i++) { if (oldList[i].length != newList[i].length) return false; - for (int j = 0; j < oldList[i].length; j++) { + for (var j = 0; j < oldList[i].length; j++) { if (oldList[i][j] != newList[i][j]) return false; } } @@ -162,7 +162,7 @@ class _DynamicTableState extends State { child: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: _horizontalBodyScrollController, - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SizedBox( width: widget.size.width, @@ -184,7 +184,7 @@ class _DynamicTableState extends State { rowIndex: rowIndex, columnIndex: entry.key, ); - }).toList(), + }), ], ); }), @@ -304,13 +304,13 @@ class _DynamicTableState extends State { required int rowIndex, required int columnIndex, }) { - bool isBatteryLevel = content.endsWith('%'); + final isBatteryLevel = content.endsWith('%'); double? batteryLevel; if (isBatteryLevel) { batteryLevel = double.tryParse(content.replaceAll('%', '').trim()); } - bool isSettingsColumn = widget.headers[columnIndex] == 'Settings'; + final isSettingsColumn = widget.headers[columnIndex] == 'Settings'; if (isSettingsColumn) { return buildSettingsIcon( @@ -404,7 +404,7 @@ class _DynamicTableState extends State { borderRadius: BorderRadius.circular(height / 2), boxShadow: [ BoxShadow( - color: Colors.black.withOpacity(0.17), + color: Colors.black.withValues(alpha: 0.17), blurRadius: 14, offset: const Offset(0, 4), ), @@ -416,11 +416,10 @@ class _DynamicTableState extends State { padding: const EdgeInsets.all(8.0), child: Center( child: SvgPicture.asset( - Assets.settings, // ضع المسار الصحيح هنا + Assets.settings, width: 40, height: 22, - color: ColorsManager - .primaryColor, // نفس لون الأيقونة في الصورة + color: ColorsManager.primaryColor, ), ), ), diff --git a/lib/pages/common/filter/filter_widget.dart b/lib/pages/common/filter/filter_widget.dart index 1af23045..afd98eef 100644 --- a/lib/pages/common/filter/filter_widget.dart +++ b/lib/pages/common/filter/filter_widget.dart @@ -36,7 +36,7 @@ class FilterWidget extends StatelessWidget { color: ColorsManager.boxColor, border: Border.all( color: isSelected - ? ColorsManager.blueColor.withOpacity(0.8) + ? ColorsManager.blueColor.withValues(alpha: 0.8) : Colors.transparent, width: 2.0, ), @@ -48,7 +48,7 @@ class FilterWidget extends StatelessWidget { tabs[index], style: TextStyle( color: isSelected - ? ColorsManager.blueColor.withOpacity(0.8) + ? ColorsManager.blueColor.withValues(alpha: 0.8) : Colors.black, ), ), diff --git a/lib/pages/common/hour_picker_dialog.dart b/lib/pages/common/hour_picker_dialog.dart index 01a87720..2c5be850 100644 --- a/lib/pages/common/hour_picker_dialog.dart +++ b/lib/pages/common/hour_picker_dialog.dart @@ -1,5 +1,3 @@ - - import 'package:flutter/material.dart'; class HourPickerDialog extends StatefulWidget { @@ -18,7 +16,7 @@ class _HourPickerDialogState extends State { void initState() { super.initState(); // Initialize the selectedHour with the initial time passed to the dialog - selectedHour = widget.initialTime.hour.toString().padLeft(2, '0') + ':00'; + selectedHour = '${widget.initialTime.hour.toString().padLeft(2, '0')}:00'; } @override @@ -28,7 +26,7 @@ class _HourPickerDialogState extends State { content: DropdownButton( value: selectedHour, // Show the currently selected hour items: List.generate(24, (index) { - String hour = index.toString().padLeft(2, '0'); + final hour = index.toString().padLeft(2, '0'); return DropdownMenuItem( value: '$hour:00', child: Text('$hour:00'), @@ -37,14 +35,16 @@ class _HourPickerDialogState extends State { onChanged: (String? newValue) { if (newValue != null) { setState(() { - selectedHour = newValue; // Update the selected hour without closing the dialog + selectedHour = + newValue; // Update the selected hour without closing the dialog }); } }, ), actions: [ TextButton( - onPressed: () => Navigator.of(context).pop(null), // Close the dialog without selection + onPressed: () => Navigator.of(context) + .pop(null), // Close the dialog without selection child: const Text('Cancel'), ), TextButton( diff --git a/lib/pages/common/info_dialog.dart b/lib/pages/common/info_dialog.dart index 97656418..f2062319 100644 --- a/lib/pages/common/info_dialog.dart +++ b/lib/pages/common/info_dialog.dart @@ -9,7 +9,8 @@ class InfoDialog extends StatelessWidget { final Size? size; final List? actions; - InfoDialog({ + const InfoDialog({ + super.key, required this.title, required this.content, this.actions, diff --git a/lib/pages/device_managment/ac/bloc/ac_bloc.dart b/lib/pages/device_managment/ac/bloc/ac_bloc.dart index af5a7b0a..d96a4714 100644 --- a/lib/pages/device_managment/ac/bloc/ac_bloc.dart +++ b/lib/pages/device_managment/ac/bloc/ac_bloc.dart @@ -45,7 +45,8 @@ class AcBloc extends Bloc { ) async { emit(AcsLoadingState()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); deviceStatus = AcStatusModel.fromJson(event.deviceId, status.status); if (deviceStatus.countdown1 != 0) { final totalMinutes = deviceStatus.countdown1 * 6; @@ -71,21 +72,20 @@ class AcBloc extends Bloc { void _listenToChanges(deviceId) { try { final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; - - stream.listen((DatabaseEvent event) async { + ref.onValue.listen((DatabaseEvent event) async { if (event.snapshot.value == null) return; - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { - statusList.add(Status(code: element['code'], value: element['value'])); + statusList + .add(Status(code: element['code'], value: element['value'])); }); - deviceStatus = AcStatusModel.fromJson(usersMap['productUuid'], statusList); + deviceStatus = + AcStatusModel.fromJson(usersMap['productUuid'], statusList); if (!isClosed) { add(AcStatusUpdated(deviceStatus)); } @@ -129,8 +129,10 @@ class AcBloc extends Bloc { ) async { emit(AcsLoadingState()); try { - final status = await DevicesManagementApi().getBatchStatus(event.devicesIds); - deviceStatus = AcStatusModel.fromJson(event.devicesIds.first, status.status); + final status = + await DevicesManagementApi().getBatchStatus(event.devicesIds); + deviceStatus = + AcStatusModel.fromJson(event.devicesIds.first, status.status); emit(ACStatusLoaded(status: deviceStatus)); } catch (e) { emit(AcsFailedState(error: e.toString())); @@ -190,8 +192,8 @@ class AcBloc extends Bloc { void _handleIncreaseTime(IncreaseTimeEvent event, Emitter emit) { if (state is! ACStatusLoaded) return; final currentState = state as ACStatusLoaded; - int newHours = scheduledHours; - int newMinutes = scheduledMinutes + 30; + var newHours = scheduledHours; + var newMinutes = scheduledMinutes + 30; newHours += newMinutes ~/ 60; newMinutes = newMinutes % 60; if (newHours > 23) { @@ -213,7 +215,7 @@ class AcBloc extends Bloc { ) { if (state is! ACStatusLoaded) return; final currentState = state as ACStatusLoaded; - int totalMinutes = (scheduledHours * 60) + scheduledMinutes; + var totalMinutes = (scheduledHours * 60) + scheduledMinutes; totalMinutes = (totalMinutes - 30).clamp(0, 1440); scheduledHours = totalMinutes ~/ 60; scheduledMinutes = totalMinutes % 60; @@ -286,7 +288,7 @@ class AcBloc extends Bloc { void _startCountdownTimer(Emitter emit) { _countdownTimer?.cancel(); - int totalSeconds = (scheduledHours * 3600) + (scheduledMinutes * 60); + var totalSeconds = (scheduledHours * 3600) + (scheduledMinutes * 60); _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) { if (totalSeconds > 0) { @@ -336,32 +338,26 @@ class AcBloc extends Bloc { if (value is bool) { deviceStatus = deviceStatus.copyWith(acSwitch: value); } - break; case 'temp_set': if (value is int) { deviceStatus = deviceStatus.copyWith(tempSet: value); } - break; case 'mode': if (value is String) { deviceStatus = deviceStatus.copyWith(modeString: value); } - break; case 'level': if (value is String) { deviceStatus = deviceStatus.copyWith(fanSpeedsString: value); } - break; case 'child_lock': if (value is bool) { deviceStatus = deviceStatus.copyWith(childLock: value); } - break; case 'countdown_time': if (value is int) { deviceStatus = deviceStatus.copyWith(countdown1: value); } - break; default: break; } diff --git a/lib/pages/device_managment/ac/bloc/ac_event.dart b/lib/pages/device_managment/ac/bloc/ac_event.dart index 9764f3ed..217199ea 100644 --- a/lib/pages/device_managment/ac/bloc/ac_event.dart +++ b/lib/pages/device_managment/ac/bloc/ac_event.dart @@ -22,7 +22,7 @@ class AcFetchDeviceStatusEvent extends AcsEvent { class AcStatusUpdated extends AcsEvent { final AcStatusModel deviceStatus; - AcStatusUpdated(this.deviceStatus); + const AcStatusUpdated(this.deviceStatus); } class AcFetchBatchStatusEvent extends AcsEvent { @@ -77,8 +77,6 @@ class AcFactoryResetEvent extends AcsEvent { List get props => [deviceId, factoryResetModel]; } - - class OnClose extends AcsEvent {} class IncreaseTimeEvent extends AcsEvent { @@ -95,8 +93,7 @@ class ToggleScheduleEvent extends AcsEvent {} class TimerCompletedEvent extends AcsEvent {} -class UpdateTimerEvent extends AcsEvent { -} +class UpdateTimerEvent extends AcsEvent {} class ApiCountdownValueEvent extends AcsEvent { final int apiValue; diff --git a/lib/pages/device_managment/ac/bloc/ac_state.dart b/lib/pages/device_managment/ac/bloc/ac_state.dart index 3e1e2c68..a8985957 100644 --- a/lib/pages/device_managment/ac/bloc/ac_state.dart +++ b/lib/pages/device_managment/ac/bloc/ac_state.dart @@ -18,6 +18,7 @@ class ACStatusLoaded extends AcsState { final DateTime timestamp; final int scheduledHours; final int scheduledMinutes; + @override final bool isTimerActive; ACStatusLoaded({ @@ -72,5 +73,3 @@ class TimerRunInProgress extends AcsState { @override List get props => [remainingTime]; } - - diff --git a/lib/pages/device_managment/ac/model/ac_model.dart b/lib/pages/device_managment/ac/model/ac_model.dart index 6afc778d..32a7de0c 100644 --- a/lib/pages/device_managment/ac/model/ac_model.dart +++ b/lib/pages/device_managment/ac/model/ac_model.dart @@ -32,9 +32,9 @@ class AcStatusModel { late int currentTemp; late String fanSpeeds; late bool childLock; - late int _countdown1 = 0; + late var countdown1 = 0; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch': acSwitch = status.value ?? false; @@ -55,7 +55,7 @@ class AcStatusModel { childLock = status.value ?? false; break; case 'countdown_time': - _countdown1 = status.value ?? 0; + countdown1 = status.value ?? 0; break; } } @@ -68,7 +68,7 @@ class AcStatusModel { currentTemp: currentTemp, fanSpeedsString: fanSpeeds, childLock: childLock, - countdown1: _countdown1, + countdown1: countdown1, ); } diff --git a/lib/pages/device_managment/ac/view/ac_device_batch_control.dart b/lib/pages/device_managment/ac/view/ac_device_batch_control.dart index aad0669b..5b03ae3d 100644 --- a/lib/pages/device_managment/ac/view/ac_device_batch_control.dart +++ b/lib/pages/device_managment/ac/view/ac_device_batch_control.dart @@ -15,7 +15,8 @@ import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class AcDeviceBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class AcDeviceBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const AcDeviceBatchControlView({super.key, required this.devicesIds}); final List devicesIds; @@ -100,8 +101,8 @@ class AcDeviceBatchControlView extends StatelessWidget with HelperResponsiveLayo ), Text( 'h', - style: - context.textTheme.bodySmall!.copyWith(color: ColorsManager.blackColor), + style: context.textTheme.bodySmall! + .copyWith(color: ColorsManager.blackColor), ), Text( '30', @@ -148,7 +149,8 @@ class AcDeviceBatchControlView extends StatelessWidget with HelperResponsiveLayo callFactoryReset: () { context.read().add(AcFactoryResetEvent( deviceId: state.status.uuid, - factoryResetModel: FactoryResetModel(devicesUuid: devicesIds), + factoryResetModel: + FactoryResetModel(devicesUuid: devicesIds), )); }, ), diff --git a/lib/pages/device_managment/ac/view/ac_device_control.dart b/lib/pages/device_managment/ac/view/ac_device_control.dart index a882e6d5..b779a5ca 100644 --- a/lib/pages/device_managment/ac/view/ac_device_control.dart +++ b/lib/pages/device_managment/ac/view/ac_device_control.dart @@ -14,7 +14,7 @@ import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; class AcDeviceControlsView extends StatelessWidget with HelperResponsiveLayout { - const AcDeviceControlsView({super.key, required this.device}); + const AcDeviceControlsView({super.key, required this.device}); final AllDevicesModel device; diff --git a/lib/pages/device_managment/ac/view/batch_control_list/batch_current_temp.dart b/lib/pages/device_managment/ac/view/batch_control_list/batch_current_temp.dart index be7441df..11724f1d 100644 --- a/lib/pages/device_managment/ac/view/batch_control_list/batch_current_temp.dart +++ b/lib/pages/device_managment/ac/view/batch_control_list/batch_current_temp.dart @@ -41,7 +41,7 @@ class _CurrentTempState extends State { double _initialAdjustedValue(dynamic value) { if (value is int || value is double) { - double doubleValue = value.toDouble(); + final double doubleValue = value.toDouble(); return doubleValue > 99 ? doubleValue / 10 : doubleValue; } else { throw ArgumentError('Invalid value type: Expected int or double'); @@ -75,35 +75,48 @@ class _CurrentTempState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - widget.isBatch == true - ? Text( - 'Set Temperature', - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), - ) - : Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, + if (widget.isBatch == true) + Text( + 'Set Temperature', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.grey), + ) + else + Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Current Temperature', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.grey), + ), + const SizedBox( + height: 5, + ), + Row( children: [ Text( - 'Current Temperature', - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), - ), - const SizedBox( - height: 5, - ), - Row( - children: [ - Text( - (widget.currentTemp > 99 ? widget.currentTemp / 10 : widget.currentTemp).toString(), - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), - ), - const CelsiusSymbol( - color: Colors.grey, - ) - ], + (widget.currentTemp > 99 + ? widget.currentTemp / 10 + : widget.currentTemp) + .toString(), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.grey), ), + const CelsiusSymbol( + color: Colors.grey, + ) ], ), + ], + ), const Spacer(), IncrementDecrementWidget( value: _adjustedValue.toString(), diff --git a/lib/pages/device_managment/ac/view/control_list/ac_toggle.dart b/lib/pages/device_managment/ac/view/control_list/ac_toggle.dart index 4e81ec09..8e592d48 100644 --- a/lib/pages/device_managment/ac/view/control_list/ac_toggle.dart +++ b/lib/pages/device_managment/ac/view/control_list/ac_toggle.dart @@ -52,7 +52,7 @@ class AcToggle extends StatelessWidget { height: 20, width: 35, child: CupertinoSwitch( - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, value: value, onChanged: (newValue) { context.read().add( diff --git a/lib/pages/device_managment/ac/view/control_list/current_temp.dart b/lib/pages/device_managment/ac/view/control_list/current_temp.dart index fdd51164..7c5f9494 100644 --- a/lib/pages/device_managment/ac/view/control_list/current_temp.dart +++ b/lib/pages/device_managment/ac/view/control_list/current_temp.dart @@ -39,7 +39,7 @@ class _CurrentTempState extends State { double _initialAdjustedValue(dynamic value) { if (value is int || value is double) { - double doubleValue = value.toDouble(); + final double doubleValue = value.toDouble(); return doubleValue > 99 ? doubleValue / 10 : doubleValue; } else { throw ArgumentError('Invalid value type: Expected int or double'); @@ -60,6 +60,7 @@ class _CurrentTempState extends State { ); }); } + @override void didUpdateWidget(CurrentTemp oldWidget) { super.didUpdateWidget(oldWidget); @@ -69,6 +70,7 @@ class _CurrentTempState extends State { }); } } + @override void dispose() { _debounce?.cancel(); @@ -87,7 +89,10 @@ class _CurrentTempState extends State { children: [ Text( 'Current Temperature', - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.grey), ), const SizedBox( height: 5, @@ -95,8 +100,14 @@ class _CurrentTempState extends State { Row( children: [ Text( - (widget.currentTemp > 99 ? widget.currentTemp / 10 : widget.currentTemp).toString(), - style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), + (widget.currentTemp > 99 + ? widget.currentTemp / 10 + : widget.currentTemp) + .toString(), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.grey), ), const CelsiusSymbol( color: Colors.grey, diff --git a/lib/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart b/lib/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart index 05e82f1f..0cf13036 100644 --- a/lib/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart +++ b/lib/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart @@ -16,7 +16,7 @@ class DeviceManagementBloc int _onlineCount = 0; int _offlineCount = 0; int _lowBatteryCount = 0; - List _selectedDevices = []; + final List _selectedDevices = []; List _filteredDevices = []; String currentProductName = ''; String? currentCommunity; @@ -37,20 +37,21 @@ class DeviceManagementBloc FetchDevices event, Emitter emit) async { emit(DeviceManagementLoading()); try { - List devices = []; + var devices = []; _devices.clear(); - var spaceBloc = event.context.read(); - final projectUuid = await ProjectManager.getProjectUUID() ?? ''; + final spaceBloc = event.context.read(); + final projectUuid = await ProjectManager.getProjectUUID() ?? ''; if (spaceBloc.state.selectedCommunities.isEmpty) { - devices = await DevicesManagementApi().fetchDevices('', '', projectUuid); + devices = + await DevicesManagementApi().fetchDevices('', '', projectUuid); } else { - for (var community in spaceBloc.state.selectedCommunities) { - List spacesList = + for (final community in spaceBloc.state.selectedCommunities) { + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[community] ?? []; - for (var space in spacesList) { - devices.addAll(await DevicesManagementApi().fetchDevices( - community, space, projectUuid)); + for (final space in spacesList) { + devices.addAll(await DevicesManagementApi() + .fetchDevices(community, space, projectUuid)); } } } @@ -73,7 +74,7 @@ class DeviceManagementBloc } } - void _onFilterDevices( + Future _onFilterDevices( FilterDevices event, Emitter emit) async { if (_devices.isNotEmpty) { _filteredDevices = List.from(_devices.where((device) { @@ -165,9 +166,9 @@ class DeviceManagementBloc _selectedDevices.add(event.selectedDevice); } - List clonedSelectedDevices = List.from(_selectedDevices); + final clonedSelectedDevices = List.from(_selectedDevices); - bool isControlButtonEnabled = + final isControlButtonEnabled = _checkIfControlButtonEnabled(clonedSelectedDevices); if (state is DeviceManagementLoaded) { @@ -197,8 +198,8 @@ class DeviceManagementBloc void _onUpdateSelection( UpdateSelection event, Emitter emit) { - List selectedDevices = []; - List devicesToSelectFrom = []; + final selectedDevices = []; + var devicesToSelectFrom = []; if (state is DeviceManagementLoaded) { devicesToSelectFrom = (state as DeviceManagementLoaded).devices; @@ -206,7 +207,7 @@ class DeviceManagementBloc devicesToSelectFrom = (state as DeviceManagementFiltered).filteredDevices; } - for (int i = 0; i < event.selectedRows.length; i++) { + for (var i = 0; i < event.selectedRows.length; i++) { if (event.selectedRows[i]) { selectedDevices.add(devicesToSelectFrom[i]); } @@ -294,7 +295,7 @@ class DeviceManagementBloc currentCommunity = event.community; currentUnitName = event.unitName; - List devicesToSearch = _filteredDevices; + final devicesToSearch = _filteredDevices; if (devicesToSearch.isNotEmpty) { final filteredDevices = devicesToSearch.where((device) { diff --git a/lib/pages/device_managment/all_devices/helper/route_controls_based_code.dart b/lib/pages/device_managment/all_devices/helper/route_controls_based_code.dart index 5586a310..25a8342b 100644 --- a/lib/pages/device_managment/all_devices/helper/route_controls_based_code.dart +++ b/lib/pages/device_managment/all_devices/helper/route_controls_based_code.dart @@ -18,6 +18,7 @@ import 'package:syncrow_web/pages/device_managment/gateway/view/gateway_view.dar import 'package:syncrow_web/pages/device_managment/main_door_sensor/view/main_door_control_view.dart'; import 'package:syncrow_web/pages/device_managment/main_door_sensor/view/main_door_sensor_batch_view.dart'; import 'package:syncrow_web/pages/device_managment/one_g_glass_switch/view/one_gang_glass_batch_control_view.dart'; +import 'package:syncrow_web/pages/device_managment/one_g_glass_switch/view/one_gang_glass_switch_control_view.dart'; import 'package:syncrow_web/pages/device_managment/one_gang_switch/view/wall_light_batch_control.dart'; import 'package:syncrow_web/pages/device_managment/one_gang_switch/view/wall_light_device_control.dart'; import 'package:syncrow_web/pages/device_managment/power_clamp/view/power_clamp_batch_control_view.dart'; @@ -39,8 +40,6 @@ import 'package:syncrow_web/pages/device_managment/water_heater/view/water_heate import 'package:syncrow_web/pages/device_managment/water_leak/view/water_leak_batch_control_view.dart'; import 'package:syncrow_web/pages/device_managment/water_leak/view/water_leak_control_view.dart'; -import '../../one_g_glass_switch/view/one_gang_glass_switch_control_view.dart'; - mixin RouteControlsBasedCode { Widget routeControlsWidgets({required AllDevicesModel device}) { switch (device.productType) { @@ -107,7 +106,7 @@ mixin RouteControlsBasedCode { case 'SOS': return SosDeviceControlsView(device: device); - case 'NCPS': + case 'NCPS': return FlushMountedPresenceSensorControlView(device: device); default: return const SizedBox(); @@ -132,76 +131,133 @@ mixin RouteControlsBasedCode { switch (devices.first.productType) { case '1G': return WallLightBatchControlView( - deviceIds: devices.where((e) => (e.productType == '1G')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '1G') + .map((e) => e.uuid!) + .toList(), ); case '2G': return TwoGangBatchControlView( - deviceIds: devices.where((e) => (e.productType == '2G')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '2G') + .map((e) => e.uuid!) + .toList(), ); case '3G': return LivingRoomBatchControlsView( - deviceIds: devices.where((e) => (e.productType == '3G')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '3G') + .map((e) => e.uuid!) + .toList(), ); case '1GT': return OneGangGlassSwitchBatchControlView( - deviceIds: devices.where((e) => (e.productType == '1GT')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '1GT') + .map((e) => e.uuid!) + .toList(), ); case '2GT': return TwoGangGlassSwitchBatchControlView( - deviceIds: devices.where((e) => (e.productType == '2GT')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '2GT') + .map((e) => e.uuid!) + .toList(), ); case '3GT': return ThreeGangGlassSwitchBatchControlView( - deviceIds: devices.where((e) => (e.productType == '3GT')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == '3GT') + .map((e) => e.uuid!) + .toList(), ); case 'GW': return GatewayBatchControlView( - gatewayIds: devices.where((e) => (e.productType == 'GW')).map((e) => e.uuid!).toList(), + gatewayIds: devices + .where((e) => e.productType == 'GW') + .map((e) => e.uuid!) + .toList(), ); case 'DL': return DoorLockBatchControlView( - devicesIds: devices.where((e) => (e.productType == 'DL')).map((e) => e.uuid!).toList()); + devicesIds: devices + .where((e) => e.productType == 'DL') + .map((e) => e.uuid!) + .toList()); case 'WPS': return WallSensorBatchControlView( - devicesIds: devices.where((e) => (e.productType == 'WPS')).map((e) => e.uuid!).toList()); + devicesIds: devices + .where((e) => e.productType == 'WPS') + .map((e) => e.uuid!) + .toList()); case 'CPS': return CeilingSensorBatchControlView( - devicesIds: devices.where((e) => (e.productType == 'CPS')).map((e) => e.uuid!).toList(), + devicesIds: devices + .where((e) => e.productType == 'CPS') + .map((e) => e.uuid!) + .toList(), ); case 'CUR': return CurtainBatchStatusView( - devicesIds: devices.where((e) => (e.productType == 'CUR')).map((e) => e.uuid!).toList(), + devicesIds: devices + .where((e) => e.productType == 'CUR') + .map((e) => e.uuid!) + .toList(), ); case 'AC': return AcDeviceBatchControlView( - devicesIds: devices.where((e) => (e.productType == 'AC')).map((e) => e.uuid!).toList()); + devicesIds: devices + .where((e) => e.productType == 'AC') + .map((e) => e.uuid!) + .toList()); case 'WH': return WaterHEaterBatchControlView( - deviceIds: devices.where((e) => (e.productType == 'WH')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == 'WH') + .map((e) => e.uuid!) + .toList(), ); case 'DS': return MainDoorSensorBatchView( - devicesIds: devices.where((e) => (e.productType == 'DS')).map((e) => e.uuid!).toList(), + devicesIds: devices + .where((e) => e.productType == 'DS') + .map((e) => e.uuid!) + .toList(), ); case 'GD': return GarageDoorBatchControlView( - deviceIds: devices.where((e) => (e.productType == 'GD')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == 'GD') + .map((e) => e.uuid!) + .toList(), ); case 'WL': return WaterLeakBatchControlView( - deviceIds: devices.where((e) => (e.productType == 'WL')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == 'WL') + .map((e) => e.uuid!) + .toList(), ); case 'PC': return PowerClampBatchControlView( - deviceIds: devices.where((e) => (e.productType == 'PC')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == 'PC') + .map((e) => e.uuid!) + .toList(), ); case 'SOS': return SOSBatchControlView( - deviceIds: devices.where((e) => (e.productType == 'SOS')).map((e) => e.uuid!).toList(), + deviceIds: devices + .where((e) => e.productType == 'SOS') + .map((e) => e.uuid!) + .toList(), ); case 'NCPS': return FlushMountedPresenceSensorBatchControlView( - devicesIds: devices.where((e) => (e.productType == 'NCPS')).map((e) => e.uuid!).toList(), + devicesIds: devices + .where((e) => e.productType == 'NCPS') + .map((e) => e.uuid!) + .toList(), ); default: return const SizedBox(); diff --git a/lib/pages/device_managment/all_devices/models/device_sub_space.dart b/lib/pages/device_managment/all_devices/models/device_sub_space.dart index 96195f76..bf94524b 100644 --- a/lib/pages/device_managment/all_devices/models/device_sub_space.dart +++ b/lib/pages/device_managment/all_devices/models/device_sub_space.dart @@ -5,7 +5,12 @@ class DeviceSubSpace { String? subspaceName; bool? disabled; - DeviceSubSpace({this.id, this.createdAt, this.updatedAt, this.subspaceName, this.disabled}); + DeviceSubSpace( + {this.id, + this.createdAt, + this.updatedAt, + this.subspaceName, + this.disabled}); DeviceSubSpace.fromJson(Map json) { id = json['uuid']?.toString() ?? ''; diff --git a/lib/pages/device_managment/all_devices/models/devices_model.dart b/lib/pages/device_managment/all_devices/models/devices_model.dart index 808a683f..a14b14d3 100644 --- a/lib/pages/device_managment/all_devices/models/devices_model.dart +++ b/lib/pages/device_managment/all_devices/models/devices_model.dart @@ -212,8 +212,8 @@ PC SOS */ - DeviceType type = devicesTypesMap[productType] ?? DeviceType.Other; - String tempIcon = ''; + final type = devicesTypesMap[productType] ?? DeviceType.Other; + var tempIcon = ''; if (type == DeviceType.LightBulb) { tempIcon = Assets.lightBulb; } else if (type == DeviceType.CeilingSensor || @@ -441,13 +441,9 @@ SOS VoltageCStatusFunction( deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'), CurrentCStatusFunction( - deviceId: uuid ?? '', - deviceName: name ?? '', - type: 'IF'), + deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'), PowerFactorCStatusFunction( - deviceId: uuid ?? '', - deviceName: name ?? '', - type: 'IF'), + deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'), ]; default: @@ -565,23 +561,23 @@ SOS } Map devicesTypesMap = { - "AC": DeviceType.AC, - "GW": DeviceType.Gateway, - "CPS": DeviceType.CeilingSensor, - "DL": DeviceType.DoorLock, - "WPS": DeviceType.WallSensor, - "3G": DeviceType.ThreeGang, - "2G": DeviceType.TwoGang, - "1G": DeviceType.OneGang, - "CUR": DeviceType.Curtain, - "WH": DeviceType.WH, - "DS": DeviceType.DS, - "1GT": DeviceType.OneTouch, - "2GT": DeviceType.TowTouch, - "3GT": DeviceType.ThreeTouch, - "GD": DeviceType.GarageDoor, - "WL": DeviceType.WaterLeak, - "NCPS": DeviceType.NCPS, - "PC": DeviceType.PC, + 'AC': DeviceType.AC, + 'GW': DeviceType.Gateway, + 'CPS': DeviceType.CeilingSensor, + 'DL': DeviceType.DoorLock, + 'WPS': DeviceType.WallSensor, + '3G': DeviceType.ThreeGang, + '2G': DeviceType.TwoGang, + '1G': DeviceType.OneGang, + 'CUR': DeviceType.Curtain, + 'WH': DeviceType.WH, + 'DS': DeviceType.DS, + '1GT': DeviceType.OneTouch, + '2GT': DeviceType.TowTouch, + '3GT': DeviceType.ThreeTouch, + 'GD': DeviceType.GarageDoor, + 'WL': DeviceType.WaterLeak, + 'NCPS': DeviceType.NCPS, + 'PC': DeviceType.PC, }; } diff --git a/lib/pages/device_managment/all_devices/models/factory_reset_model.dart b/lib/pages/device_managment/all_devices/models/factory_reset_model.dart index 1b5685a1..decfa05f 100644 --- a/lib/pages/device_managment/all_devices/models/factory_reset_model.dart +++ b/lib/pages/device_managment/all_devices/models/factory_reset_model.dart @@ -6,13 +6,13 @@ class FactoryResetModel { FactoryResetModel({ required this.devicesUuid, - this.operationType = "RESET", + this.operationType = 'RESET', }); factory FactoryResetModel.fromJson(Map json) { return FactoryResetModel( devicesUuid: List.from(json['devicesUuid']), - operationType: "RESET", + operationType: 'RESET', ); } @@ -58,4 +58,3 @@ class FactoryResetModel { @override int get hashCode => devicesUuid.hashCode; } - diff --git a/lib/pages/device_managment/all_devices/widgets/device_managment_body.dart b/lib/pages/device_managment/all_devices/widgets/device_managment_body.dart index f4baad0c..abd06cd0 100644 --- a/lib/pages/device_managment/all_devices/widgets/device_managment_body.dart +++ b/lib/pages/device_managment/all_devices/widgets/device_managment_body.dart @@ -24,13 +24,13 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout { Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { - List devicesToShow = []; - int selectedIndex = 0; - int onlineCount = 0; - int offlineCount = 0; - int lowBatteryCount = 0; - bool isControlButtonEnabled = false; - List selectedDevices = []; + var devicesToShow = []; + var selectedIndex = 0; + var onlineCount = 0; + var offlineCount = 0; + var lowBatteryCount = 0; + var isControlButtonEnabled = false; + var selectedDevices = []; if (state is DeviceManagementLoaded) { devicesToShow = state.devices; @@ -194,18 +194,23 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout { device.name ?? '', device.productName ?? '', device.uuid ?? '', - (device.spaces != null && - device.spaces!.isNotEmpty) - ? device.spaces![0].spaceName - : '', + if (device.spaces != null && + device.spaces!.isNotEmpty) + device.spaces![0].spaceName + else + '', combinedSpaceNames, - device.batteryLevel != null - ? '${device.batteryLevel}%' - : '-', + if (device.batteryLevel != null) + '${device.batteryLevel}%' + else + '-', formatDateTime( DateTime.fromMillisecondsSinceEpoch( (device.createTime ?? 0) * 1000)), - device.online == true ? 'Online' : 'Offline', + if (device.online == true) + 'Online' + else + 'Offline', formatDateTime( DateTime.fromMillisecondsSinceEpoch( (device.updateTime ?? 0) * 1000)), @@ -243,7 +248,7 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout { showGeneralDialog( context: context, barrierDismissible: true, - barrierLabel: "Device Settings", + barrierLabel: 'Device Settings', transitionDuration: const Duration(milliseconds: 300), pageBuilder: (context, anim1, anim2) { return Align( diff --git a/lib/pages/device_managment/all_devices/widgets/device_search_filters.dart b/lib/pages/device_managment/all_devices/widgets/device_search_filters.dart index 6440d18f..99378a86 100644 --- a/lib/pages/device_managment/all_devices/widgets/device_search_filters.dart +++ b/lib/pages/device_managment/all_devices/widgets/device_search_filters.dart @@ -33,9 +33,9 @@ class _DeviceSearchFiltersState extends State spacing: 20, runSpacing: 10, children: [ - _buildSearchField("Space Name", _unitNameController, 200), + _buildSearchField('Space Name', _unitNameController, 200), _buildSearchField( - "Device Name / Product Name", _productNameController, 300), + 'Device Name / Product Name', _productNameController, 300), _buildSearchResetButtons(), ], ); diff --git a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart index 42387e57..0d5e59b2 100644 --- a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart +++ b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart @@ -37,7 +37,8 @@ class CeilingSensorBloc extends Bloc { ) async { emit(CeilingLoadingInitialState()); try { - final response = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final response = + await DevicesManagementApi().getDeviceStatus(event.deviceId); deviceStatus = CeilingSensorModel.fromJson(response.status); emit(CeilingUpdateState(ceilingSensorModel: deviceStatus)); _listenToChanges(event.deviceId); @@ -54,11 +55,12 @@ class CeilingSensorBloc extends Bloc { stream.listen((DatabaseEvent event) { if (event.snapshot.value == null) return; - final usersMap = event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; final statusList = []; usersMap['status'].forEach((element) { - statusList.add(Status(code: element['code'], value: element['value'])); + statusList + .add(Status(code: element['code'], value: element['value'])); }); deviceStatus = CeilingSensorModel.fromJson(statusList); @@ -178,7 +180,8 @@ class CeilingSensorBloc extends Bloc { ) async { emit(CeilingLoadingInitialState()); try { - final response = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final response = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = CeilingSensorModel.fromJson(response.status); emit(CeilingUpdateState(ceilingSensorModel: deviceStatus)); } catch (e) { diff --git a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart index 1dc7d8d7..e296e1b9 100644 --- a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart +++ b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart @@ -85,8 +85,6 @@ class CeilingFactoryResetEvent extends CeilingSensorEvent { List get props => [devicesId, factoryResetModel]; } - - class StatusUpdated extends CeilingSensorEvent { final CeilingSensorModel deviceStatus; const StatusUpdated(this.deviceStatus); diff --git a/lib/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart b/lib/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart index 08a65a11..c05b4e09 100644 --- a/lib/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart +++ b/lib/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart @@ -26,48 +26,53 @@ class CeilingSensorModel { }); factory CeilingSensorModel.fromJson(List jsonList) { - late String _presenceState = 'none'; - late int _sensitivity = 1; - late String _checkingResult = ''; - int _presenceRange = 1; - int _sportsPara = 1; - String _bodyMovement = 'none'; - String _noBodyTime = 'none'; - int _maxDis = 0; - SpaceTypes _spaceType = SpaceTypes.none; + late var presenceState = 'none'; + late var sensitivity = 1; + late var checkingResult = ''; + var presenceRange = 1; + var sportsPara = 1; + var bodyMovement = 'none'; + var noBodyTime = 'none'; + var maxDis = 0; + var spaceType = SpaceTypes.none; try { - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'presence_state': - _presenceState = status.value ?? 'none'; + presenceState = status.value ?? 'none'; break; case 'scene': - _spaceType = getSpaceType(status.value ?? 'none'); + spaceType = getSpaceType(status.value ?? 'none'); break; case 'sensitivity': - _sensitivity = - status.value is int ? status.value : int.tryParse(status.value ?? '1') ?? 1; + sensitivity = status.value is int + ? status.value + : int.tryParse(status.value ?? '1') ?? 1; break; case 'checking_result': - _checkingResult = status.value ?? ''; + checkingResult = status.value ?? ''; break; case 'presence_range': - _presenceRange = - status.value is int ? status.value : int.tryParse(status.value ?? '0') ?? 0; + presenceRange = status.value is int + ? status.value + : int.tryParse(status.value ?? '0') ?? 0; break; case 'sports_para': - _sportsPara = - status.value is int ? status.value : int.tryParse(status.value ?? '0') ?? 0; + sportsPara = status.value is int + ? status.value + : int.tryParse(status.value ?? '0') ?? 0; break; case 'body_movement': - _bodyMovement = status.value ?? ''; + bodyMovement = status.value ?? ''; break; case 'nobody_time': - _noBodyTime = status.value ?? 'none'; + noBodyTime = status.value ?? 'none'; break; case 'moving_max_dis': - _maxDis = status.value is int ? status.value : int.tryParse(status.value ?? '0') ?? 0; + maxDis = status.value is int + ? status.value + : int.tryParse(status.value ?? '0') ?? 0; break; } } @@ -76,15 +81,15 @@ class CeilingSensorModel { } return CeilingSensorModel( - presenceState: _presenceState, - sensitivity: _sensitivity, - checkingResult: _checkingResult, - presenceRange: _presenceRange, - sportsPara: _sportsPara, - bodyMovement: _bodyMovement, - noBodyTime: _noBodyTime, - maxDistance: _maxDis, - spaceType: _spaceType, + presenceState: presenceState, + sensitivity: sensitivity, + checkingResult: checkingResult, + presenceRange: presenceRange, + sportsPara: sportsPara, + bodyMovement: bodyMovement, + noBodyTime: noBodyTime, + maxDistance: maxDis, + spaceType: spaceType, ); } diff --git a/lib/pages/device_managment/ceiling_sensor/view/ceiling_sensor_batch_control.dart b/lib/pages/device_managment/ceiling_sensor/view/ceiling_sensor_batch_control.dart index 9b5ab360..3f57e7a1 100644 --- a/lib/pages/device_managment/ceiling_sensor/view/ceiling_sensor_batch_control.dart +++ b/lib/pages/device_managment/ceiling_sensor/view/ceiling_sensor_batch_control.dart @@ -12,7 +12,8 @@ import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presen import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presense_nobody_time.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class CeilingSensorBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class CeilingSensorBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const CeilingSensorBatchControlView({super.key, required this.devicesIds}); final List devicesIds; @@ -28,11 +29,12 @@ class CeilingSensorBatchControlView extends StatelessWidget with HelperResponsiv )..add(CeilingFetchDeviceStatusEvent(devicesIds)), child: BlocBuilder( builder: (context, state) { - if (state is CeilingLoadingInitialState || state is CeilingReportsLoadingState) { + if (state is CeilingLoadingInitialState || + state is CeilingReportsLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is CeilingUpdateState) { - return _buildGridView( - context, state.ceilingSensorModel, isExtraLarge, isLarge, isMedium); + return _buildGridView(context, state.ceilingSensorModel, + isExtraLarge, isLarge, isMedium); } return const Center(child: Text('Error fetching status')); }, @@ -40,8 +42,8 @@ class CeilingSensorBatchControlView extends StatelessWidget with HelperResponsiv ); } - Widget _buildGridView(BuildContext context, CeilingSensorModel model, bool isExtraLarge, - bool isLarge, bool isMedium) { + Widget _buildGridView(BuildContext context, CeilingSensorModel model, + bool isExtraLarge, bool isLarge, bool isMedium) { return GridView( padding: const EdgeInsets.symmetric(horizontal: 50), shrinkWrap: true, @@ -116,7 +118,8 @@ class CeilingSensorBatchControlView extends StatelessWidget with HelperResponsiv context.read().add( CeilingFactoryResetEvent( devicesId: devicesIds.first, - factoryResetModel: FactoryResetModel(devicesUuid: devicesIds), + factoryResetModel: + FactoryResetModel(devicesUuid: devicesIds), ), ); }, diff --git a/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart b/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart index 749a7729..f75ff8b4 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart @@ -34,7 +34,8 @@ class CurtainBloc extends Bloc { ) async { emit(CurtainStatusLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); _listenToChanges(event.deviceId, emit); deviceStatus = _checkStatus(status.status[0].value); emit(CurtainStatusLoaded(deviceStatus)); @@ -54,7 +55,7 @@ class CurtainBloc extends Bloc { final statusList = []; if (data['status'] != null) { - for (var element in data['status']) { + for (final element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -121,7 +122,8 @@ class CurtainBloc extends Bloc { ) async { emit(CurtainStatusLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final status = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = _checkStatus(status.status[0].value); emit(CurtainStatusLoaded(deviceStatus)); } catch (e) { diff --git a/lib/pages/device_managment/curtain/bloc/curtain_event.dart b/lib/pages/device_managment/curtain/bloc/curtain_event.dart index dd6700f9..d8c85ccd 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_event.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_event.dart @@ -60,7 +60,8 @@ class CurtainFactoryReset extends CurtainEvent { @override List get props => [deviceId, factoryReset]; } + class StatusUpdated extends CurtainEvent { final bool deviceStatus; const StatusUpdated(this.deviceStatus); -} \ No newline at end of file +} diff --git a/lib/pages/device_managment/curtain/bloc/curtain_state.dart b/lib/pages/device_managment/curtain/bloc/curtain_state.dart index dfe11c2a..72d974f1 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_state.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_state.dart @@ -1,7 +1,6 @@ - import 'package:equatable/equatable.dart'; -sealed class CurtainState extends Equatable { +sealed class CurtainState extends Equatable { const CurtainState(); @override diff --git a/lib/pages/device_managment/curtain/model/curtain_model.dart b/lib/pages/device_managment/curtain/model/curtain_model.dart index 908415d5..0a400c38 100644 --- a/lib/pages/device_managment/curtain/model/curtain_model.dart +++ b/lib/pages/device_managment/curtain/model/curtain_model.dart @@ -12,8 +12,8 @@ class CurtainModel { }); factory CurtainModel.fromJson(dynamic json) { - var statusList = json['status'] as List; - List status = statusList.map((i) => Status.fromJson(i)).toList(); + final statusList = json['status'] as List; + final status = statusList.map((i) => Status.fromJson(i)).toList(); return CurtainModel( productUuid: json['productUuid'], diff --git a/lib/pages/device_managment/curtain/view/curtain_batch_status_view.dart b/lib/pages/device_managment/curtain/view/curtain_batch_status_view.dart index 41dcaf9e..ccb9613d 100644 --- a/lib/pages/device_managment/curtain/view/curtain_batch_status_view.dart +++ b/lib/pages/device_managment/curtain/view/curtain_batch_status_view.dart @@ -10,7 +10,8 @@ import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_ // import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class CurtainBatchStatusView extends StatelessWidget with HelperResponsiveLayout { +class CurtainBatchStatusView extends StatelessWidget + with HelperResponsiveLayout { const CurtainBatchStatusView({super.key, required this.devicesIds}); final List devicesIds; @@ -18,8 +19,8 @@ class CurtainBatchStatusView extends StatelessWidget with HelperResponsiveLayout @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => - CurtainBlocFactory.create(deviceId: devicesIds.first)..add(CurtainFetchBatchStatus(devicesIds)), + create: (context) => CurtainBlocFactory.create(deviceId: devicesIds.first) + ..add(CurtainFetchBatchStatus(devicesIds)), child: BlocBuilder( builder: (context, state) { if (state is CurtainStatusLoading) { diff --git a/lib/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart b/lib/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart index c996cf72..73e31f89 100644 --- a/lib/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart +++ b/lib/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart @@ -2,12 +2,13 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; -import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/device_info_model.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart'; +import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/device_info_model.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/sub_space_model.dart'; import 'package:syncrow_web/services/devices_mang_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart'; import 'package:syncrow_web/utils/snack_bar.dart'; + part 'setting_bloc_event.dart'; class SettingDeviceBloc extends Bloc { @@ -37,7 +38,7 @@ class SettingDeviceBloc extends Bloc { String? _fullNameValidator(String? value) { if (value == null) return 'name is required'; - final withoutExtraSpaces = value.replaceAll(RegExp(r"\s+"), ' ').trim(); + final withoutExtraSpaces = value.replaceAll(RegExp(r'\s+'), ' ').trim(); if (withoutExtraSpaces.length < 2 || withoutExtraSpaces.length > 30) { return 'name must be between 2 and 30 characters long'; } @@ -66,8 +67,8 @@ class SettingDeviceBloc extends Bloc { DeviceSettingInitialInfo event, Emitter emit) async { try { emit(DeviceSettingsLoading()); - var response = await DevicesManagementApi.getDeviceInfo(deviceId); - DeviceInfoModel deviceInfo = DeviceInfoModel.fromJson(response); + final response = await DevicesManagementApi.getDeviceInfo(deviceId); + final deviceInfo = DeviceInfoModel.fromJson(response); nameController.text = deviceInfo.name; emit(DeviceSettingsUpdate( deviceName: nameController.text, @@ -92,9 +93,7 @@ class SettingDeviceBloc extends Bloc { )); editName = event.value!; if (editName) { - Future.delayed(const Duration(milliseconds: 500), () { - focusNode.requestFocus(); - }); + Future.delayed(const Duration(milliseconds: 500), focusNode.requestFocus); } else { add(const SettingBlocSaveName()); focusNode.unfocus(); @@ -106,7 +105,7 @@ class SettingDeviceBloc extends Bloc { )); } - void _deleteDevice( + Future _deleteDevice( SettingBlocDeleteDevice event, Emitter emit) async { try { emit(DeviceSettingsLoading()); @@ -123,7 +122,7 @@ class SettingDeviceBloc extends Bloc { } } - void _onAssignDevice( + Future _onAssignDevice( SettingBlocAssignRoom event, Emitter emit) async { try { emit(DeviceSettingsLoading()); @@ -143,7 +142,7 @@ class SettingDeviceBloc extends Bloc { } } - void _fetchRooms( + Future _fetchRooms( SettingBlocFetchRooms event, Emitter emit) async { try { emit(DeviceSettingsLoading()); diff --git a/lib/pages/device_managment/device_setting/device_settings_panel.dart b/lib/pages/device_managment/device_setting/device_settings_panel.dart index 48458b3b..cea5bea6 100644 --- a/lib/pages/device_managment/device_setting/device_settings_panel.dart +++ b/lib/pages/device_managment/device_setting/device_settings_panel.dart @@ -2,12 +2,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart'; +import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart'; +import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/device_icon_type_helper.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/device_management_content.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/remove_device_widget.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/device_info_model.dart'; -import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart'; -import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart'; import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/sub_space_model.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; @@ -38,7 +38,7 @@ class DeviceSettingsPanel extends StatelessWidget { builder: (context) { return BlocBuilder( builder: (context, state) { - final _bloc = context.read(); + final bloc = context.read(); final iconPath = DeviceIconTypeHelper.getDeviceIconByTypeCode( device.productType); final deviceInfo = state is DeviceSettingsUpdate @@ -73,7 +73,7 @@ class DeviceSettingsPanel extends StatelessWidget { .copyWith( fontWeight: FontWeight.w700, color: ColorsManager.vividBlue - .withOpacity(0.7), + .withValues(alpha: 0.7), fontSize: 24), ), ], @@ -87,8 +87,8 @@ class DeviceSettingsPanel extends StatelessWidget { padding: const EdgeInsets.only(left: 15), child: CircleAvatar( radius: 38, - backgroundColor: - ColorsManager.grayBorder.withOpacity(0.5), + backgroundColor: ColorsManager.grayBorder + .withValues(alpha: 0.5), child: CircleAvatar( backgroundColor: ColorsManager.whiteColors, radius: 36, @@ -128,14 +128,14 @@ class DeviceSettingsPanel extends StatelessWidget { fontSize: 16, ), textAlign: TextAlign.start, - focusNode: _bloc.focusNode, - controller: _bloc.nameController, - enabled: _bloc.editName, + focusNode: bloc.focusNode, + controller: bloc.nameController, + enabled: bloc.editName, onFieldSubmitted: (value) { - _bloc.add(const ChangeNameEvent( + bloc.add(const ChangeNameEvent( value: false)); }, - decoration: InputDecoration( + decoration: const InputDecoration( isDense: true, contentPadding: EdgeInsets.zero, border: InputBorder.none, @@ -151,11 +151,11 @@ class DeviceSettingsPanel extends StatelessWidget { height: 25, child: Visibility( visible: - _bloc.editName != true, + bloc.editName != true, replacement: const SizedBox(), child: InkWell( onTap: () { - _bloc.add( + bloc.add( const ChangeNameEvent( value: true)); }, @@ -192,14 +192,14 @@ class DeviceSettingsPanel extends StatelessWidget { deviceInfo: deviceInfo, ), const SizedBox(height: 32), - RemoveDeviceWidget(bloc: _bloc), + RemoveDeviceWidget(bloc: bloc), ], ), ), if (state is DeviceSettingsLoading) Positioned.fill( - child: Container( - color: Colors.black.withOpacity(0.1), + child: ColoredBox( + color: Colors.black.withValues(alpha: 0.1), child: const Center( child: CircularProgressIndicator( color: ColorsManager.primaryColor, diff --git a/lib/pages/device_managment/device_setting/settings_model/sub_space_model.dart b/lib/pages/device_managment/device_setting/settings_model/sub_space_model.dart index 9d3f4036..f4ab1cd0 100644 --- a/lib/pages/device_managment/device_setting/settings_model/sub_space_model.dart +++ b/lib/pages/device_managment/device_setting/settings_model/sub_space_model.dart @@ -20,9 +20,9 @@ class SubSpaceModel { } factory SubSpaceModel.fromJson(Map json) { - List devices = []; + final devices = []; if (json['devices'] != null) { - for (var device in json['devices']) { + for (final device in json['devices']) { devices.add(DeviceModel.fromJson(device)); } } diff --git a/lib/pages/device_managment/device_setting/sub_space_dialog.dart b/lib/pages/device_managment/device_setting/sub_space_dialog.dart index 28350d4d..2b909a85 100644 --- a/lib/pages/device_managment/device_setting/sub_space_dialog.dart +++ b/lib/pages/device_managment/device_setting/sub_space_dialog.dart @@ -12,11 +12,11 @@ class SubSpaceDialog extends StatefulWidget { final void Function(SubSpaceModel?) onConfirmed; const SubSpaceDialog({ - Key? key, + super.key, required this.subSpaces, this.selected, required this.onConfirmed, - }) : super(key: key); + }); @override State createState() => _SubSpaceDialogState(); @@ -63,7 +63,7 @@ class _SubSpaceDialogState extends State { _selectedId = value; }); }, - activeColor: Color(0xFF2962FF), + activeColor: const Color(0xFF2962FF), title: Text( space.name ?? 'Unnamed Sub-Space', style: context.textTheme.bodyMedium?.copyWith( @@ -75,7 +75,7 @@ class _SubSpaceDialogState extends State { controlAffinity: ListTileControlAffinity.trailing, contentPadding: const EdgeInsets.symmetric(horizontal: 24), ); - }).toList(), + }), const SizedBox(height: 12), const Divider(height: 1, thickness: 1), SubSpaceDialogButtons(selectedId: _selectedId, widget: widget), diff --git a/lib/pages/device_managment/door_lock/bloc/door_lock_bloc.dart b/lib/pages/device_managment/door_lock/bloc/door_lock_bloc.dart index f83ced1a..a42f4352 100644 --- a/lib/pages/device_managment/door_lock/bloc/door_lock_bloc.dart +++ b/lib/pages/device_managment/door_lock/bloc/door_lock_bloc.dart @@ -22,17 +22,15 @@ class DoorLockBloc extends Bloc { on(_onStatusUpdated); } - _listenToChanges(deviceId) { + void _listenToChanges(deviceId) { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$deviceId'); - Stream stream = ref.onValue; + final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + final stream = ref.onValue; stream.listen((DatabaseEvent event) { - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); diff --git a/lib/pages/device_managment/door_lock/bloc/door_lock_state.dart b/lib/pages/device_managment/door_lock/bloc/door_lock_state.dart index 39c4ca16..8bbb3c03 100644 --- a/lib/pages/device_managment/door_lock/bloc/door_lock_state.dart +++ b/lib/pages/device_managment/door_lock/bloc/door_lock_state.dart @@ -1,4 +1,3 @@ - import 'package:equatable/equatable.dart'; import 'package:syncrow_web/pages/device_managment/door_lock/models/door_lock_status_model.dart'; diff --git a/lib/pages/device_managment/door_lock/models/door_lock_status_model.dart b/lib/pages/device_managment/door_lock/models/door_lock_status_model.dart index cda512c5..9dca688b 100644 --- a/lib/pages/device_managment/door_lock/models/door_lock_status_model.dart +++ b/lib/pages/device_managment/door_lock/models/door_lock_status_model.dart @@ -60,7 +60,7 @@ class DoorLockStatusModel { late String remoteNoDpKey; late bool normalOpenSwitch; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'unlock_fingerprint': unlockFingerprint = status.value ?? 0; diff --git a/lib/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart b/lib/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart index b28737fc..e2d85df9 100644 --- a/lib/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart +++ b/lib/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart @@ -7,7 +7,8 @@ import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_ // import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class DoorLockBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class DoorLockBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const DoorLockBatchControlView({super.key, required this.devicesIds}); final List devicesIds; diff --git a/lib/pages/device_managment/door_lock/widget/door_button.dart b/lib/pages/device_managment/door_lock/widget/door_button.dart index e8e3066e..6bf8acf6 100644 --- a/lib/pages/device_managment/door_lock/widget/door_button.dart +++ b/lib/pages/device_managment/door_lock/widget/door_button.dart @@ -90,7 +90,7 @@ class _DoorLockButtonState extends State shape: BoxShape.circle, boxShadow: [ BoxShadow( - color: Colors.grey.withOpacity(0.5), + color: Colors.grey.withValues(alpha: 0.5), blurRadius: 18, blurStyle: BlurStyle.outer, ), diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart index aea800dd..f4b933ae 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart @@ -15,8 +15,8 @@ import 'package:syncrow_web/services/devices_mang_api.dart'; part 'flush_mounted_presence_sensor_event.dart'; part 'flush_mounted_presence_sensor_state.dart'; -class FlushMountedPresenceSensorBloc - extends Bloc { +class FlushMountedPresenceSensorBloc extends Bloc< + FlushMountedPresenceSensorEvent, FlushMountedPresenceSensorState> { final String deviceId; final ControlDeviceService controlDeviceService; final BatchControlDevicesService batchControlDevicesService; @@ -54,7 +54,7 @@ class FlushMountedPresenceSensorBloc ); } - void _onFlushMountedPresenceSensorFetchStatusEvent( + Future _onFlushMountedPresenceSensorFetchStatusEvent( FlushMountedPresenceSensorFetchStatusEvent event, Emitter emit, ) async { @@ -76,7 +76,8 @@ class FlushMountedPresenceSensorBloc ) async { emit(FlushMountedPresenceSensorLoadingInitialState()); try { - final response = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final response = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = FlushMountedPresenceSensorModel.fromJson(response.status); emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus)); } catch (e) { @@ -91,9 +92,9 @@ class FlushMountedPresenceSensorBloc ); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value as Map; + final eventsMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -113,7 +114,7 @@ class FlushMountedPresenceSensorBloc } } - void _onFlushMountedPresenceSensorChangeValueEvent( + Future _onFlushMountedPresenceSensorChangeValueEvent( FlushMountedPresenceSensorChangeValueEvent event, Emitter emit, ) async { @@ -196,7 +197,8 @@ class FlushMountedPresenceSensorBloc deviceReport: value, code: event.code)); }); } catch (e) { - emit(FlushMountedPresenceSensorDeviceReportsFailedState(error: e.toString())); + emit(FlushMountedPresenceSensorDeviceReportsFailedState( + error: e.toString())); return; } } diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_event.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_event.dart index 08a01615..e7fe8156 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_event.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_event.dart @@ -59,7 +59,8 @@ class FlushMountedPresenceSensorGetDeviceReportsEvent class FlushMountedPresenceSensorShowDescriptionEvent extends FlushMountedPresenceSensorEvent { final String description; - const FlushMountedPresenceSensorShowDescriptionEvent({required this.description}); + const FlushMountedPresenceSensorShowDescriptionEvent( + {required this.description}); } class FlushMountedPresenceSensorBackToGridViewEvent diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_state.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_state.dart index 0fef07f2..e88a9ad8 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_state.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_state.dart @@ -13,7 +13,8 @@ class FlushMountedPresenceSensorInitialState class FlushMountedPresenceSensorLoadingInitialState extends FlushMountedPresenceSensorState {} -class FlushMountedPresenceSensorUpdateState extends FlushMountedPresenceSensorState { +class FlushMountedPresenceSensorUpdateState + extends FlushMountedPresenceSensorState { final FlushMountedPresenceSensorModel model; const FlushMountedPresenceSensorUpdateState({required this.model}); @@ -30,7 +31,8 @@ class FlushMountedPresenceSensorLoadingNewSate List get props => [model]; } -class FlushMountedPresenceSensorFailedState extends FlushMountedPresenceSensorState { +class FlushMountedPresenceSensorFailedState + extends FlushMountedPresenceSensorState { final String error; const FlushMountedPresenceSensorFailedState({required this.error}); @@ -58,7 +60,8 @@ class FlushMountedPresenceSensorDeviceReportsState class FlushMountedPresenceSensorDeviceReportsFailedState extends FlushMountedPresenceSensorState { - const FlushMountedPresenceSensorDeviceReportsFailedState({required this.error}); + const FlushMountedPresenceSensorDeviceReportsFailedState( + {required this.error}); final String error; @@ -68,7 +71,8 @@ class FlushMountedPresenceSensorDeviceReportsFailedState class FlushMountedPresenceSensorShowDescriptionState extends FlushMountedPresenceSensorState { - const FlushMountedPresenceSensorShowDescriptionState({required this.description}); + const FlushMountedPresenceSensorShowDescriptionState( + {required this.description}); final String description; @override diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart index e842f36b..e1458dc9 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart @@ -9,8 +9,10 @@ abstract final class FlushMountedPresenceSensorBlocFactory { }) { return FlushMountedPresenceSensorBloc( deviceId: deviceId, - controlDeviceService: DeviceBlocDependenciesFactory.createControlDeviceService(), - batchControlDevicesService: DeviceBlocDependenciesFactory.createBatchControlDevicesService(), + controlDeviceService: + DeviceBlocDependenciesFactory.createControlDeviceService(), + batchControlDevicesService: + DeviceBlocDependenciesFactory.createBatchControlDevicesService(), ); } } diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart index bf97005d..106a9942 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart @@ -37,18 +37,18 @@ class FlushMountedPresenceSensorModel { int sensiReduce; factory FlushMountedPresenceSensorModel.fromJson(List jsonList) { - String presenceState = 'none'; - int sensitivity = 0; - int nearDetection = 0; - int farDetection = 0; - String checkingResult = 'none'; - int presenceDelay = 0; - int noneDelay = 0; - int occurDistReduce = 0; - int illuminance = 0; - int sensiReduce = 0; + var presenceState = 'none'; + var sensitivity = 0; + var nearDetection = 0; + var farDetection = 0; + var checkingResult = 'none'; + var presenceDelay = 0; + var noneDelay = 0; + var occurDistReduce = 0; + var illuminance = 0; + var sensiReduce = 0; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case codePresenceState: presenceState = status.value ?? 'presence'; @@ -97,7 +97,3 @@ class FlushMountedPresenceSensorModel { ); } } - - - - diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart index 2860e5cc..589b6b0e 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart @@ -66,13 +66,14 @@ class FlushMountedPresenceSensorBatchControlView extends StatelessWidget minValue: 0, maxValue: 9, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorBatchControlEvent( - deviceIds: devicesIds, - code: FlushMountedPresenceSensorModel.codeSensitivity, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorBatchControlEvent( + deviceIds: devicesIds, + code: FlushMountedPresenceSensorModel.codeSensitivity, + value: value, + ), + ), ), PresenceUpdateData( value: (model.nearDetection / 100).clamp(0.0, double.infinity), @@ -114,13 +115,14 @@ class FlushMountedPresenceSensorBatchControlView extends StatelessWidget minValue: 0, maxValue: 3, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorBatchControlEvent( - deviceIds: devicesIds, - code: FlushMountedPresenceSensorModel.codeSensiReduce, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorBatchControlEvent( + deviceIds: devicesIds, + code: FlushMountedPresenceSensorModel.codeSensiReduce, + value: value, + ), + ), ), PresenceUpdateData( value: model.occurDistReduce.toDouble(), @@ -128,16 +130,17 @@ class FlushMountedPresenceSensorBatchControlView extends StatelessWidget minValue: 0, maxValue: 3, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorBatchControlEvent( - deviceIds: devicesIds, - code: FlushMountedPresenceSensorModel.codeOccurDistReduce, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorBatchControlEvent( + deviceIds: devicesIds, + code: FlushMountedPresenceSensorModel.codeOccurDistReduce, + value: value, + ), + ), ), PresenceUpdateData( - value: (model.presenceDelay / 10).toDouble(), + value: model.presenceDelay / 10, title: 'Target Confirm Time:', description: 's', minValue: 0.0, @@ -154,7 +157,7 @@ class FlushMountedPresenceSensorBatchControlView extends StatelessWidget ), ), PresenceUpdateData( - value: ((model.noneDelay / 10).toDouble()), + value: model.noneDelay / 10, description: 's', title: 'Disappe Delay:', minValue: 20, diff --git a/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart b/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart index 08ad809d..098dbb61 100644 --- a/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart +++ b/lib/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart @@ -15,7 +15,8 @@ import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_la class FlushMountedPresenceSensorControlView extends StatelessWidget with HelperResponsiveLayout { - const FlushMountedPresenceSensorControlView({required this.device, super.key}); + const FlushMountedPresenceSensorControlView( + {required this.device, super.key}); final AllDevicesModel device; @@ -37,9 +38,9 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget return ReportsTable( report: state.deviceReport, thirdColumnTitle: - state.code == 'illuminance_value' ? "Value" : 'Status', + state.code == 'illuminance_value' ? 'Value' : 'Status', thirdColumnDescription: - state.code == 'illuminance_value' ? "Lux" : null, + state.code == 'illuminance_value' ? 'Lux' : null, onRowTap: (index) {}, onClose: () { context @@ -56,7 +57,8 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget .add(FlushMountedPresenceSensorBackToGridViewEvent()); }, ); - } else if (state is FlushMountedPresenceSensorDeviceReportsFailedState) { + } else if (state + is FlushMountedPresenceSensorDeviceReportsFailedState) { final model = context.read().deviceStatus; return _buildGridView(context, model); @@ -105,12 +107,13 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget minValue: 0, maxValue: 9, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorChangeValueEvent( - code: FlushMountedPresenceSensorModel.codeSensitivity, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorChangeValueEvent( + code: FlushMountedPresenceSensorModel.codeSensitivity, + value: value, + ), + ), ), PresenceUpdateData( value: (model.nearDetection / 100).clamp(0.0, double.infinity), @@ -150,12 +153,13 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget minValue: 0, maxValue: 3, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorChangeValueEvent( - code: FlushMountedPresenceSensorModel.codeSensiReduce, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorChangeValueEvent( + code: FlushMountedPresenceSensorModel.codeSensiReduce, + value: value, + ), + ), ), PresenceUpdateData( value: model.occurDistReduce.toDouble(), @@ -163,15 +167,16 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget minValue: 0, maxValue: 3, steps: 1, - action: (int value) => context.read().add( - FlushMountedPresenceSensorChangeValueEvent( - code: FlushMountedPresenceSensorModel.codeOccurDistReduce, - value: value, - ), - ), + action: (int value) => + context.read().add( + FlushMountedPresenceSensorChangeValueEvent( + code: FlushMountedPresenceSensorModel.codeOccurDistReduce, + value: value, + ), + ), ), PresenceUpdateData( - value: (model.presenceDelay / 10).toDouble(), + value: model.presenceDelay / 10, valuesPercision: 1, title: 'Target Confirm Time:', description: 's', @@ -187,7 +192,7 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget ), ), PresenceUpdateData( - value: (model.noneDelay / 10).toDouble(), + value: model.noneDelay / 10, description: 's', title: 'Disappe Delay:', minValue: 20, diff --git a/lib/pages/device_managment/garage_door/bloc/garage_door_bloc.dart b/lib/pages/device_managment/garage_door/bloc/garage_door_bloc.dart index 28a7e33b..48fd146b 100644 --- a/lib/pages/device_managment/garage_door/bloc/garage_door_bloc.dart +++ b/lib/pages/device_managment/garage_door/bloc/garage_door_bloc.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:firebase_database/firebase_database.dart'; -import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_event.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_state.dart'; @@ -42,17 +41,15 @@ class GarageDoorBloc extends Bloc { on(_onEditSchedule); on(_onStatusUpdated); } - _listenToChanges(deviceId) { + void _listenToChanges(deviceId) { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$deviceId'); - Stream stream = ref.onValue; + final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + final stream = ref.onValue; stream.listen((DatabaseEvent event) { - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); @@ -72,11 +69,11 @@ class GarageDoorBloc extends Bloc { emit(GarageDoorLoadedState(status: deviceStatus)); } - void _fetchGarageDoorStatus( + Future _fetchGarageDoorStatus( GarageDoorInitialEvent event, Emitter emit) async { emit(GarageDoorLoadingState()); try { - var response = + final response = await DevicesManagementApi().getDeviceStatus(event.deviceId); deviceStatus = GarageDoorStatusModel.fromJson(deviceId, response.status); _listenToChanges(deviceId); @@ -103,13 +100,13 @@ class GarageDoorBloc extends Bloc { Future _addSchedule( AddGarageDoorScheduleEvent event, Emitter emit) async { try { - ScheduleEntry newSchedule = ScheduleEntry( + final newSchedule = ScheduleEntry( category: event.category, time: formatTimeOfDayToISO(event.time), function: Status(code: 'doorcontact_state', value: event.functionOn), days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - bool success = + final success = await DevicesManagementApi().addScheduleRecord(newSchedule, deviceId); if (success) { add(FetchGarageDoorSchedulesEvent( @@ -156,7 +153,7 @@ class GarageDoorBloc extends Bloc { } return schedule; }).toList(); - bool success = await DevicesManagementApi().updateScheduleRecord( + final success = await DevicesManagementApi().updateScheduleRecord( enable: event.enable, uuid: deviceStatus.uuid, scheduleId: event.scheduleId, @@ -175,7 +172,7 @@ class GarageDoorBloc extends Bloc { Future _deleteSchedule(DeleteGarageDoorScheduleEvent event, Emitter emit) async { try { - bool success = await DevicesManagementApi() + final success = await DevicesManagementApi() .deleteScheduleRecord(deviceStatus.uuid, event.scheduleId); if (success) { final updatedSchedules = deviceStatus.schedules @@ -195,7 +192,7 @@ class GarageDoorBloc extends Bloc { Emitter emit) async { emit(ScheduleGarageLoadingState()); try { - List schedules = await DevicesManagementApi() + final schedules = await DevicesManagementApi() .getDeviceSchedules(deviceStatus.uuid, event.category); deviceStatus = deviceStatus.copyWith(schedules: schedules); emit( @@ -226,7 +223,7 @@ class GarageDoorBloc extends Bloc { UpdateSelectedDayEvent event, Emitter emit) async { final currentState = state; if (currentState is GarageDoorLoadedState) { - List updatedDays = List.from(currentState.selectedDays); + final updatedDays = List.from(currentState.selectedDays); updatedDays[event.dayIndex] = event.isSelected; emit(currentState.copyWith( selectedDays: updatedDays, selectedTime: currentState.selectedTime)); @@ -264,9 +261,8 @@ class GarageDoorBloc extends Bloc { .subtract(const Duration(days: 30)) .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final DeviceReport records = - await DevicesManagementApi.getDeviceReportsByDate( - event.deviceId, 'switch_1', from.toString(), to.toString()); + final records = await DevicesManagementApi.getDeviceReportsByDate( + event.deviceId, 'switch_1', from.toString(), to.toString()); emit(GarageDoorReportsState(deviceReport: records)); } catch (e) { emit(GarageDoorReportsFailedState(error: e.toString())); @@ -352,12 +348,12 @@ class GarageDoorBloc extends Bloc { } } - void _increaseDelay( + Future _increaseDelay( IncreaseGarageDoorDelayEvent event, Emitter emit) async { // if (deviceStatus.countdown1 != 0) { try { deviceStatus = deviceStatus.copyWith( - delay: deviceStatus.delay + Duration(minutes: 10)); + delay: deviceStatus.delay + const Duration(minutes: 10)); emit(GarageDoorLoadedState(status: deviceStatus)); add(GarageDoorControlEvent( deviceId: deviceId, @@ -369,13 +365,13 @@ class GarageDoorBloc extends Bloc { // } } - void _decreaseDelay( + Future _decreaseDelay( DecreaseGarageDoorDelayEvent event, Emitter emit) async { // if (deviceStatus.countdown1 != 0) { try { if (deviceStatus.delay.inMinutes > 10) { deviceStatus = deviceStatus.copyWith( - delay: deviceStatus.delay - Duration(minutes: 10)); + delay: deviceStatus.delay - const Duration(minutes: 10)); } emit(GarageDoorLoadedState(status: deviceStatus)); add(GarageDoorControlEvent( @@ -388,7 +384,7 @@ class GarageDoorBloc extends Bloc { //} } - void _garageDoorControlEvent( + Future _garageDoorControlEvent( GarageDoorControlEvent event, Emitter emit) async { final oldValue = event.code == 'countdown_1' ? deviceStatus.countdown1 @@ -489,14 +485,14 @@ class GarageDoorBloc extends Bloc { FutureOr _onEditSchedule( EditGarageDoorScheduleEvent event, Emitter emit) async { try { - ScheduleEntry newSchedule = ScheduleEntry( + final newSchedule = ScheduleEntry( scheduleId: event.scheduleId, category: event.category, time: formatTimeOfDayToISO(event.time), function: Status(code: 'doorcontact_state', value: event.functionOn), days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - bool success = await DevicesManagementApi() + final success = await DevicesManagementApi() .editScheduleRecord(deviceId, newSchedule); if (success) { add(FetchGarageDoorSchedulesEvent( diff --git a/lib/pages/device_managment/garage_door/helper/garage_door_helper.dart b/lib/pages/device_managment/garage_door/helper/garage_door_helper.dart index 7b133d45..4600a685 100644 --- a/lib/pages/device_managment/garage_door/helper/garage_door_helper.dart +++ b/lib/pages/device_managment/garage_door/helper/garage_door_helper.dart @@ -18,7 +18,7 @@ class GarageDoorDialogHelper { final bloc = context.read(); if (schedule == null) { - bloc.add((const UpdateSelectedTimeEvent(null))); + bloc.add(const UpdateSelectedTimeEvent(null)); bloc.add(InitializeAddScheduleEvent( selectedTime: null, selectedDays: List.filled(7, false), @@ -77,9 +77,10 @@ class GarageDoorDialogHelper { backgroundColor: ColorsManager.boxColor, borderRadius: 15, onPressed: () async { - TimeOfDay? time = await showTimePicker( + final time = await showTimePicker( context: context, - initialTime: state.selectedTime ?? TimeOfDay.now(), + initialTime: + state.selectedTime ?? TimeOfDay.now(), builder: (context, child) { return Theme( data: Theme.of(context).copyWith( @@ -99,7 +100,9 @@ class GarageDoorDialogHelper { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - state.selectedTime == null ? 'Time' : state.selectedTime!.format(context), + state.selectedTime == null + ? 'Time' + : state.selectedTime!.format(context), style: context.textTheme.bodySmall!.copyWith( color: ColorsManager.grayColor, ), @@ -114,7 +117,8 @@ class GarageDoorDialogHelper { ), ), const SizedBox(height: 16), - _buildDayCheckboxes(context, state.selectedDays, isEdit: isEdit), + _buildDayCheckboxes(context, state.selectedDays, + isEdit: isEdit), const SizedBox(height: 16), _buildFunctionSwitch(context, state.functionOn, isEdit), ], @@ -188,9 +192,9 @@ class GarageDoorDialogHelper { static List _convertDaysStringToBooleans(List selectedDays) { final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - List daysBoolean = List.filled(7, false); + final daysBoolean = List.filled(7, false); - for (int i = 0; i < daysOfWeek.length; i++) { + for (var i = 0; i < daysOfWeek.length; i++) { if (selectedDays.contains(daysOfWeek[i])) { daysBoolean[i] = true; } @@ -199,7 +203,9 @@ class GarageDoorDialogHelper { return daysBoolean; } - static Widget _buildDayCheckboxes(BuildContext context, List selectedDays, {bool? isEdit}) { + static Widget _buildDayCheckboxes( + BuildContext context, List selectedDays, + {bool? isEdit}) { final dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; return Row( @@ -209,7 +215,9 @@ class GarageDoorDialogHelper { Checkbox( value: selectedDays[index], onChanged: (bool? value) { - context.read().add(UpdateSelectedDayEvent(index, value!)); + context + .read() + .add(UpdateSelectedDayEvent(index, value!)); }, ), Text(dayLabels[index]), @@ -219,19 +227,23 @@ class GarageDoorDialogHelper { ); } - static Widget _buildFunctionSwitch(BuildContext context, bool isOn, bool? isEdit) { + static Widget _buildFunctionSwitch( + BuildContext context, bool isOn, bool? isEdit) { return Row( children: [ Text( 'Function:', - style: context.textTheme.bodySmall!.copyWith(color: ColorsManager.grayColor), + style: context.textTheme.bodySmall! + .copyWith(color: ColorsManager.grayColor), ), const SizedBox(width: 10), Radio( value: true, groupValue: isOn, onChanged: (bool? value) { - context.read().add(const UpdateFunctionOnEvent(functionOn: true)); + context + .read() + .add(const UpdateFunctionOnEvent(functionOn: true)); }, ), const Text('On'), @@ -240,7 +252,9 @@ class GarageDoorDialogHelper { value: false, groupValue: isOn, onChanged: (bool? value) { - context.read().add(const UpdateFunctionOnEvent(functionOn: false)); + context + .read() + .add(const UpdateFunctionOnEvent(functionOn: false)); }, ), const Text('Off'), @@ -297,13 +311,17 @@ class GarageDoorDialogHelper { alertBody: TimeOutAlarmDialogBody(bloc), title: 'Time Out Alarm', onConfirm: () { - final updatedState = context.read().state; - if (updatedState is GarageDoorLoadedState) { + final updatedState = + context.read().state; + if (updatedState + is GarageDoorLoadedState) { context.read().add( GarageDoorControlEvent( - deviceId: updatedState.status.uuid, + deviceId: + updatedState.status.uuid, code: 'countdown_alarm', - value: updatedState.status.countdownAlarm, + value: updatedState + .status.countdownAlarm, ), ); Navigator.pop(context); @@ -311,8 +329,11 @@ class GarageDoorDialogHelper { }); }, child: ToggleWidget( - icon: "-1", - value: state.status.doorState1 == "close_time_alarm" ? false : true, + icon: '-1', + value: state.status.doorState1 == + 'close_time_alarm' + ? false + : true, code: 'door_state_1', deviceId: bloc.deviceId, label: 'Alarm when door is open', @@ -321,9 +342,10 @@ class GarageDoorDialogHelper { GarageDoorControlEvent( deviceId: bloc.deviceId, code: 'door_state_1', - value: state.status.doorState1 == "close_time_alarm" - ? "unclosed_time" - : "close_time_alarm", + value: state.status.doorState1 == + 'close_time_alarm' + ? 'unclosed_time' + : 'close_time_alarm', ), ); }), @@ -348,13 +370,17 @@ class GarageDoorDialogHelper { ), title: 'Opening and Closing Time', onConfirm: () { - final updatedState = context.read().state; - if (updatedState is GarageDoorLoadedState) { + final updatedState = + context.read().state; + if (updatedState + is GarageDoorLoadedState) { context.read().add( GarageDoorControlEvent( - deviceId: updatedState.status.uuid, + deviceId: + updatedState.status.uuid, code: 'tr_timecon', - value: updatedState.status.trTimeCon, + value: updatedState + .status.trTimeCon, ), ); Navigator.pop(context); diff --git a/lib/pages/device_managment/garage_door/models/garage_door_model.dart b/lib/pages/device_managment/garage_door/models/garage_door_model.dart index 60d37d9f..4c991a9f 100644 --- a/lib/pages/device_managment/garage_door/models/garage_door_model.dart +++ b/lib/pages/device_managment/garage_door/models/garage_door_model.dart @@ -39,9 +39,9 @@ class GarageDoorStatusModel { late String doorControl1; late bool voiceControl1; late String doorState1; - List schedules = []; // Initialize schedules + final schedules = []; // Initialize schedules - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; diff --git a/lib/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart b/lib/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart index 9b3159bb..d21db9db 100644 --- a/lib/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart +++ b/lib/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart @@ -11,10 +11,11 @@ import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class GarageDoorBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class GarageDoorBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const GarageDoorBatchControlView({Key? key, required this.deviceIds}) : super(key: key); + const GarageDoorBatchControlView({super.key, required this.deviceIds}); @override Widget build(BuildContext context) { @@ -37,7 +38,8 @@ class GarageDoorBatchControlView extends StatelessWidget with HelperResponsiveLa ); } - Widget _buildStatusControls(BuildContext context, GarageDoorStatusModel status) { + Widget _buildStatusControls( + BuildContext context, GarageDoorStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); diff --git a/lib/pages/device_managment/garage_door/widgets/opening_clsoing_time_dialog_body.dart b/lib/pages/device_managment/garage_door/widgets/opening_clsoing_time_dialog_body.dart index 843bac9b..403beb85 100644 --- a/lib/pages/device_managment/garage_door/widgets/opening_clsoing_time_dialog_body.dart +++ b/lib/pages/device_managment/garage_door/widgets/opening_clsoing_time_dialog_body.dart @@ -1,4 +1,3 @@ -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_bloc.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_state.dart'; @@ -8,7 +7,8 @@ class OpeningAndClosingTimeDialogBody extends StatefulWidget { final ValueChanged onDurationChanged; final GarageDoorBloc bloc; - OpeningAndClosingTimeDialogBody({ + const OpeningAndClosingTimeDialogBody({ + super.key, required this.onDurationChanged, required this.bloc, }); diff --git a/lib/pages/device_managment/garage_door/widgets/schedule__garage_table.dart b/lib/pages/device_managment/garage_door/widgets/schedule__garage_table.dart index 07cd9c7a..238b7ad7 100644 --- a/lib/pages/device_managment/garage_door/widgets/schedule__garage_table.dart +++ b/lib/pages/device_managment/garage_door/widgets/schedule__garage_table.dart @@ -26,7 +26,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { Table( border: TableBorder.all( color: ColorsManager.graysColor, - borderRadius: const BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)), + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(20), topRight: Radius.circular(20)), ), children: [ TableRow( @@ -50,17 +51,21 @@ class ScheduleGarageTableWidget extends StatelessWidget { BlocBuilder( builder: (context, state) { if (state is ScheduleGarageLoadingState) { - return const SizedBox(height: 200, child: Center(child: CircularProgressIndicator())); + return const SizedBox( + height: 200, + child: Center(child: CircularProgressIndicator())); } - if (state is GarageDoorLoadedState && state.status.schedules?.isEmpty == true) { + if (state is GarageDoorLoadedState && + state.status.schedules?.isEmpty == true) { return _buildEmptyState(context); } else if (state is GarageDoorLoadedState) { return Container( height: 200, decoration: BoxDecoration( border: Border.all(color: ColorsManager.graysColor), - borderRadius: - const BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(20), + bottomRight: Radius.circular(20)), ), child: _buildTableBody(state, context)); } @@ -78,7 +83,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { height: 200, decoration: BoxDecoration( border: Border.all(color: ColorsManager.graysColor), - borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), + borderRadius: const BorderRadius.only( + bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), ), child: Center( child: Column( @@ -112,7 +118,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { children: [ if (state.status.schedules != null) for (int i = 0; i < state.status.schedules!.length; i++) - _buildScheduleRow(state.status.schedules![i], i, context, state), + _buildScheduleRow( + state.status.schedules![i], i, context, state), ], ), ), @@ -134,7 +141,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { ); } - TableRow _buildScheduleRow(ScheduleModel schedule, int index, BuildContext context, GarageDoorLoadedState state) { + TableRow _buildScheduleRow(ScheduleModel schedule, int index, + BuildContext context, GarageDoorLoadedState state) { return TableRow( children: [ Center( @@ -152,7 +160,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { width: 24, height: 24, child: schedule.enable - ? const Icon(Icons.radio_button_checked, color: ColorsManager.blueColor) + ? const Icon(Icons.radio_button_checked, + color: ColorsManager.blueColor) : const Icon( Icons.radio_button_unchecked, color: ColorsManager.grayColor, @@ -160,7 +169,9 @@ class ScheduleGarageTableWidget extends StatelessWidget { ), ), ), - Center(child: Text(_getSelectedDays(ScheduleModel.parseSelectedDays(schedule.days)))), + Center( + child: Text(_getSelectedDays( + ScheduleModel.parseSelectedDays(schedule.days)))), Center(child: Text(formatIsoStringToTime(schedule.time, context))), Center(child: Text(schedule.function.value ? 'On' : 'Off')), Center( @@ -170,18 +181,24 @@ class ScheduleGarageTableWidget extends StatelessWidget { TextButton( style: TextButton.styleFrom(padding: EdgeInsets.zero), onPressed: () { - GarageDoorDialogHelper.showAddGarageDoorScheduleDialog(context, - schedule: schedule, index: index, isEdit: true); + GarageDoorDialogHelper.showAddGarageDoorScheduleDialog( + context, + schedule: schedule, + index: index, + isEdit: true); }, child: Text( 'Edit', - style: context.textTheme.bodySmall!.copyWith(color: ColorsManager.blueColor), + style: context.textTheme.bodySmall! + .copyWith(color: ColorsManager.blueColor), ), ), TextButton( style: TextButton.styleFrom(padding: EdgeInsets.zero), onPressed: () { - context.read().add(DeleteGarageDoorScheduleEvent( + context + .read() + .add(DeleteGarageDoorScheduleEvent( index: index, scheduleId: schedule.scheduleId, deviceId: state.status.uuid, @@ -189,7 +206,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { }, child: Text( 'Delete', - style: context.textTheme.bodySmall!.copyWith(color: ColorsManager.blueColor), + style: context.textTheme.bodySmall! + .copyWith(color: ColorsManager.blueColor), ), ), ], @@ -201,8 +219,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { String _getSelectedDays(List selectedDays) { final days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - List selectedDaysStr = []; - for (int i = 0; i < selectedDays.length; i++) { + final selectedDaysStr = []; + for (var i = 0; i < selectedDays.length; i++) { if (selectedDays[i]) { selectedDaysStr.add(days[i]); } diff --git a/lib/pages/device_managment/garage_door/widgets/schedule_garage_managment_ui.dart b/lib/pages/device_managment/garage_door/widgets/schedule_garage_managment_ui.dart index e5819e89..786b3fa6 100644 --- a/lib/pages/device_managment/garage_door/widgets/schedule_garage_managment_ui.dart +++ b/lib/pages/device_managment/garage_door/widgets/schedule_garage_managment_ui.dart @@ -28,7 +28,7 @@ class ScheduleGarageManagementUI extends StatelessWidget { padding: 2, backgroundColor: ColorsManager.graysColor, borderRadius: 15, - onPressed: () => onAddSchedule(), + onPressed: onAddSchedule, child: Row( children: [ const Icon(Icons.add, color: ColorsManager.primaryColor), diff --git a/lib/pages/device_managment/garage_door/widgets/schedule_garage_mode_selector.dart b/lib/pages/device_managment/garage_door/widgets/schedule_garage_mode_selector.dart index 7b6e4690..3f8939dd 100644 --- a/lib/pages/device_managment/garage_door/widgets/schedule_garage_mode_selector.dart +++ b/lib/pages/device_managment/garage_door/widgets/schedule_garage_mode_selector.dart @@ -35,7 +35,8 @@ class ScheduleGarageDoorModeSelector extends StatelessWidget { ); } - Widget _buildRadioTile(BuildContext context, String label, ScheduleModes mode, GarageDoorLoadedState state) { + Widget _buildRadioTile(BuildContext context, String label, ScheduleModes mode, + GarageDoorLoadedState state) { return Flexible( child: ListTile( contentPadding: EdgeInsets.zero, diff --git a/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart b/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart index 491be37b..f2805d39 100644 --- a/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart +++ b/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart @@ -4,7 +4,8 @@ class SecondsPicker extends StatefulWidget { final int initialSeconds; final ValueChanged onSecondsChanged; - SecondsPicker({ + const SecondsPicker({ + super.key, required this.initialSeconds, required this.onSecondsChanged, }); diff --git a/lib/pages/device_managment/garage_door/widgets/time_out_alarm_dialog_body.dart b/lib/pages/device_managment/garage_door/widgets/time_out_alarm_dialog_body.dart index 541ab9e4..2eff275d 100644 --- a/lib/pages/device_managment/garage_door/widgets/time_out_alarm_dialog_body.dart +++ b/lib/pages/device_managment/garage_door/widgets/time_out_alarm_dialog_body.dart @@ -5,7 +5,7 @@ import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_ import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_state.dart'; class TimeOutAlarmDialogBody extends StatefulWidget { - TimeOutAlarmDialogBody(this.bloc); + const TimeOutAlarmDialogBody(this.bloc, {super.key}); final GarageDoorBloc bloc; @override diff --git a/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart b/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart index e14672ae..66c33fbe 100644 --- a/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart +++ b/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart @@ -16,10 +16,12 @@ class GateWayBloc extends Bloc { on(_onFactoryReset); } - FutureOr _getGatWayById(GatWayById event, Emitter emit) async { + FutureOr _getGatWayById( + GatWayById event, Emitter emit) async { emit(GatewayLoadingState()); try { - List devicesList = await DevicesManagementApi.getDevicesByGatewayId(event.getWayId); + final devicesList = + await DevicesManagementApi.getDevicesByGatewayId(event.getWayId); emit(UpdateGatewayState(list: devicesList)); } catch (e) { @@ -28,7 +30,8 @@ class GateWayBloc extends Bloc { } } - FutureOr _onFactoryReset(GateWayFactoryReset event, Emitter emit) async { + FutureOr _onFactoryReset( + GateWayFactoryReset event, Emitter emit) async { emit(GatewayLoadingState()); try { final response = await DevicesManagementApi().factoryReset( diff --git a/lib/pages/device_managment/gateway/view/gateway_batch_control.dart b/lib/pages/device_managment/gateway/view/gateway_batch_control.dart index f3a08a18..a9fe13ba 100644 --- a/lib/pages/device_managment/gateway/view/gateway_batch_control.dart +++ b/lib/pages/device_managment/gateway/view/gateway_batch_control.dart @@ -6,7 +6,8 @@ import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_ // import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class GatewayBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class GatewayBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const GatewayBatchControlView({super.key, required this.gatewayIds}); final List gatewayIds; @@ -38,7 +39,8 @@ class GatewayBatchControlView extends StatelessWidget with HelperResponsiveLayou context.read().add( GateWayFactoryReset( deviceId: gatewayIds.first, - factoryReset: FactoryResetModel(devicesUuid: gatewayIds), + factoryReset: + FactoryResetModel(devicesUuid: gatewayIds), ), ); }, diff --git a/lib/pages/device_managment/gateway/view/gateway_view.dart b/lib/pages/device_managment/gateway/view/gateway_view.dart index d674e4d8..8f5d0674 100644 --- a/lib/pages/device_managment/gateway/view/gateway_view.dart +++ b/lib/pages/device_managment/gateway/view/gateway_view.dart @@ -37,21 +37,21 @@ class GateWayControlsView extends StatelessWidget with HelperResponsiveLayout { mainAxisSize: MainAxisSize.min, children: [ Text( - "Bluetooth Devices:", + 'Bluetooth Devices:', style: context.textTheme.bodyMedium!.copyWith( color: ColorsManager.grayColor, ), ), const SizedBox(height: 12), Text( - "No devices found", + 'No devices found', style: context.textTheme.bodySmall!.copyWith( color: ColorsManager.blackColor, ), ), const SizedBox(height: 30), Text( - "ZigBee Devices:", + 'ZigBee Devices:', style: context.textTheme.bodyMedium!.copyWith( color: ColorsManager.grayColor, ), diff --git a/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart b/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart index 493e3037..1a2d0ab1 100644 --- a/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart +++ b/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart @@ -159,17 +159,15 @@ class MainDoorSensorBloc } } - _listenToChanges(deviceId) { + void _listenToChanges(deviceId) { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$deviceId'); - Stream stream = ref.onValue; + final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + final stream = ref.onValue; stream.listen((DatabaseEvent event) { - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); diff --git a/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart b/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart index 569cfa11..8dcc221a 100644 --- a/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart +++ b/lib/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart @@ -1,8 +1,7 @@ import 'package:equatable/equatable.dart'; +import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart'; import 'package:syncrow_web/pages/device_managment/main_door_sensor/models/main_door_status_model.dart'; -import '../../all_devices/models/factory_reset_model.dart'; - class MainDoorSensorEvent extends Equatable { @override List get props => []; @@ -75,7 +74,7 @@ class MainDoorSensorFactoryReset extends MainDoorSensorEvent { class StatusUpdated extends MainDoorSensorEvent { final MainDoorSensorStatusModel deviceStatus; - StatusUpdated(this.deviceStatus); + StatusUpdated(this.deviceStatus); @override List get props => [deviceStatus]; } diff --git a/lib/pages/device_managment/main_door_sensor/models/main_door_status_model.dart b/lib/pages/device_managment/main_door_sensor/models/main_door_status_model.dart index 52dda7a3..65518938 100644 --- a/lib/pages/device_managment/main_door_sensor/models/main_door_status_model.dart +++ b/lib/pages/device_managment/main_door_sensor/models/main_door_status_model.dart @@ -12,10 +12,10 @@ class MainDoorSensorStatusModel { }); factory MainDoorSensorStatusModel.fromJson(String id, List jsonList) { - late bool doorContactState = false; - late int batteryPercentage = 0; + late var doorContactState = false; + late var batteryPercentage = 0; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'doorcontact_state': doorContactState = status.value ?? false; diff --git a/lib/pages/device_managment/main_door_sensor/view/main_door_control_view.dart b/lib/pages/device_managment/main_door_sensor/view/main_door_control_view.dart index ecdb367a..723cb2f0 100644 --- a/lib/pages/device_managment/main_door_sensor/view/main_door_control_view.dart +++ b/lib/pages/device_managment/main_door_sensor/view/main_door_control_view.dart @@ -12,7 +12,8 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLayout { +class MainDoorSensorControlView extends StatelessWidget + with HelperResponsiveLayout { const MainDoorSensorControlView({super.key, required this.device}); final AllDevicesModel device; @@ -20,10 +21,12 @@ class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLay @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => MainDoorSensorBloc()..add(MainDoorSensorFetchDeviceEvent(device.uuid!)), + create: (context) => MainDoorSensorBloc() + ..add(MainDoorSensorFetchDeviceEvent(device.uuid!)), child: BlocBuilder( builder: (context, state) { - if (state is MainDoorSensorLoadingState || state is MainDoorSensorReportsLoadingState) { + if (state is MainDoorSensorLoadingState || + state is MainDoorSensorReportsLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is MainDoorSensorDeviceStatusLoaded) { return _buildStatusControls(context, state.status); @@ -32,12 +35,15 @@ class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLay report: state.deviceReport, onRowTap: (index) {}, onClose: () { - context.read().add(MainDoorSensorFetchDeviceEvent(device.uuid!)); + context + .read() + .add(MainDoorSensorFetchDeviceEvent(device.uuid!)); }, hideValueShowDescription: true, mainDoorSensor: true, ); - } else if (state is MainDoorSensorFailedState || state is MainDoorSensorBatchFailedState) { + } else if (state is MainDoorSensorFailedState || + state is MainDoorSensorBatchFailedState) { return const Center(child: Text('Error fetching status')); } else { return const Center(child: CircularProgressIndicator()); @@ -46,7 +52,8 @@ class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLay )); } - Widget _buildStatusControls(BuildContext context, MainDoorSensorStatusModel status) { + Widget _buildStatusControls( + BuildContext context, MainDoorSensorStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -71,7 +78,9 @@ class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLay icon: Assets.openCloseDoor, onTap: () {}, status: status.doorContactState, - textColor: status.doorContactState ? ColorsManager.red : ColorsManager.blackColor, + textColor: status.doorContactState + ? ColorsManager.red + : ColorsManager.blackColor, paddingAmount: 8, ), IconNameStatusContainer( @@ -79,7 +88,9 @@ class MainDoorSensorControlView extends StatelessWidget with HelperResponsiveLay name: 'Open/Close\nRecord', icon: Assets.openCloseRecords, onTap: () { - final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch; + final from = DateTime.now() + .subtract(const Duration(days: 30)) + .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; context.read().add( MainDoorSensorReportsEvent( diff --git a/lib/pages/device_managment/main_door_sensor/view/main_door_sensor_batch_view.dart b/lib/pages/device_managment/main_door_sensor/view/main_door_sensor_batch_view.dart index bbebabaa..e14321dd 100644 --- a/lib/pages/device_managment/main_door_sensor/view/main_door_sensor_batch_view.dart +++ b/lib/pages/device_managment/main_door_sensor/view/main_door_sensor_batch_view.dart @@ -27,7 +27,8 @@ class MainDoorSensorBatchView extends StatelessWidget { BlocProvider.of(innerContext).add( MainDoorSensorFactoryReset( deviceId: devicesIds.first, - factoryReset: FactoryResetModel(devicesUuid: devicesIds), + factoryReset: + FactoryResetModel(devicesUuid: devicesIds), ), ); }, diff --git a/lib/pages/device_managment/main_door_sensor/widgets/notification_dialog.dart b/lib/pages/device_managment/main_door_sensor/widgets/notification_dialog.dart index ac66b315..8e9cc8cd 100644 --- a/lib/pages/device_managment/main_door_sensor/widgets/notification_dialog.dart +++ b/lib/pages/device_managment/main_door_sensor/widgets/notification_dialog.dart @@ -53,7 +53,7 @@ class _NotificationDialogState extends State { ), ), child: IconButton( - padding: EdgeInsets.all(1), + padding: const EdgeInsets.all(1), icon: const Icon( Icons.close, color: Colors.grey, diff --git a/lib/pages/device_managment/one_g_glass_switch/bloc/one_gang_glass_switch_bloc.dart b/lib/pages/device_managment/one_g_glass_switch/bloc/one_gang_glass_switch_bloc.dart index c1e976ab..8de84264 100644 --- a/lib/pages/device_managment/one_g_glass_switch/bloc/one_gang_glass_switch_bloc.dart +++ b/lib/pages/device_managment/one_g_glass_switch/bloc/one_gang_glass_switch_bloc.dart @@ -39,9 +39,11 @@ class OneGangGlassSwitchBloc ) async { emit(OneGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); _listenToChanges(event.deviceId, emit); - deviceStatus = OneGangGlassStatusModel.fromJson(event.deviceId, status.status); + deviceStatus = + OneGangGlassStatusModel.fromJson(event.deviceId, status.status); emit(OneGangGlassSwitchStatusLoaded(deviceStatus)); } catch (e) { emit(OneGangGlassSwitchError(e.toString())); @@ -62,7 +64,7 @@ class OneGangGlassSwitchBloc final statusList = []; if (data['status'] != null) { - for (var element in data['status']) { + for (final element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -72,7 +74,8 @@ class OneGangGlassSwitchBloc } } if (statusList.isNotEmpty) { - final newStatus = OneGangGlassStatusModel.fromJson(deviceId, statusList); + final newStatus = + OneGangGlassStatusModel.fromJson(deviceId, statusList); if (newStatus != deviceStatus) { deviceStatus = newStatus; if (!isClosed) { @@ -140,9 +143,10 @@ class OneGangGlassSwitchBloc ) async { emit(OneGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.deviceIds); - deviceStatus = - OneGangGlassStatusModel.fromJson(event.deviceIds.first, status.status); + final status = + await DevicesManagementApi().getBatchStatus(event.deviceIds); + deviceStatus = OneGangGlassStatusModel.fromJson( + event.deviceIds.first, status.status); emit(OneGangGlassSwitchStatusLoaded(deviceStatus)); } catch (e) { emit(OneGangGlassSwitchError(e.toString())); diff --git a/lib/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart b/lib/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart index 39c96dd0..dd8a1140 100644 --- a/lib/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart +++ b/lib/pages/device_managment/one_g_glass_switch/models/once_gang_glass_status_model.dart @@ -15,7 +15,7 @@ class OneGangGlassStatusModel { late bool switch1; late int countDown; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; @@ -46,5 +46,6 @@ class OneGangGlassStatusModel { } @override - String toString() => 'OneGangGlassStatusModel(uuid: $uuid, switch1: $switch1, countDown: $countDown)'; + String toString() => + 'OneGangGlassStatusModel(uuid: $uuid, switch1: $switch1, countDown: $countDown)'; } diff --git a/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_batch_control_view.dart b/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_batch_control_view.dart index 307e61da..5f88768a 100644 --- a/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_batch_control_view.dart +++ b/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_batch_control_view.dart @@ -8,16 +8,19 @@ import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_ import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class OneGangGlassSwitchBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class OneGangGlassSwitchBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const OneGangGlassSwitchBatchControlView({required this.deviceIds, super.key}); + const OneGangGlassSwitchBatchControlView( + {required this.deviceIds, super.key}); @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => OneGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) - ..add(OneGangGlassSwitchFetchBatchStatusEvent(deviceIds)), + create: (context) => + OneGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) + ..add(OneGangGlassSwitchFetchBatchStatusEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is OneGangGlassSwitchLoading) { @@ -34,7 +37,8 @@ class OneGangGlassSwitchBatchControlView extends StatelessWidget with HelperResp ); } - Widget _buildStatusControls(BuildContext context, OneGangGlassStatusModel status) { + Widget _buildStatusControls( + BuildContext context, OneGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); diff --git a/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_switch_control_view.dart b/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_switch_control_view.dart index 997be513..2c376ad6 100644 --- a/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_switch_control_view.dart +++ b/lib/pages/device_managment/one_g_glass_switch/view/one_gang_glass_switch_control_view.dart @@ -7,7 +7,8 @@ import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class OneGangGlassSwitchControlView extends StatelessWidget with HelperResponsiveLayout { +class OneGangGlassSwitchControlView extends StatelessWidget + with HelperResponsiveLayout { final String deviceId; const OneGangGlassSwitchControlView({required this.deviceId, super.key}); @@ -16,7 +17,8 @@ class OneGangGlassSwitchControlView extends StatelessWidget with HelperResponsiv Widget build(BuildContext context) { return BlocProvider( create: (context) => - OneGangGlassSwitchBlocFactory.create(deviceId: deviceId)..add(OneGangGlassSwitchFetchDeviceEvent(deviceId)), + OneGangGlassSwitchBlocFactory.create(deviceId: deviceId) + ..add(OneGangGlassSwitchFetchDeviceEvent(deviceId)), child: BlocBuilder( builder: (context, state) { if (state is OneGangGlassSwitchLoading) { @@ -33,7 +35,8 @@ class OneGangGlassSwitchControlView extends StatelessWidget with HelperResponsiv ); } - Widget _buildStatusControls(BuildContext context, OneGangGlassStatusModel status) { + Widget _buildStatusControls( + BuildContext context, OneGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -56,7 +59,7 @@ class OneGangGlassSwitchControlView extends StatelessWidget with HelperResponsiv value: status.switch1, code: 'switch_1', deviceId: deviceId, - label: "Wall Light", + label: 'Wall Light', onChange: (value) { context.read().add( OneGangGlassSwitchControl( diff --git a/lib/pages/device_managment/one_gang_switch/bloc/wall_light_switch_bloc.dart b/lib/pages/device_managment/one_gang_switch/bloc/wall_light_switch_bloc.dart index 59eccfe9..cf22faba 100644 --- a/lib/pages/device_managment/one_gang_switch/bloc/wall_light_switch_bloc.dart +++ b/lib/pages/device_managment/one_gang_switch/bloc/wall_light_switch_bloc.dart @@ -10,7 +10,8 @@ import 'package:syncrow_web/services/batch_control_devices_service.dart'; import 'package:syncrow_web/services/control_device_service.dart'; import 'package:syncrow_web/services/devices_mang_api.dart'; -class WallLightSwitchBloc extends Bloc { +class WallLightSwitchBloc + extends Bloc { late WallLightStatusModel deviceStatus; final String deviceId; final ControlDeviceService controlDeviceService; @@ -35,9 +36,11 @@ class WallLightSwitchBloc extends Bloc[]; if (data['status'] != null) { - for (var element in data['status']) { + for (final element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -136,7 +139,8 @@ class WallLightSwitchBloc extends Bloc deviceIds; @@ -18,15 +19,17 @@ class WallLightBatchControlView extends StatelessWidget with HelperResponsiveLay @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => WallLightSwitchBlocFactory.create(deviceId: deviceIds.first) - ..add(WallLightSwitchFetchBatchEvent(deviceIds)), + create: (context) => + WallLightSwitchBlocFactory.create(deviceId: deviceIds.first) + ..add(WallLightSwitchFetchBatchEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is WallLightSwitchLoading) { return const Center(child: CircularProgressIndicator()); } else if (state is WallLightSwitchStatusLoaded) { return _buildStatusControls(context, state.status); - } else if (state is WallLightSwitchError || state is WallLightSwitchControlError) { + } else if (state is WallLightSwitchError || + state is WallLightSwitchControlError) { return const Center(child: Text('Error fetching status')); } else { return const Center(child: CircularProgressIndicator()); @@ -36,7 +39,8 @@ class WallLightBatchControlView extends StatelessWidget with HelperResponsiveLay ); } - Widget _buildStatusControls(BuildContext context, WallLightStatusModel status) { + Widget _buildStatusControls( + BuildContext context, WallLightStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -78,7 +82,8 @@ class WallLightBatchControlView extends StatelessWidget with HelperResponsiveLay FactoryResetWidget( callFactoryReset: () { context.read().add(WallLightFactoryReset( - deviceId: status.uuid, factoryReset: FactoryResetModel(devicesUuid: deviceIds))); + deviceId: status.uuid, + factoryReset: FactoryResetModel(devicesUuid: deviceIds))); }, ), ], diff --git a/lib/pages/device_managment/power_clamp/bloc/smart_power_bloc.dart b/lib/pages/device_managment/power_clamp/bloc/smart_power_bloc.dart index 24c5138f..4cc0dbf3 100644 --- a/lib/pages/device_managment/power_clamp/bloc/smart_power_bloc.dart +++ b/lib/pages/device_managment/power_clamp/bloc/smart_power_bloc.dart @@ -215,33 +215,46 @@ class SmartPowerBloc extends Bloc { SmartPowerFetchDeviceEvent event, Emitter emit) async { emit(SmartPowerLoading()); try { - var status = + final status = await DevicesManagementApi().getPowerClampInfo(event.deviceId); - deviceStatus = PowerClampModel.fromJson(status as Map? ??{}); + deviceStatus = + PowerClampModel.fromJson(status as Map? ?? {}); final phaseADataPoints = deviceStatus.status.phaseA.dataPoints; final phaseBDataPoints = deviceStatus.status.phaseB.dataPoints; final phaseCDataPoints = deviceStatus.status.phaseC.dataPoints; phaseData = [ { 'name': 'Phase A', - 'voltage': '${(phaseADataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V', - 'current': '${(phaseADataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A', - 'activePower': '${phaseADataPoints.elementAtOrNull(2)?.value??'N/A'} W', - 'powerFactor': '${phaseADataPoints.elementAtOrNull(3)?.value??'N/A'}', + 'voltage': + '${(phaseADataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V', + 'current': + '${(phaseADataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A', + 'activePower': + '${phaseADataPoints.elementAtOrNull(2)?.value ?? 'N/A'} W', + 'powerFactor': + '${phaseADataPoints.elementAtOrNull(3)?.value ?? 'N/A'}', }, { 'name': 'Phase B', - 'voltage': '${(phaseBDataPoints .elementAtOrNull(0)?.value as num? ?? 0) / 10} V', - 'current': '${(phaseBDataPoints .elementAtOrNull(1)?.value as num? ?? 0) / 10} A', - 'activePower': '${phaseBDataPoints.elementAtOrNull(2)?.value??'N/A'} W', - 'powerFactor': '${phaseBDataPoints.elementAtOrNull(3)?.value??'N/A'}', + 'voltage': + '${(phaseBDataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V', + 'current': + '${(phaseBDataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A', + 'activePower': + '${phaseBDataPoints.elementAtOrNull(2)?.value ?? 'N/A'} W', + 'powerFactor': + '${phaseBDataPoints.elementAtOrNull(3)?.value ?? 'N/A'}', }, { 'name': 'Phase C', - 'voltage': '${(phaseCDataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V', - 'current': '${(phaseCDataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A', - 'activePower': '${phaseCDataPoints.elementAtOrNull(2)?.value ?? 'N/A'} W', - 'powerFactor': '${phaseCDataPoints.elementAtOrNull(3)?.value ?? 'N/A'}', + 'voltage': + '${(phaseCDataPoints.elementAtOrNull(0)?.value as num? ?? 0) / 10} V', + 'current': + '${(phaseCDataPoints.elementAtOrNull(1)?.value as num? ?? 0) / 10} A', + 'activePower': + '${phaseCDataPoints.elementAtOrNull(2)?.value ?? 'N/A'} W', + 'powerFactor': + '${phaseCDataPoints.elementAtOrNull(3)?.value ?? 'N/A'}', }, ]; emit(GetDeviceStatus()); @@ -305,8 +318,7 @@ class SmartPowerBloc extends Bloc { try { final response = await DevicesManagementApi().getPowerStatus(event.devicesIds); - PowerClampBatchModel deviceStatus = - PowerClampBatchModel.fromJson(response); + final deviceStatus = PowerClampBatchModel.fromJson(response); emit(SmartPowerLoadBatchControll(deviceStatus)); } catch (e) { @@ -417,15 +429,15 @@ class SmartPowerBloc extends Bloc { } Future selectMonthAndYear(BuildContext context) async { - int selectedYear = DateTime.now().year; - int selectedMonth = DateTime.now().month; + var selectedYear = DateTime.now().year; + var selectedMonth = DateTime.now().month; - FixedExtentScrollController yearController = + final yearController = FixedExtentScrollController(initialItem: selectedYear - 1905); - FixedExtentScrollController monthController = + final monthController = FixedExtentScrollController(initialItem: selectedMonth - 1); - return await showDialog( + return showDialog( context: context, builder: (BuildContext context) { return Column( @@ -537,11 +549,11 @@ class SmartPowerBloc extends Bloc { } Future selectYear(BuildContext context) async { - int selectedYear = DateTime.now().year; - FixedExtentScrollController yearController = + var selectedYear = DateTime.now().year; + final yearController = FixedExtentScrollController(initialItem: selectedYear - 1905); - return await showDialog( + return showDialog( context: context, builder: (BuildContext context) { return Column( @@ -622,9 +634,9 @@ class SmartPowerBloc extends Bloc { Future dayMonthYearPicker({ required BuildContext context, }) async { - DateTime selectedDate = DateTime.now(); + var selectedDate = DateTime.now(); - return await showDialog( + return showDialog( context: context, builder: (BuildContext context) { return Column( @@ -686,7 +698,7 @@ class SmartPowerBloc extends Bloc { String formattedDate = DateFormat('yyyy/MM/dd').format(DateTime.now()); - void checkDayMonthYearSelected( + Future checkDayMonthYearSelected( SelectDateEvent event, Emitter emit) async { Future Function(BuildContext context)? dateSelector; String dateFormat; @@ -698,15 +710,11 @@ class SmartPowerBloc extends Bloc { dateFormat = 'yyyy/MM/dd'; break; case 1: - dateSelector = (context) { - return selectMonthAndYear(context); - }; + dateSelector = selectMonthAndYear; dateFormat = 'yyyy-MM'; break; case 2: - dateSelector = (context) { - return selectYear(context); - }; + dateSelector = selectYear; dateFormat = 'yyyy'; break; default: @@ -743,7 +751,7 @@ class SmartPowerBloc extends Bloc { .toList(); } else if (event.viewType == 'Month') { formattedDate = - "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}"; + '${event.selectedDate.year}-${getMonthShortName(event.selectedDate.month)}'; filteredRecords = record .where((record) => @@ -752,7 +760,7 @@ class SmartPowerBloc extends Bloc { .toList(); } else if (event.viewType == 'Day') { formattedDate = - "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}-${event.selectedDate.day}"; + '${event.selectedDate.year}-${getMonthShortName(event.selectedDate.month)}-${event.selectedDate.day}'; filteredRecords = record .where((record) => @@ -784,11 +792,11 @@ class SmartPowerBloc extends Bloc { String endChartDate = ''; - void selectDateRange() async { - DateTime startDate = dateTime!; - DateTime endDate = DateTime(startDate.year, startDate.month + 1, 1) + Future selectDateRange() async { + final startDate = dateTime!; + final endDate = DateTime(startDate.year, startDate.month + 1, 1) .subtract(const Duration(days: 1)); - String formattedEndDate = DateFormat('dd/MM/yyyy').format(endDate); + final formattedEndDate = DateFormat('dd/MM/yyyy').format(endDate); endChartDate = ' - $formattedEndDate'; } } diff --git a/lib/pages/device_managment/power_clamp/bloc/smart_power_event.dart b/lib/pages/device_managment/power_clamp/bloc/smart_power_event.dart index 1985c67c..c6cca576 100644 --- a/lib/pages/device_managment/power_clamp/bloc/smart_power_event.dart +++ b/lib/pages/device_managment/power_clamp/bloc/smart_power_event.dart @@ -95,16 +95,18 @@ class FilterRecordsByDateEvent extends SmartPowerEvent { class FetchPowerClampBatchStatusEvent extends SmartPowerEvent { final List deviceIds; - FetchPowerClampBatchStatusEvent(this.deviceIds); + FetchPowerClampBatchStatusEvent(this.deviceIds); @override List get props => [deviceIds]; -}class PowerBatchControlEvent extends SmartPowerEvent { +} + +class PowerBatchControlEvent extends SmartPowerEvent { final List deviceIds; final String code; final dynamic value; - PowerBatchControlEvent({ + PowerBatchControlEvent({ required this.deviceIds, required this.code, required this.value, @@ -112,4 +114,4 @@ class FetchPowerClampBatchStatusEvent extends SmartPowerEvent { @override List get props => [deviceIds, code, value]; -} \ No newline at end of file +} diff --git a/lib/pages/device_managment/power_clamp/models/device_event.dart b/lib/pages/device_managment/power_clamp/models/device_event.dart index 09f7b46e..8ef43961 100644 --- a/lib/pages/device_managment/power_clamp/models/device_event.dart +++ b/lib/pages/device_managment/power_clamp/models/device_event.dart @@ -1,4 +1,3 @@ - class EventDevice { final String? code; final DateTime? eventTime; @@ -12,7 +11,7 @@ class EventDevice { EventDevice.fromJson(Map json) : code = json['code'] as String?, - eventTime = json['eventTime'] , + eventTime = json['eventTime'], value = json['value'] as String?; Map toJson() => { diff --git a/lib/pages/device_managment/power_clamp/models/power_clamp_batch_model.dart b/lib/pages/device_managment/power_clamp/models/power_clamp_batch_model.dart index 1812d1c9..10ea3a11 100644 --- a/lib/pages/device_managment/power_clamp/models/power_clamp_batch_model.dart +++ b/lib/pages/device_managment/power_clamp/models/power_clamp_batch_model.dart @@ -19,10 +19,10 @@ class PowerClampBatchModel extends PowerClampModel1 { }); factory PowerClampBatchModel.fromJson(Map json) { - String productUuid = json['productUuid'] ?? ''; - String productType = json['productType'] ?? ''; + final String productUuid = json['productUuid'] ?? ''; + final String productType = json['productType'] ?? ''; - List statusList = []; + var statusList = []; if (json['status'] != null && json['status'] is List) { statusList = (json['status'] as List).map((e) => Status.fromJson(e)).toList(); diff --git a/lib/pages/device_managment/power_clamp/models/power_clamp_model.dart b/lib/pages/device_managment/power_clamp/models/power_clamp_model.dart index b6592f4d..424c940f 100644 --- a/lib/pages/device_managment/power_clamp/models/power_clamp_model.dart +++ b/lib/pages/device_managment/power_clamp/models/power_clamp_model.dart @@ -16,7 +16,8 @@ class PowerClampModel { return PowerClampModel( productUuid: json['productUuid'] as String? ?? '', productType: json['productType'] as String? ?? '', - status: PowerStatus.fromJson(json['status'] as Map? ?? {}), + status: + PowerStatus.fromJson(json['status'] as Map? ?? {}), ); } diff --git a/lib/pages/device_managment/power_clamp/view/phase_widget.dart b/lib/pages/device_managment/power_clamp/view/phase_widget.dart index 223acd95..ab70237e 100644 --- a/lib/pages/device_managment/power_clamp/view/phase_widget.dart +++ b/lib/pages/device_managment/power_clamp/view/phase_widget.dart @@ -5,7 +5,8 @@ import 'package:syncrow_web/utils/constants/assets.dart'; class PhaseWidget extends StatefulWidget { final List> phaseData; - PhaseWidget({ + const PhaseWidget({ + super.key, required this.phaseData, }); @override @@ -19,7 +20,7 @@ class _PhaseWidgetState extends State { Widget build(BuildContext context) { return Column( children: [ - SizedBox(height: 10), + const SizedBox(height: 10), Row( children: List.generate(widget.phaseData.length, (index) { return InkWell( @@ -43,27 +44,28 @@ class _PhaseWidgetState extends State { ); }), ), - SizedBox(height: 10), - _selectedPhaseIndex == 0 - ? phase( - totalActive: widget.phaseData[0]['activePower'] ?? '0', - totalCurrent: widget.phaseData[0]['current'] ?? '0', - totalFactor: widget.phaseData[0]['powerFactor'] ?? '0', - totalVoltage: widget.phaseData[0]['voltage'] ?? '0', - ) - : _selectedPhaseIndex == 1 - ? phase( - totalActive: widget.phaseData[1]['activePower'] ?? '0', - totalCurrent: widget.phaseData[1]['current'] ?? '0', - totalFactor: widget.phaseData[1]['powerFactor'] ?? '0', - totalVoltage: widget.phaseData[1]['voltage'] ?? '0', - ) - : phase( - totalActive: widget.phaseData[2]['activePower'] ?? '0', - totalCurrent: widget.phaseData[2]['current'] ?? '0', - totalFactor: widget.phaseData[2]['powerFactor'] ?? '0', - totalVoltage: widget.phaseData[2]['voltage'] ?? '0', - ), + const SizedBox(height: 10), + if (_selectedPhaseIndex == 0) + phase( + totalActive: widget.phaseData[0]['activePower'] ?? '0', + totalCurrent: widget.phaseData[0]['current'] ?? '0', + totalFactor: widget.phaseData[0]['powerFactor'] ?? '0', + totalVoltage: widget.phaseData[0]['voltage'] ?? '0', + ) + else + _selectedPhaseIndex == 1 + ? phase( + totalActive: widget.phaseData[1]['activePower'] ?? '0', + totalCurrent: widget.phaseData[1]['current'] ?? '0', + totalFactor: widget.phaseData[1]['powerFactor'] ?? '0', + totalVoltage: widget.phaseData[1]['voltage'] ?? '0', + ) + : phase( + totalActive: widget.phaseData[2]['activePower'] ?? '0', + totalCurrent: widget.phaseData[2]['current'] ?? '0', + totalFactor: widget.phaseData[2]['powerFactor'] ?? '0', + totalVoltage: widget.phaseData[2]['voltage'] ?? '0', + ), ], ); } diff --git a/lib/pages/device_managment/power_clamp/view/power_chart.dart b/lib/pages/device_managment/power_clamp/view/power_chart.dart index 7d6371f4..bbdcd87d 100644 --- a/lib/pages/device_managment/power_clamp/view/power_chart.dart +++ b/lib/pages/device_managment/power_clamp/view/power_chart.dart @@ -35,7 +35,7 @@ class _EnergyConsumptionPageState extends State { @override Widget build(BuildContext context) { - return Container( + return ColoredBox( color: ColorsManager.whiteColors, child: Column( children: [ @@ -146,7 +146,7 @@ class _EnergyConsumptionPageState extends State { showTitles: false, reservedSize: 70, getTitlesWidget: (value, meta) { - int index = value.toInt(); + final index = value.toInt(); if (index >= 0 && index < _chartData.length) { return Padding( padding: const EdgeInsets.all(8.0), @@ -169,14 +169,14 @@ class _EnergyConsumptionPageState extends State { verticalInterval: 1, getDrawingVerticalLine: (value) { return FlLine( - color: Colors.grey.withOpacity(0.2), + color: Colors.grey.withValues(alpha: 0.2), dashArray: [8, 8], strokeWidth: 1, ); }, getDrawingHorizontalLine: (value) { return FlLine( - color: Colors.grey.withOpacity(0.2), + color: Colors.grey.withValues(alpha: 0.2), dashArray: [5, 5], strokeWidth: 1, ); @@ -192,19 +192,21 @@ class _EnergyConsumptionPageState extends State { spots: _chartData .asMap() .entries - .map((entry) => FlSpot( - entry.key.toDouble(), entry.value.consumption)) + .map((entry) => FlSpot(entry.key.toDouble(), + entry.value.consumption)) .toList(), isCurved: true, - color: ColorsManager.primaryColor.withOpacity(0.6), + color: + ColorsManager.primaryColor.withValues(alpha: 0.6), show: true, shadow: const Shadow(color: Colors.black12), belowBarData: BarAreaData( show: true, gradient: LinearGradient( colors: [ - ColorsManager.primaryColor.withOpacity(0.5), - Colors.blue.withOpacity(0.1), + ColorsManager.primaryColor + .withValues(alpha: 0.5), + Colors.blue.withValues(alpha: 0.1), ], begin: Alignment.center, end: Alignment.bottomCenter, @@ -220,7 +222,7 @@ class _EnergyConsumptionPageState extends State { borderData: FlBorderData( show: false, border: Border.all( - color: const Color(0xff023DFE).withOpacity(0.7), + color: const Color(0xff023DFE).withValues(alpha: 0.7), width: 10, ), ), diff --git a/lib/pages/device_managment/power_clamp/view/power_clamp_batch_control_view.dart b/lib/pages/device_managment/power_clamp/view/power_clamp_batch_control_view.dart index 7f6a4b64..2032cd90 100644 --- a/lib/pages/device_managment/power_clamp/view/power_clamp_batch_control_view.dart +++ b/lib/pages/device_managment/power_clamp/view/power_clamp_batch_control_view.dart @@ -9,16 +9,17 @@ import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_ // import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class PowerClampBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class PowerClampBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const PowerClampBatchControlView({Key? key, required this.deviceIds}) : super(key: key); + const PowerClampBatchControlView({super.key, required this.deviceIds}); @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => - SmartPowerBloc(deviceId: deviceIds.first)..add(SmartPowerFetchBatchEvent(deviceIds)), + create: (context) => SmartPowerBloc(deviceId: deviceIds.first) + ..add(SmartPowerFetchBatchEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is SmartPowerLoading) { @@ -35,7 +36,8 @@ class PowerClampBatchControlView extends StatelessWidget with HelperResponsiveLa ); } - Widget _buildStatusControls(BuildContext context, PowerClampBatchModel status) { + Widget _buildStatusControls( + BuildContext context, PowerClampBatchModel status) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ diff --git a/lib/pages/device_managment/power_clamp/view/power_info_card.dart b/lib/pages/device_managment/power_clamp/view/power_info_card.dart index 601b6346..b06bd1c3 100644 --- a/lib/pages/device_managment/power_clamp/view/power_info_card.dart +++ b/lib/pages/device_managment/power_clamp/view/power_info_card.dart @@ -9,12 +9,12 @@ class PowerClampInfoCard extends StatelessWidget { final String unit; const PowerClampInfoCard({ - Key? key, + super.key, required this.iconPath, required this.title, required this.value, required this.unit, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/pages/device_managment/power_clamp/view/smart_power_device_control.dart b/lib/pages/device_managment/power_clamp/view/smart_power_device_control.dart index 67313802..3f67a027 100644 --- a/lib/pages/device_managment/power_clamp/view/smart_power_device_control.dart +++ b/lib/pages/device_managment/power_clamp/view/smart_power_device_control.dart @@ -12,7 +12,8 @@ import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; //Smart Power Clamp -class SmartPowerDeviceControl extends StatelessWidget with HelperResponsiveLayout { +class SmartPowerDeviceControl extends StatelessWidget + with HelperResponsiveLayout { final String deviceId; const SmartPowerDeviceControl({super.key, required this.deviceId}); @@ -59,7 +60,7 @@ class SmartPowerDeviceControl extends StatelessWidget with HelperResponsiveLayou required SmartPowerBloc blocProvider, required int currentPage, }) { - PageController pageController = PageController(initialPage: currentPage); + final pageController = PageController(initialPage: currentPage); return Container( padding: const EdgeInsets.symmetric(horizontal: 50), child: DeviceControlsContainer( @@ -195,8 +196,8 @@ class SmartPowerDeviceControl extends StatelessWidget with HelperResponsiveLayou blocProvider.add(SelectDateEvent(context: context)); blocProvider.add(FilterRecordsByDateEvent( selectedDate: blocProvider.dateTime!, - viewType: - blocProvider.views[blocProvider.currentIndex])); + viewType: blocProvider + .views[blocProvider.currentIndex])); }, widget: blocProvider.dateSwitcher(), chartData: blocProvider.energyDataList.isNotEmpty diff --git a/lib/pages/device_managment/shared/device_batch_control_dialog.dart b/lib/pages/device_managment/shared/device_batch_control_dialog.dart index f2dc68f5..c99b0028 100644 --- a/lib/pages/device_managment/shared/device_batch_control_dialog.dart +++ b/lib/pages/device_managment/shared/device_batch_control_dialog.dart @@ -4,7 +4,8 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_mo import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; -class DeviceBatchControlDialog extends StatelessWidget with RouteControlsBasedCode { +class DeviceBatchControlDialog extends StatelessWidget + with RouteControlsBasedCode { final List devices; const DeviceBatchControlDialog({super.key, required this.devices}); @@ -43,7 +44,7 @@ class DeviceBatchControlDialog extends StatelessWidget with RouteControlsBasedCo height: 8, ), Text( - "Batch Control", + 'Batch Control', style: context.textTheme.bodySmall!.copyWith( color: ColorsManager.dialogBlueTitle, ), @@ -104,39 +105,39 @@ String getBatchDialogName(AllDevicesModel device) { */ switch (device.productType) { case '1G': - return "Smart Light Switch"; + return 'Smart Light Switch'; case '2G': - return "Smart Light Switch"; + return 'Smart Light Switch'; case '3G': - return "Smart Light Switch"; + return 'Smart Light Switch'; case 'GW': - return "Gateway"; + return 'Gateway'; case 'DL': - return "Door Lock"; + return 'Door Lock'; case 'WPS': - return "White Presence Sensor"; + return 'White Presence Sensor'; case 'CPS': - return "Black Presence Sensor"; + return 'Black Presence Sensor'; case 'CUR': - return "Smart Curtains"; + return 'Smart Curtains'; case 'WH': - return "Smart Water Heater"; + return 'Smart Water Heater'; case 'AC': - return "Smart AC"; + return 'Smart AC'; case 'DS': - return "Door / Window Sensor"; + return 'Door / Window Sensor'; case '1GT': - return "Touch Switch"; + return 'Touch Switch'; case '2GT': - return "Touch Switch"; + return 'Touch Switch'; case '3GT': - return "Touch Switch"; + return 'Touch Switch'; case 'GD': - return "Garage Door Opener"; + return 'Garage Door Opener'; case 'WL': - return "Water Leak Sensor"; + return 'Water Leak Sensor'; case 'SOS': - return "SOS"; + return 'SOS'; default: return device.categoryName ?? 'Device Control'; } diff --git a/lib/pages/device_managment/shared/device_control_dialog.dart b/lib/pages/device_managment/shared/device_control_dialog.dart index beb3b52c..0c9c4398 100644 --- a/lib/pages/device_managment/shared/device_control_dialog.dart +++ b/lib/pages/device_managment/shared/device_control_dialog.dart @@ -50,7 +50,7 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode { ), ), child: IconButton( - padding: EdgeInsets.all(1), + padding: const EdgeInsets.all(1), icon: const Icon( Icons.close, color: Colors.grey, @@ -107,7 +107,7 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode { 'Installation Date and Time:', formatDateTime( DateTime.fromMillisecondsSinceEpoch( - ((device.createTime ?? 0) * 1000), + (device.createTime ?? 0) * 1000, ), ), ), @@ -115,7 +115,7 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode { 'Battery Level:', device.batteryLevel != null ? '${device.batteryLevel ?? 0}%' - : "-", + : '-', statusColor: device.batteryLevel != null ? (device.batteryLevel! < 20 ? ColorsManager.red @@ -131,7 +131,7 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode { 'Last Offline Date and Time:', formatDateTime( DateTime.fromMillisecondsSinceEpoch( - ((device.updateTime ?? 0) * 1000), + (device.updateTime ?? 0) * 1000, ), ), ), diff --git a/lib/pages/device_managment/shared/device_controls_container.dart b/lib/pages/device_managment/shared/device_controls_container.dart index 888563da..5ee8a978 100644 --- a/lib/pages/device_managment/shared/device_controls_container.dart +++ b/lib/pages/device_managment/shared/device_controls_container.dart @@ -18,8 +18,9 @@ class DeviceControlsContainer extends StatelessWidget { color: Colors.grey.shade100, borderRadius: BorderRadius.circular(20), ), - padding: - EdgeInsets.symmetric(vertical: padding ?? 10, horizontal: padding ?? 16), //EdgeInsets.all(padding ?? 12), + padding: EdgeInsets.symmetric( + vertical: padding ?? 10, + horizontal: padding ?? 16), //EdgeInsets.all(padding ?? 12), child: child, ), ); diff --git a/lib/pages/device_managment/shared/sensors_widgets/presence_display_data.dart b/lib/pages/device_managment/shared/sensors_widgets/presence_display_data.dart index aac34b77..ba84bd87 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presence_display_data.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presence_display_data.dart @@ -4,7 +4,10 @@ import 'package:syncrow_web/utils/color_manager.dart'; class PresenceDisplayValue extends StatelessWidget { const PresenceDisplayValue( - {super.key, required this.value, required this.postfix, required this.description}); + {super.key, + required this.value, + required this.postfix, + required this.description}); final String value; final String postfix; @@ -32,7 +35,9 @@ class PresenceDisplayValue extends StatelessWidget { child: Text( postfix, style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.blackColor, fontSize: 16, fontWeight: FontWeight.w700), + color: ColorsManager.blackColor, + fontSize: 16, + fontWeight: FontWeight.w700), ), ), ], @@ -40,7 +45,9 @@ class PresenceDisplayValue extends StatelessWidget { Text( description, style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 16), + color: ColorsManager.blackColor, + fontWeight: FontWeight.w400, + fontSize: 16), ), ], ), diff --git a/lib/pages/device_managment/shared/sensors_widgets/presence_space_type.dart b/lib/pages/device_managment/shared/sensors_widgets/presence_space_type.dart index e1ca0586..c33ac15c 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presence_space_type.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presence_space_type.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import 'package:syncrow_web/utils/constants/assets.dart'; -import 'package:syncrow_web/utils/extension/build_context_x.dart'; +import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart'; import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart'; +import 'package:syncrow_web/utils/constants/assets.dart'; +import 'package:syncrow_web/utils/extension/build_context_x.dart'; class PresenceSpaceType extends StatelessWidget { const PresenceSpaceType({ @@ -20,7 +20,7 @@ class PresenceSpaceType extends StatelessWidget { @override Widget build(BuildContext context) { - final Map spaceTypeIcons = { + final spaceTypeIcons = { SpaceTypes.none: Assets.office, SpaceTypes.parlour: Assets.parlour, SpaceTypes.area: Assets.dyi, diff --git a/lib/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart b/lib/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart index d2d48b78..b46bbcc5 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart @@ -4,7 +4,8 @@ import 'package:syncrow_web/pages/device_managment/shared/device_controls_contai import 'package:syncrow_web/utils/color_manager.dart'; class PresenceStaticWidget extends StatelessWidget { - const PresenceStaticWidget({required this.icon, required this.description, super.key}); + const PresenceStaticWidget( + {required this.icon, required this.description, super.key}); final String icon; final String description; @@ -23,7 +24,9 @@ class PresenceStaticWidget extends StatelessWidget { Text( description, style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 16), + color: ColorsManager.blackColor, + fontWeight: FontWeight.w400, + fontSize: 16), ), ], ), diff --git a/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart b/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart index 26e47c8b..4ec7737a 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart @@ -25,7 +25,9 @@ class PresenceState extends StatelessWidget { Text( 'Status:', style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 10), + color: ColorsManager.blackColor, + fontWeight: FontWeight.w400, + fontSize: 10), ), ], ), @@ -41,7 +43,9 @@ class PresenceState extends StatelessWidget { Text( value, style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 16), + color: ColorsManager.blackColor, + fontWeight: FontWeight.w400, + fontSize: 16), ), ], ), diff --git a/lib/pages/device_managment/shared/sensors_widgets/presense_nobody_time.dart b/lib/pages/device_managment/shared/sensors_widgets/presense_nobody_time.dart index 9cc23505..cda019ea 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presense_nobody_time.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presense_nobody_time.dart @@ -48,7 +48,7 @@ class _PresenceUpdateDataState extends State { String _extractNumericValue(String value) { if (value == 'none') return '0'; - return value.replaceAll(RegExp(r'[a-zA-Z]'), '').trim(); + return value.replaceAll(RegExp('[a-zA-Z]'), '').trim(); } String _extractUnit(String value) { @@ -69,17 +69,17 @@ class _PresenceUpdateDataState extends State { } void _incrementValue() { - int currentIndex = nobodyTimeRange.indexOf(_currentValue); + final currentIndex = nobodyTimeRange.indexOf(_currentValue); if (currentIndex < nobodyTimeRange.length - 1) { - String newValue = nobodyTimeRange[currentIndex + 1]; + final newValue = nobodyTimeRange[currentIndex + 1]; _onValueChanged(newValue); } } void _decrementValue() { - int currentIndex = nobodyTimeRange.indexOf(_currentValue); + final currentIndex = nobodyTimeRange.indexOf(_currentValue); if (currentIndex > 0) { - String newValue = nobodyTimeRange[currentIndex - 1]; + final newValue = nobodyTimeRange[currentIndex - 1]; _onValueChanged(newValue); } } diff --git a/lib/pages/device_managment/shared/table/report_table.dart b/lib/pages/device_managment/shared/table/report_table.dart index 11385080..72a98f56 100644 --- a/lib/pages/device_managment/shared/table/report_table.dart +++ b/lib/pages/device_managment/shared/table/report_table.dart @@ -41,7 +41,8 @@ class ReportsTable extends StatelessWidget { height: 100, child: Text( 'No reports found', - style: context.textTheme.bodyLarge!.copyWith(color: ColorsManager.grayColor), + style: context.textTheme.bodyLarge! + .copyWith(color: ColorsManager.grayColor), ), ) : Stack( @@ -49,7 +50,8 @@ class ReportsTable extends StatelessWidget { Padding( padding: const EdgeInsets.all(20.0), child: Table( - border: TableBorder.all(color: Colors.grey.shade300, width: 1), + border: + TableBorder.all(color: Colors.grey.shade300, width: 1), columnWidths: const { 0: FlexColumnWidth(), 1: FlexColumnWidth(), @@ -66,28 +68,36 @@ class ReportsTable extends StatelessWidget { ), if (report.data != null) ...report.data!.asMap().entries.map((entry) { - int index = entry.key; - DeviceEvent data = entry.value; + final index = entry.key; + final data = entry.value; // Parse eventTime into Date and Time - DateTime eventDateTime = - DateTime.fromMillisecondsSinceEpoch(data.eventTime!); - String date = DateFormat('dd/MM/yyyy').format(eventDateTime); - String time = DateFormat('HH:mm').format(eventDateTime); + final eventDateTime = + DateTime.fromMillisecondsSinceEpoch( + data.eventTime!); + final date = + DateFormat('dd/MM/yyyy').format(eventDateTime); + final time = DateFormat('HH:mm').format(eventDateTime); String value; if (hideValueShowDescription == true) { - if (mainDoorSensor != null && mainDoorSensor == true) { + if (mainDoorSensor != null && + mainDoorSensor == true) { value = data.value == 'true' ? 'Open' : 'Close'; - } else if (garageDoorSensor != null && garageDoorSensor == true) { + } else if (garageDoorSensor != null && + garageDoorSensor == true) { value = data.value == 'true' ? 'Opened' : 'Closed'; } else if (waterLeak != null && waterLeak == true) { - value = data.value == 'normal' ? 'Normal' : 'Leak Detected'; + value = data.value == 'normal' + ? 'Normal' + : 'Leak Detected'; } else { - value = '${data.value!} ${thirdColumnDescription ?? ''}'; + value = + '${data.value!} ${thirdColumnDescription ?? ''}'; } } else { - value = '${data.value!} ${thirdColumnDescription ?? ''}'; + value = + '${data.value!} ${thirdColumnDescription ?? ''}'; } return TableRow( diff --git a/lib/pages/device_managment/shared/toggle_widget.dart b/lib/pages/device_managment/shared/toggle_widget.dart index 4888572f..0e8cff37 100644 --- a/lib/pages/device_managment/shared/toggle_widget.dart +++ b/lib/pages/device_managment/shared/toggle_widget.dart @@ -42,29 +42,30 @@ class ToggleWidget extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - icon == '-1' - ? const SizedBox( - height: 60, - width: 60, - ) - : ClipOval( - child: Container( - height: 60, - width: 60, - padding: const EdgeInsets.all(8), - color: ColorsManager.whiteColors, - child: SvgPicture.asset( - icon ?? Assets.lightPulp, - width: 35, - height: 35, - fit: BoxFit.contain, - ), - )), + if (icon == '-1') + const SizedBox( + height: 60, + width: 60, + ) + else + ClipOval( + child: Container( + height: 60, + width: 60, + padding: const EdgeInsets.all(8), + color: ColorsManager.whiteColors, + child: SvgPicture.asset( + icon ?? Assets.lightPulp, + width: 35, + height: 35, + fit: BoxFit.contain, + ), + )), if (showToggle) Container( child: CupertinoSwitch( value: value, - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, onChanged: onChange, ), ), diff --git a/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart b/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart index 14fdf61c..9334a039 100644 --- a/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart +++ b/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart @@ -22,7 +22,8 @@ class SosDeviceBloc extends Bloc { late SosStatusModel deviceStatus; - FutureOr _getDeviceStatus(GetDeviceStatus event, Emitter emit) async { + FutureOr _getDeviceStatus( + GetDeviceStatus event, Emitter emit) async { emit(SosDeviceLoadingState()); try { final status = await DevicesManagementApi().getDeviceStatus(event.uuid); @@ -33,7 +34,8 @@ class SosDeviceBloc extends Bloc { } } - FutureOr _getBatchStatus(GetBatchStatus event, Emitter emit) async { + FutureOr _getBatchStatus( + GetBatchStatus event, Emitter emit) async { emit(SosDeviceLoadingState()); try { final status = await DevicesManagementApi().getBatchStatus(event.uuids); @@ -44,25 +46,31 @@ class SosDeviceBloc extends Bloc { } } - FutureOr _getDeviceRecords(GetDeviceRecords event, Emitter emit) async { + FutureOr _getDeviceRecords( + GetDeviceRecords event, Emitter emit) async { emit(SosReportLoadingState()); try { - final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch; + final from = DateTime.now() + .subtract(const Duration(days: 30)) + .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final DeviceReport records = - await DevicesManagementApi.getDeviceReportsByDate(event.uuid, 'sos', from.toString(), to.toString()); + final records = await DevicesManagementApi.getDeviceReportsByDate( + event.uuid, 'sos', from.toString(), to.toString()); emit(SosReportLoadedState(records)); } catch (e) { emit(SosReportErrorState(e.toString())); } } - FutureOr _getDeviceAutomationRecords(GetDeviceAutomationRecords event, Emitter emit) async { + FutureOr _getDeviceAutomationRecords( + GetDeviceAutomationRecords event, Emitter emit) async { emit(SosAutomationReportLoadingState()); try { - final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch; + final from = DateTime.now() + .subtract(const Duration(days: 30)) + .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final DeviceReport records = await DevicesManagementApi.getDeviceReportsByDate( + final records = await DevicesManagementApi.getDeviceReportsByDate( event.uuid, 'sos_automation', from.toString(), to.toString()); emit(SosAutomationReportLoadedState(records)); } catch (e) { @@ -70,14 +78,17 @@ class SosDeviceBloc extends Bloc { } } - FutureOr _backToSosStatusView(BackToSosStatusView event, Emitter emit) { + FutureOr _backToSosStatusView( + BackToSosStatusView event, Emitter emit) { emit(SosDeviceLoadedState(deviceStatus)); } - FutureOr _sosFactoryReset(SosFactoryReset event, Emitter emit) async { + FutureOr _sosFactoryReset( + SosFactoryReset event, Emitter emit) async { emit(SosDeviceLoadingState()); try { - final response = await DevicesManagementApi().factoryReset(event.factoryReset, event.deviceId); + final response = await DevicesManagementApi() + .factoryReset(event.factoryReset, event.deviceId); if (response) { emit(SosDeviceLoadedState(deviceStatus)); } else { diff --git a/lib/pages/device_managment/sos/models/sos_status_model.dart b/lib/pages/device_managment/sos/models/sos_status_model.dart index ac0de3b0..4a9f2114 100644 --- a/lib/pages/device_managment/sos/models/sos_status_model.dart +++ b/lib/pages/device_managment/sos/models/sos_status_model.dart @@ -15,7 +15,7 @@ class SosStatusModel { late int batteryLevel; late String sosStatus; - for (var status in statuses) { + for (final status in statuses) { switch (status.code) { case 'battery_percentage': batteryLevel = status.value; diff --git a/lib/pages/device_managment/sos/view/sos_device_control_view.dart b/lib/pages/device_managment/sos/view/sos_device_control_view.dart index dde4512b..631a7424 100644 --- a/lib/pages/device_managment/sos/view/sos_device_control_view.dart +++ b/lib/pages/device_managment/sos/view/sos_device_control_view.dart @@ -6,13 +6,12 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_mo import 'package:syncrow_web/pages/device_managment/shared/icon_name_status_container.dart'; import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart'; import 'package:syncrow_web/pages/device_managment/sos/bloc/sos_device_bloc.dart'; +import 'package:syncrow_web/pages/device_managment/sos/models/sos_status_model.dart'; import 'package:syncrow_web/pages/device_managment/sos/widgets/sos_notification_dialog.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -import '../models/sos_status_model.dart'; - class SosDeviceControlsView extends StatelessWidget with HelperResponsiveLayout { const SosDeviceControlsView({ @@ -56,9 +55,9 @@ class SosDeviceControlsView extends StatelessWidget } else if (state is SosDeviceErrorState) { return const Center(child: Text('Error fetching status')); } else if (state is SosAutomationReportErrorState) { - return Center(child: Text('Error: ${state.message.toString()}')); + return Center(child: Text('Error: ${state.message}')); } else if (state is SosReportErrorState) { - return Center(child: Text('Error: ${state.message.toString()}')); + return Center(child: Text('Error: ${state.message}')); } return const Center(child: CircularProgressIndicator()); }, diff --git a/lib/pages/device_managment/sos/widgets/sos_notification_dialog.dart b/lib/pages/device_managment/sos/widgets/sos_notification_dialog.dart index 55428107..bbdeaa3d 100644 --- a/lib/pages/device_managment/sos/widgets/sos_notification_dialog.dart +++ b/lib/pages/device_managment/sos/widgets/sos_notification_dialog.dart @@ -52,7 +52,7 @@ class _NotificationDialogState extends State { ), ), child: IconButton( - padding: EdgeInsets.all(1), + padding: const EdgeInsets.all(1), icon: const Icon( Icons.close, color: Colors.grey, diff --git a/lib/pages/device_managment/three_g_glass_switch/bloc/three_gang_glass_switch_bloc.dart b/lib/pages/device_managment/three_g_glass_switch/bloc/three_gang_glass_switch_bloc.dart index 766c3163..7ab5567d 100644 --- a/lib/pages/device_managment/three_g_glass_switch/bloc/three_gang_glass_switch_bloc.dart +++ b/lib/pages/device_managment/three_g_glass_switch/bloc/three_gang_glass_switch_bloc.dart @@ -40,7 +40,8 @@ class ThreeGangGlassSwitchBloc ) async { emit(ThreeGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); _listenToChanges(event.deviceId, emit); deviceStatus = ThreeGangGlassStatusModel.fromJson(event.deviceId, status.status); @@ -64,7 +65,7 @@ class ThreeGangGlassSwitchBloc final statusList = []; if (data['status'] != null) { - for (var element in data['status']) { + for (final element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -74,7 +75,8 @@ class ThreeGangGlassSwitchBloc } } if (statusList.isNotEmpty) { - final newStatus = ThreeGangGlassStatusModel.fromJson(deviceId, statusList); + final newStatus = + ThreeGangGlassStatusModel.fromJson(deviceId, statusList); if (newStatus != deviceStatus) { deviceStatus = newStatus; if (!isClosed) { @@ -142,9 +144,10 @@ class ThreeGangGlassSwitchBloc ) async { emit(ThreeGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.deviceIds); - deviceStatus = - ThreeGangGlassStatusModel.fromJson(event.deviceIds.first, status.status); + final status = + await DevicesManagementApi().getBatchStatus(event.deviceIds); + deviceStatus = ThreeGangGlassStatusModel.fromJson( + event.deviceIds.first, status.status); emit(ThreeGangGlassSwitchBatchStatusLoaded(deviceStatus)); } catch (e) { emit(ThreeGangGlassSwitchError(e.toString())); diff --git a/lib/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart b/lib/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart index cec12b7f..e439a434 100644 --- a/lib/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart +++ b/lib/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart @@ -27,7 +27,7 @@ class ThreeGangGlassStatusModel { late bool switch3; late int countDown3; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; diff --git a/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_batch_control_view.dart b/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_batch_control_view.dart index 93fbe53e..22b5ff53 100644 --- a/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_batch_control_view.dart +++ b/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_batch_control_view.dart @@ -9,16 +9,19 @@ import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/factorie import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class ThreeGangGlassSwitchBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class ThreeGangGlassSwitchBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const ThreeGangGlassSwitchBatchControlView({required this.deviceIds, super.key}); + const ThreeGangGlassSwitchBatchControlView( + {required this.deviceIds, super.key}); @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => ThreeGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) - ..add(ThreeGangGlassSwitchFetchBatchStatusEvent(deviceIds)), + create: (context) => + ThreeGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) + ..add(ThreeGangGlassSwitchFetchBatchStatusEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is ThreeGangGlassSwitchLoading) { @@ -35,7 +38,8 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget with HelperRe ); } - Widget _buildStatusControls(BuildContext context, ThreeGangGlassStatusModel status) { + Widget _buildStatusControls( + BuildContext context, ThreeGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -58,7 +62,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget with HelperRe value: status.switch1, code: 'switch_1', deviceId: deviceIds.first, - label: "Wall Light", + label: 'Wall Light', onChange: (value) { context.read().add( ThreeGangGlassSwitchBatchControl( @@ -73,7 +77,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget with HelperRe value: status.switch2, code: 'switch_2', deviceId: deviceIds.first, - label: "Ceiling Light", + label: 'Ceiling Light', onChange: (value) { context.read().add( ThreeGangGlassSwitchBatchControl( @@ -88,7 +92,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget with HelperRe value: status.switch3, code: 'switch_3', deviceId: deviceIds.first, - label: "SpotLight", + label: 'SpotLight', onChange: (value) { context.read().add( ThreeGangGlassSwitchBatchControl( diff --git a/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_control_view.dart b/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_control_view.dart index 21a81df0..019f17f2 100644 --- a/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_control_view.dart +++ b/lib/pages/device_managment/three_g_glass_switch/view/three_gang_glass_switch_control_view.dart @@ -3,12 +3,12 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/bloc/three_gang_glass_switch_bloc.dart'; import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/factories/three_gang_glass_switch_bloc_factory.dart'; +import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -import '../models/three_gang_glass_switch.dart'; - -class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperResponsiveLayout { +class ThreeGangGlassSwitchControlView extends StatelessWidget + with HelperResponsiveLayout { final String deviceId; const ThreeGangGlassSwitchControlView({required this.deviceId, super.key}); @@ -17,7 +17,8 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperRespons Widget build(BuildContext context) { return BlocProvider( create: (context) => - ThreeGangGlassSwitchBlocFactory.create(deviceId: deviceId)..add(ThreeGangGlassSwitchFetchDeviceEvent(deviceId)), + ThreeGangGlassSwitchBlocFactory.create(deviceId: deviceId) + ..add(ThreeGangGlassSwitchFetchDeviceEvent(deviceId)), child: BlocBuilder( builder: (context, state) { if (state is ThreeGangGlassSwitchLoading) { @@ -34,7 +35,8 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperRespons ); } - Widget _buildStatusControls(BuildContext context, ThreeGangGlassStatusModel status) { + Widget _buildStatusControls( + BuildContext context, ThreeGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -57,7 +59,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperRespons value: status.switch1, code: 'switch_1', deviceId: deviceId, - label: "Wall Light", + label: 'Wall Light', onChange: (value) { context.read().add( ThreeGangGlassSwitchControl( @@ -72,7 +74,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperRespons value: status.switch2, code: 'switch_2', deviceId: deviceId, - label: "Ceiling Light", + label: 'Ceiling Light', onChange: (value) { context.read().add( ThreeGangGlassSwitchControl( @@ -87,7 +89,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperRespons value: status.switch3, code: 'switch_3', deviceId: deviceId, - label: "SpotLight", + label: 'SpotLight', onChange: (value) { context.read().add( ThreeGangGlassSwitchControl( diff --git a/lib/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart b/lib/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart index bec1314c..be51b1d2 100644 --- a/lib/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart +++ b/lib/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart @@ -39,9 +39,11 @@ class LivingRoomBloc extends Bloc { ) async { emit(LivingRoomDeviceStatusLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); _listenToChanges(deviceId); - deviceStatus = LivingRoomStatusModel.fromJson(event.deviceId, status.status); + deviceStatus = + LivingRoomStatusModel.fromJson(event.deviceId, status.status); emit(LivingRoomDeviceStatusLoaded(deviceStatus)); } catch (e) { emit(LivingRoomDeviceManagementError(e.toString())); @@ -52,9 +54,9 @@ class LivingRoomBloc extends Bloc { try { final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value as Map; + final eventsMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -122,7 +124,8 @@ class LivingRoomBloc extends Bloc { ) async { emit(LivingRoomDeviceStatusLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final status = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = LivingRoomStatusModel.fromJson(event.devicesIds.first, status.status); emit(LivingRoomDeviceStatusLoaded(deviceStatus)); diff --git a/lib/pages/device_managment/three_gang_switch/models/living_room_model.dart b/lib/pages/device_managment/three_gang_switch/models/living_room_model.dart index 4bb5eada..60ea3d12 100644 --- a/lib/pages/device_managment/three_gang_switch/models/living_room_model.dart +++ b/lib/pages/device_managment/three_gang_switch/models/living_room_model.dart @@ -18,7 +18,7 @@ class LivingRoomStatusModel { late bool switch2; late bool switch3; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; // default to false if null diff --git a/lib/pages/device_managment/three_gang_switch/view/living_room_batch_controls.dart b/lib/pages/device_managment/three_gang_switch/view/living_room_batch_controls.dart index 0b1a2f06..77647078 100644 --- a/lib/pages/device_managment/three_gang_switch/view/living_room_batch_controls.dart +++ b/lib/pages/device_managment/three_gang_switch/view/living_room_batch_controls.dart @@ -2,14 +2,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart'; import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_reset.dart'; +import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; // import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/factories/living_room_bloc_factory.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/models/living_room_model.dart'; -import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class LivingRoomBatchControlsView extends StatelessWidget with HelperResponsiveLayout { +class LivingRoomBatchControlsView extends StatelessWidget + with HelperResponsiveLayout { const LivingRoomBatchControlsView({super.key, required this.deviceIds}); final List deviceIds; @@ -18,14 +19,16 @@ class LivingRoomBatchControlsView extends StatelessWidget with HelperResponsiveL Widget build(BuildContext context) { return BlocProvider( create: (context) => - LivingRoomBlocFactory.create(deviceId: deviceIds.first)..add(LivingRoomFetchBatchEvent(deviceIds)), + LivingRoomBlocFactory.create(deviceId: deviceIds.first) + ..add(LivingRoomFetchBatchEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is LivingRoomDeviceStatusLoading) { return const Center(child: CircularProgressIndicator()); } else if (state is LivingRoomDeviceStatusLoaded) { return _buildStatusControls(context, state.status); - } else if (state is LivingRoomDeviceManagementError || state is LivingRoomControlError) { + } else if (state is LivingRoomDeviceManagementError || + state is LivingRoomControlError) { return const Center(child: Text('Error fetching status')); } else { return const Center(child: CircularProgressIndicator()); @@ -35,7 +38,8 @@ class LivingRoomBatchControlsView extends StatelessWidget with HelperResponsiveL ); } - Widget _buildStatusControls(BuildContext context, LivingRoomStatusModel status) { + Widget _buildStatusControls( + BuildContext context, LivingRoomStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); diff --git a/lib/pages/device_managment/three_gang_switch/view/living_room_device_control.dart b/lib/pages/device_managment/three_gang_switch/view/living_room_device_control.dart index 731b354c..7d0faf7f 100644 --- a/lib/pages/device_managment/three_gang_switch/view/living_room_device_control.dart +++ b/lib/pages/device_managment/three_gang_switch/view/living_room_device_control.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/factories/living_room_bloc_factory.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/models/living_room_model.dart'; -import 'package:syncrow_web/pages/device_managment/shared/toggle_widget.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; class LivingRoomDeviceControlsView extends StatelessWidget diff --git a/lib/pages/device_managment/three_gang_switch/widgets/cieling_light.dart b/lib/pages/device_managment/three_gang_switch/widgets/cieling_light.dart index 629c131b..ed0896fa 100644 --- a/lib/pages/device_managment/three_gang_switch/widgets/cieling_light.dart +++ b/lib/pages/device_managment/three_gang_switch/widgets/cieling_light.dart @@ -1,5 +1,4 @@ import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart'; @@ -7,7 +6,11 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; class CeilingLight extends StatelessWidget { - const CeilingLight({super.key, required this.value, required this.code, required this.deviceId}); + const CeilingLight( + {super.key, + required this.value, + required this.code, + required this.deviceId}); final bool value; final String code; @@ -23,7 +26,7 @@ class CeilingLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -37,7 +40,7 @@ class CeilingLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, onChanged: (newValue) { context.read().add( LivingRoomControl( diff --git a/lib/pages/device_managment/three_gang_switch/widgets/spot_light.dart b/lib/pages/device_managment/three_gang_switch/widgets/spot_light.dart index 6ac71a38..ea635247 100644 --- a/lib/pages/device_managment/three_gang_switch/widgets/spot_light.dart +++ b/lib/pages/device_managment/three_gang_switch/widgets/spot_light.dart @@ -1,5 +1,4 @@ import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart'; @@ -7,7 +6,11 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; class SpotLight extends StatelessWidget { - const SpotLight({super.key, required this.value, required this.code, required this.deviceId}); + const SpotLight( + {super.key, + required this.value, + required this.code, + required this.deviceId}); final bool value; final String code; @@ -23,7 +26,7 @@ class SpotLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -37,7 +40,7 @@ class SpotLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, onChanged: (newValue) { context.read().add( LivingRoomControl( diff --git a/lib/pages/device_managment/three_gang_switch/widgets/wall_light.dart b/lib/pages/device_managment/three_gang_switch/widgets/wall_light.dart index 12c814ac..8844cb1e 100644 --- a/lib/pages/device_managment/three_gang_switch/widgets/wall_light.dart +++ b/lib/pages/device_managment/three_gang_switch/widgets/wall_light.dart @@ -1,5 +1,4 @@ import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart'; @@ -7,7 +6,11 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; class WallLight extends StatelessWidget { - const WallLight({super.key, required this.value, required this.code, required this.deviceId}); + const WallLight( + {super.key, + required this.value, + required this.code, + required this.deviceId}); final bool value; final String code; @@ -23,7 +26,7 @@ class WallLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -37,7 +40,7 @@ class WallLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeColor: ColorsManager.dialogBlueTitle, + activeTrackColor: ColorsManager.dialogBlueTitle, onChanged: (newValue) { context.read().add( LivingRoomControl( diff --git a/lib/pages/device_managment/two_g_glass_switch/bloc/two_gang_glass_switch_bloc.dart b/lib/pages/device_managment/two_g_glass_switch/bloc/two_gang_glass_switch_bloc.dart index 8f82c198..2a71f477 100644 --- a/lib/pages/device_managment/two_g_glass_switch/bloc/two_gang_glass_switch_bloc.dart +++ b/lib/pages/device_managment/two_g_glass_switch/bloc/two_gang_glass_switch_bloc.dart @@ -42,8 +42,10 @@ class TwoGangGlassSwitchBloc ) async { emit(TwoGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); - deviceStatus = TwoGangGlassStatusModel.fromJson(event.deviceId, status.status); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); + deviceStatus = + TwoGangGlassStatusModel.fromJson(event.deviceId, status.status); _listenToChanges(event.deviceId); emit(TwoGangGlassSwitchStatusLoaded(deviceStatus)); } catch (e) { @@ -58,11 +60,12 @@ class TwoGangGlassSwitchBloc ); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value as Map; + final eventsMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; eventsMap['status'].forEach((element) { - statusList.add(Status(code: element['code'], value: element['value'])); + statusList + .add(Status(code: element['code'], value: element['value'])); }); deviceStatus = TwoGangGlassStatusModel.fromJson(deviceId, statusList); @@ -121,7 +124,8 @@ class TwoGangGlassSwitchBloc ) async { emit(TwoGangGlassSwitchLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.deviceIds); + final status = + await DevicesManagementApi().getBatchStatus(event.deviceIds); deviceStatus = TwoGangGlassStatusModel.fromJson( event.deviceIds.first, status.status, diff --git a/lib/pages/device_managment/two_g_glass_switch/models/two_gang_glass_status_model.dart b/lib/pages/device_managment/two_g_glass_switch/models/two_gang_glass_status_model.dart index 54d99d74..1d407ab6 100644 --- a/lib/pages/device_managment/two_g_glass_switch/models/two_gang_glass_status_model.dart +++ b/lib/pages/device_managment/two_g_glass_switch/models/two_gang_glass_status_model.dart @@ -21,7 +21,7 @@ class TwoGangGlassStatusModel { late bool switch2; late int countDown2; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; diff --git a/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_batch_control_view.dart b/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_batch_control_view.dart index 9d120ad6..a70f1dfe 100644 --- a/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_batch_control_view.dart +++ b/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_batch_control_view.dart @@ -9,16 +9,19 @@ import 'package:syncrow_web/pages/device_managment/two_g_glass_switch/factories/ import 'package:syncrow_web/pages/device_managment/two_g_glass_switch/models/two_gang_glass_status_model.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class TwoGangGlassSwitchBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class TwoGangGlassSwitchBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const TwoGangGlassSwitchBatchControlView({required this.deviceIds, super.key}); + const TwoGangGlassSwitchBatchControlView( + {required this.deviceIds, super.key}); @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => TwoGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) - ..add(TwoGangGlassSwitchFetchBatchStatusEvent(deviceIds)), + create: (context) => + TwoGangGlassSwitchBlocFactory.create(deviceId: deviceIds.first) + ..add(TwoGangGlassSwitchFetchBatchStatusEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is TwoGangGlassSwitchLoading) { @@ -35,7 +38,8 @@ class TwoGangGlassSwitchBatchControlView extends StatelessWidget with HelperResp ); } - Widget _buildStatusControls(BuildContext context, TwoGangGlassStatusModel status) { + Widget _buildStatusControls( + BuildContext context, TwoGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); diff --git a/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_control_view.dart b/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_control_view.dart index 575deeac..34e96c2b 100644 --- a/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_control_view.dart +++ b/lib/pages/device_managment/two_g_glass_switch/view/two_gang_glass_switch_control_view.dart @@ -16,8 +16,9 @@ class TwoGangGlassSwitchControlView extends StatelessWidget @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => TwoGangGlassSwitchBlocFactory.create(deviceId: deviceId) - ..add(TwoGangGlassSwitchFetchDeviceEvent(deviceId)), + create: (context) => + TwoGangGlassSwitchBlocFactory.create(deviceId: deviceId) + ..add(TwoGangGlassSwitchFetchDeviceEvent(deviceId)), child: BlocBuilder( builder: (context, state) { if (state is TwoGangGlassSwitchLoading) { diff --git a/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_bloc.dart b/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_bloc.dart index 2e3a8633..1d959ffb 100644 --- a/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_bloc.dart +++ b/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_bloc.dart @@ -37,7 +37,8 @@ class TwoGangSwitchBloc extends Bloc { ) async { emit(TwoGangSwitchLoading()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); deviceStatus = TwoGangStatusModel.fromJson(event.deviceId, status.status); _listenToChanges(event.deviceId); emit(TwoGangSwitchStatusLoaded(deviceStatus)); @@ -51,9 +52,9 @@ class TwoGangSwitchBloc extends Bloc { final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value as Map; + final eventsMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -116,7 +117,8 @@ class TwoGangSwitchBloc extends Bloc { ) async { emit(TwoGangSwitchLoading()); try { - final status = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final status = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = TwoGangStatusModel.fromJson( event.devicesIds.first, status.status, diff --git a/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart b/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart index b9208211..f4596d8c 100644 --- a/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart +++ b/lib/pages/device_managment/two_gang_switch/bloc/two_gang_switch_state.dart @@ -22,7 +22,7 @@ class TwoGangSwitchStatusLoaded extends TwoGangSwitchState { class TwoGangSwitchError extends TwoGangSwitchState { final String message; - TwoGangSwitchError(this.message); + TwoGangSwitchError(this.message); @override List get props => [message]; diff --git a/lib/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart b/lib/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart index 58094a71..78794d72 100644 --- a/lib/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart +++ b/lib/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart @@ -21,7 +21,7 @@ class TwoGangStatusModel { late int countDown; late int countDown2; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': switch1 = bool.tryParse(status.value.toString()) ?? false; diff --git a/lib/pages/device_managment/two_gang_switch/view/wall_light_batch_control.dart b/lib/pages/device_managment/two_gang_switch/view/wall_light_batch_control.dart index e8346cb2..1284a93b 100644 --- a/lib/pages/device_managment/two_gang_switch/view/wall_light_batch_control.dart +++ b/lib/pages/device_managment/two_gang_switch/view/wall_light_batch_control.dart @@ -10,7 +10,8 @@ import 'package:syncrow_web/pages/device_managment/two_gang_switch/factories/two import 'package:syncrow_web/pages/device_managment/two_gang_switch/models/two_gang_status_model.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class TwoGangBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class TwoGangBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const TwoGangBatchControlView({super.key, required this.deviceIds}); final List deviceIds; @@ -18,15 +19,17 @@ class TwoGangBatchControlView extends StatelessWidget with HelperResponsiveLayou @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => TwoGangSwitchBlocFactory.create(deviceId: deviceIds.first) - ..add(TwoGangSwitchFetchBatchEvent(deviceIds)), + create: (context) => + TwoGangSwitchBlocFactory.create(deviceId: deviceIds.first) + ..add(TwoGangSwitchFetchBatchEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is TwoGangSwitchLoading) { return const Center(child: CircularProgressIndicator()); } else if (state is TwoGangSwitchStatusLoaded) { return _buildStatusControls(context, state.status); - } else if (state is TwoGangSwitchError || state is TwoGangSwitchControlError) { + } else if (state is TwoGangSwitchError || + state is TwoGangSwitchControlError) { return const Center(child: Text('Error fetching status')); } else { return const Center(child: CircularProgressIndicator()); diff --git a/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart b/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart index 630a132b..4db3798e 100644 --- a/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart +++ b/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart @@ -55,7 +55,8 @@ class WallSensorBloc extends Bloc { ) async { emit(WallSensorLoadingInitialState()); try { - final response = await DevicesManagementApi().getBatchStatus(event.devicesIds); + final response = + await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = WallSensorModel.fromJson(response.status); emit(WallSensorUpdateState(wallSensorModel: deviceStatus)); } catch (e) { @@ -68,9 +69,9 @@ class WallSensorBloc extends Bloc { final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value as Map; + final eventsMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), diff --git a/lib/pages/device_managment/wall_sensor/model/wall_sensor_model.dart b/lib/pages/device_managment/wall_sensor/model/wall_sensor_model.dart index 92b1842e..d193df93 100644 --- a/lib/pages/device_managment/wall_sensor/model/wall_sensor_model.dart +++ b/lib/pages/device_managment/wall_sensor/model/wall_sensor_model.dart @@ -23,46 +23,46 @@ class WallSensorModel { required this.noBodyTime}); factory WallSensorModel.fromJson(List jsonList) { - late String _presenceState; - late int _farDetection; - late int _presenceTime; - late int _motionSensitivity; - late int _motionlessSensitivity; - late int _currentDistance; - late int _illuminance; - late bool _indicator; - late int _noBodyTime; + late String presenceState; + late int farDetection; + late int presenceTime; + late int motionSensitivity; + late int motionlessSensitivity; + late int currentDistance; + late int illuminance; + late bool indicator; + late int noBodyTime; - for (int i = 0; i < jsonList.length; i++) { + for (var i = 0; i < jsonList.length; i++) { if (jsonList[i].code == 'presence_state') { - _presenceState = jsonList[i].value ?? 'none'; + presenceState = jsonList[i].value ?? 'none'; } else if (jsonList[i].code == 'far_detection') { - _farDetection = jsonList[i].value ?? 0; + farDetection = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'presence_time') { - _presenceTime = jsonList[i].value ?? 0; + presenceTime = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'motion_sensitivity_value') { - _motionSensitivity = jsonList[i].value ?? 0; + motionSensitivity = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'motionless_sensitivity') { - _motionlessSensitivity = jsonList[i].value ?? 0; + motionlessSensitivity = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'dis_current') { - _currentDistance = jsonList[i].value ?? 0; + currentDistance = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'illuminance_value') { - _illuminance = jsonList[i].value ?? 0; + illuminance = jsonList[i].value ?? 0; } else if (jsonList[i].code == 'indicator') { - _indicator = jsonList[i].value ?? false; + indicator = jsonList[i].value ?? false; } else if (jsonList[i].code == 'no_one_time') { - _noBodyTime = jsonList[i].value ?? 0; + noBodyTime = jsonList[i].value ?? 0; } } return WallSensorModel( - presenceState: _presenceState, - farDetection: _farDetection, - presenceTime: _presenceTime, - motionSensitivity: _motionSensitivity, - motionlessSensitivity: _motionlessSensitivity, - currentDistance: _currentDistance, - illuminance: _illuminance, - indicator: _indicator, - noBodyTime: _noBodyTime); + presenceState: presenceState, + farDetection: farDetection, + presenceTime: presenceTime, + motionSensitivity: motionSensitivity, + motionlessSensitivity: motionlessSensitivity, + currentDistance: currentDistance, + illuminance: illuminance, + indicator: indicator, + noBodyTime: noBodyTime); } } diff --git a/lib/pages/device_managment/wall_sensor/view/wall_sensor_batch_control.dart b/lib/pages/device_managment/wall_sensor/view/wall_sensor_batch_control.dart index 61108387..6d15ba37 100644 --- a/lib/pages/device_managment/wall_sensor/view/wall_sensor_batch_control.dart +++ b/lib/pages/device_managment/wall_sensor/view/wall_sensor_batch_control.dart @@ -11,7 +11,8 @@ import 'package:syncrow_web/pages/device_managment/wall_sensor/factories/wall_se import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class WallSensorBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class WallSensorBatchControlView extends StatelessWidget + with HelperResponsiveLayout { const WallSensorBatchControlView({super.key, required this.devicesIds}); final List devicesIds; @@ -22,17 +23,21 @@ class WallSensorBatchControlView extends StatelessWidget with HelperResponsiveLa final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); return BlocProvider( - create: (context) => WallSensorBlocFactory.create(deviceId: devicesIds.first) - ..add(WallSensorFetchBatchStatusEvent(devicesIds)), + create: (context) => + WallSensorBlocFactory.create(deviceId: devicesIds.first) + ..add(WallSensorFetchBatchStatusEvent(devicesIds)), child: BlocBuilder( builder: (context, state) { - if (state is WallSensorLoadingInitialState || state is DeviceReportsLoadingState) { + if (state is WallSensorLoadingInitialState || + state is DeviceReportsLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is WallSensorUpdateState) { - return _buildGridView(context, state.wallSensorModel, isExtraLarge, isLarge, isMedium); + return _buildGridView(context, state.wallSensorModel, isExtraLarge, + isLarge, isMedium); } else if (state is DeviceReportsFailedState) { final model = context.read().deviceStatus; - return _buildGridView(context, model, isExtraLarge, isLarge, isMedium); + return _buildGridView( + context, model, isExtraLarge, isLarge, isMedium); } return const Center(child: Text('Error fetching status')); }, @@ -40,8 +45,8 @@ class WallSensorBatchControlView extends StatelessWidget with HelperResponsiveLa ); } - Widget _buildGridView( - BuildContext context, WallSensorModel model, bool isExtraLarge, bool isLarge, bool isMedium) { + Widget _buildGridView(BuildContext context, WallSensorModel model, + bool isExtraLarge, bool isLarge, bool isMedium) { return GridView( padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20), shrinkWrap: true, @@ -94,11 +99,12 @@ class WallSensorBatchControlView extends StatelessWidget with HelperResponsiveLa maxValue: 10000, steps: 1, description: 'sec', - action: (int value) => context.read().add(WallSensorBatchControlEvent( - deviceIds: devicesIds, - code: 'no_one_time', - value: value, - ))), + action: (int value) => + context.read().add(WallSensorBatchControlEvent( + deviceIds: devicesIds, + code: 'no_one_time', + value: value, + ))), PresenceUpdateData( value: model.farDetection.toDouble(), title: 'Far Detection:', diff --git a/lib/pages/device_managment/wall_sensor/view/wall_sensor_conrtols.dart b/lib/pages/device_managment/wall_sensor/view/wall_sensor_conrtols.dart index def8ed93..b6279b07 100644 --- a/lib/pages/device_managment/wall_sensor/view/wall_sensor_conrtols.dart +++ b/lib/pages/device_managment/wall_sensor/view/wall_sensor_conrtols.dart @@ -1,21 +1,22 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart'; +import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_display_data.dart'; +import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart'; +import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_status.dart'; +import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart'; import 'package:syncrow_web/pages/device_managment/shared/table/description_view.dart'; import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart'; import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_bloc.dart'; import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_event.dart'; import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_state.dart'; -import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_display_data.dart'; -import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart'; -import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_status.dart'; -import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart'; import 'package:syncrow_web/pages/device_managment/wall_sensor/factories/wall_sensor_bloc_factory.dart'; import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout { +class WallSensorControlsView extends StatelessWidget + with HelperResponsiveLayout { const WallSensorControlsView({super.key, required this.device}); final AllDevicesModel device; @@ -26,19 +27,23 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); return BlocProvider( - create: (context) => - WallSensorBlocFactory.create(deviceId: device.uuid!)..add(WallSensorFetchStatusEvent()), + create: (context) => WallSensorBlocFactory.create(deviceId: device.uuid!) + ..add(WallSensorFetchStatusEvent()), child: BlocBuilder( builder: (context, state) { - if (state is WallSensorLoadingInitialState || state is DeviceReportsLoadingState) { + if (state is WallSensorLoadingInitialState || + state is DeviceReportsLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is WallSensorUpdateState) { - return _buildGridView(context, state.wallSensorModel, isExtraLarge, isLarge, isMedium); + return _buildGridView(context, state.wallSensorModel, isExtraLarge, + isLarge, isMedium); } else if (state is DeviceReportsState) { return ReportsTable( report: state.deviceReport, - thirdColumnTitle: state.code == 'illuminance_value' ? "Value" : 'Status', - thirdColumnDescription: state.code == 'illuminance_value' ? "Lux" : null, + thirdColumnTitle: + state.code == 'illuminance_value' ? 'Value' : 'Status', + thirdColumnDescription: + state.code == 'illuminance_value' ? 'Lux' : null, onRowTap: (index) {}, onClose: () { context.read().add(BackToGridViewEvent()); @@ -53,7 +58,8 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout ); } else if (state is DeviceReportsFailedState) { final model = context.read().deviceStatus; - return _buildGridView(context, model, isExtraLarge, isLarge, isMedium); + return _buildGridView( + context, model, isExtraLarge, isLarge, isMedium); } return const Center(child: Text('Error fetching status')); }, @@ -61,8 +67,8 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout ); } - Widget _buildGridView( - BuildContext context, WallSensorModel model, bool isExtraLarge, bool isLarge, bool isMedium) { + Widget _buildGridView(BuildContext context, WallSensorModel model, + bool isExtraLarge, bool isLarge, bool isMedium) { return GridView( padding: const EdgeInsets.symmetric(horizontal: 50), shrinkWrap: true, @@ -131,10 +137,11 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout maxValue: 10000, steps: 1, description: 'sec', - action: (int value) => context.read().add(WallSensorChangeValueEvent( - code: 'no_one_time', - value: value, - ))), + action: (int value) => + context.read().add(WallSensorChangeValueEvent( + code: 'no_one_time', + value: value, + ))), PresenceUpdateData( value: model.farDetection.toDouble(), title: 'Far Detection:', @@ -151,9 +158,8 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout ), GestureDetector( onTap: () { - context - .read() - .add(GetDeviceReportsEvent(code: 'illuminance_value', deviceUuid: device.uuid!)); + context.read().add(GetDeviceReportsEvent( + code: 'illuminance_value', deviceUuid: device.uuid!)); }, child: const PresenceStaticWidget( icon: Assets.illuminanceRecordIcon, @@ -162,9 +168,8 @@ class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout ), GestureDetector( onTap: () { - context - .read() - .add(GetDeviceReportsEvent(code: 'presence_state', deviceUuid: device.uuid!)); + context.read().add(GetDeviceReportsEvent( + code: 'presence_state', deviceUuid: device.uuid!)); }, child: const PresenceStaticWidget( icon: Assets.presenceRecordIcon, diff --git a/lib/pages/device_managment/water_heater/bloc/water_heater_bloc.dart b/lib/pages/device_managment/water_heater/bloc/water_heater_bloc.dart index 560a61e1..69b49e4c 100644 --- a/lib/pages/device_managment/water_heater/bloc/water_heater_bloc.dart +++ b/lib/pages/device_managment/water_heater/bloc/water_heater_bloc.dart @@ -123,11 +123,13 @@ class WaterHeaterBloc extends Bloc { countdownRemaining: countdownRemaining, )); - if (!currentState.isCountdownActive! && countdownRemaining > Duration.zero) { + if (!currentState.isCountdownActive! && + countdownRemaining > Duration.zero) { _startCountdownTimer(emit, countdownRemaining); } } else if (event.scheduleMode == ScheduleModes.inching) { - final inchingDuration = Duration(hours: event.hours, minutes: event.minutes); + final inchingDuration = + Duration(hours: event.hours, minutes: event.minutes); emit( currentState.copyWith( @@ -165,7 +167,7 @@ class WaterHeaterBloc extends Bloc { ); if (success) { - if (event.code == "countdown_1") { + if (event.code == 'countdown_1') { final countdownDuration = Duration(seconds: event.value); emit( @@ -190,7 +192,7 @@ class WaterHeaterBloc extends Bloc { ), ); } - } else if (event.code == "switch_inching") { + } else if (event.code == 'switch_inching') { final inchingDuration = Duration(seconds: event.value); emit( currentState.copyWith( @@ -236,7 +238,8 @@ class WaterHeaterBloc extends Bloc { try { final status = await DevicesManagementApi().deviceControl( event.deviceId, - Status(code: isCountDown ? 'countdown_1' : 'switch_inching', value: 0), + Status( + code: isCountDown ? 'countdown_1' : 'switch_inching', value: 0), ); if (!status) { emit(const WaterHeaterFailedState(error: 'Failed to stop schedule.')); @@ -254,8 +257,10 @@ class WaterHeaterBloc extends Bloc { emit(WaterHeaterLoadingState()); try { - final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); - deviceStatus = WaterHeaterStatusModel.fromJson(event.deviceId, status.status); + final status = + await DevicesManagementApi().getDeviceStatus(event.deviceId); + deviceStatus = + WaterHeaterStatusModel.fromJson(event.deviceId, status.status); if (deviceStatus.scheduleMode == ScheduleModes.countdown) { final countdownRemaining = Duration( @@ -326,21 +331,20 @@ class WaterHeaterBloc extends Bloc { void _listenToChanges(deviceId) { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$deviceId'); - Stream stream = ref.onValue; + final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + final stream = ref.onValue; stream.listen((DatabaseEvent event) { - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { - statusList.add(Status(code: element['code'], value: element['value'])); + statusList + .add(Status(code: element['code'], value: element['value'])); }); - deviceStatus = - WaterHeaterStatusModel.fromJson(usersMap['productUuid'], statusList); + deviceStatus = WaterHeaterStatusModel.fromJson( + usersMap['productUuid'], statusList); if (!isClosed) { add(StatusUpdated(deviceStatus)); } @@ -475,14 +479,14 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - ScheduleEntry newSchedule = ScheduleEntry( + final newSchedule = ScheduleEntry( category: event.category, time: formatTimeOfDayToISO(event.time), function: Status(code: 'switch_1', value: event.functionOn), days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - bool success = await DevicesManagementApi() + final success = await DevicesManagementApi() .addScheduleRecord(newSchedule, currentState.status.uuid); if (success) { @@ -500,7 +504,7 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - ScheduleEntry newSchedule = ScheduleEntry( + final newSchedule = ScheduleEntry( scheduleId: event.scheduleId, category: event.category, time: formatTimeOfDayToISO(event.time), @@ -508,7 +512,7 @@ class WaterHeaterBloc extends Bloc { days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - bool success = await DevicesManagementApi().editScheduleRecord( + final success = await DevicesManagementApi().editScheduleRecord( currentState.status.uuid, newSchedule, ); @@ -538,7 +542,7 @@ class WaterHeaterBloc extends Bloc { return schedule; }).toList(); - bool success = await DevicesManagementApi().updateScheduleRecord( + final success = await DevicesManagementApi().updateScheduleRecord( enable: event.enable, uuid: currentState.status.uuid, scheduleId: event.scheduleId, @@ -559,7 +563,7 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - bool success = await DevicesManagementApi() + final success = await DevicesManagementApi() .deleteScheduleRecord(currentState.status.uuid, event.scheduleId); if (success) { @@ -584,8 +588,8 @@ class WaterHeaterBloc extends Bloc { final status = await DevicesManagementApi().getBatchStatus( event.devicesUuid, ); - deviceStatus = - WaterHeaterStatusModel.fromJson(event.devicesUuid.first, status.status); + deviceStatus = WaterHeaterStatusModel.fromJson( + event.devicesUuid.first, status.status); emit(WaterHeaterDeviceStatusLoaded(deviceStatus)); } catch (e) { @@ -593,8 +597,8 @@ class WaterHeaterBloc extends Bloc { } } - Future _batchControlWaterHeater( - ControlWaterHeaterBatchEvent event, Emitter emit) async { + Future _batchControlWaterHeater(ControlWaterHeaterBatchEvent event, + Emitter emit) async { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; @@ -613,7 +617,7 @@ class WaterHeaterBloc extends Bloc { ); if (success) { - if (event.code == "switch_1") { + if (event.code == 'switch_1') { emit(currentState.copyWith( status: deviceStatus, )); diff --git a/lib/pages/device_managment/water_heater/bloc/water_heater_event.dart b/lib/pages/device_managment/water_heater/bloc/water_heater_event.dart index e4cc8474..92c5c293 100644 --- a/lib/pages/device_managment/water_heater/bloc/water_heater_event.dart +++ b/lib/pages/device_managment/water_heater/bloc/water_heater_event.dart @@ -54,7 +54,6 @@ final class WaterHeaterFetchStatusEvent extends WaterHeaterEvent { final class DecrementCountdownEvent extends WaterHeaterEvent {} - class StatusUpdated extends WaterHeaterEvent { final WaterHeaterStatusModel deviceStatus; const StatusUpdated(this.deviceStatus); @@ -62,7 +61,6 @@ class StatusUpdated extends WaterHeaterEvent { List get props => [deviceStatus]; } - final class AddScheduleEvent extends WaterHeaterEvent { final List selectedDays; final TimeOfDay time; diff --git a/lib/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart b/lib/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart index 9278e396..27df3a9e 100644 --- a/lib/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart +++ b/lib/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart @@ -7,11 +7,12 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; class ScheduleDialogHelper { - static void showAddScheduleDialog(BuildContext context, {ScheduleModel? schedule, int? index, bool? isEdit}) { + static void showAddScheduleDialog(BuildContext context, + {ScheduleModel? schedule, int? index, bool? isEdit}) { final bloc = context.read(); if (schedule == null) { - bloc.add((const UpdateSelectedTimeEvent(null))); + bloc.add(const UpdateSelectedTimeEvent(null)); bloc.add(InitializeAddScheduleEvent( selectedTime: null, selectedDays: List.filled(7, false), @@ -70,9 +71,10 @@ class ScheduleDialogHelper { backgroundColor: ColorsManager.boxColor, borderRadius: 15, onPressed: () async { - TimeOfDay? time = await showTimePicker( + final time = await showTimePicker( context: context, - initialTime: state.selectedTime ?? TimeOfDay.now(), + initialTime: + state.selectedTime ?? TimeOfDay.now(), builder: (context, child) { return Theme( data: Theme.of(context).copyWith( @@ -92,7 +94,9 @@ class ScheduleDialogHelper { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - state.selectedTime == null ? 'Time' : state.selectedTime!.format(context), + state.selectedTime == null + ? 'Time' + : state.selectedTime!.format(context), style: context.textTheme.bodySmall!.copyWith( color: ColorsManager.grayColor, ), @@ -107,7 +111,8 @@ class ScheduleDialogHelper { ), ), const SizedBox(height: 16), - _buildDayCheckboxes(context, state.selectedDays, isEdit: isEdit), + _buildDayCheckboxes(context, state.selectedDays, + isEdit: isEdit), const SizedBox(height: 16), _buildFunctionSwitch(context, state.functionOn, isEdit), ], @@ -181,9 +186,9 @@ class ScheduleDialogHelper { static List _convertDaysStringToBooleans(List selectedDays) { final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - List daysBoolean = List.filled(7, false); + final daysBoolean = List.filled(7, false); - for (int i = 0; i < daysOfWeek.length; i++) { + for (var i = 0; i < daysOfWeek.length; i++) { if (selectedDays.contains(daysOfWeek[i])) { daysBoolean[i] = true; } @@ -192,7 +197,9 @@ class ScheduleDialogHelper { return daysBoolean; } - static Widget _buildDayCheckboxes(BuildContext context, List selectedDays, {bool? isEdit}) { + static Widget _buildDayCheckboxes( + BuildContext context, List selectedDays, + {bool? isEdit}) { final dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; return Row( @@ -202,7 +209,9 @@ class ScheduleDialogHelper { Checkbox( value: selectedDays[index], onChanged: (bool? value) { - context.read().add(UpdateSelectedDayEvent(index, value!)); + context + .read() + .add(UpdateSelectedDayEvent(index, value!)); }, ), Text(dayLabels[index]), @@ -212,19 +221,23 @@ class ScheduleDialogHelper { ); } - static Widget _buildFunctionSwitch(BuildContext context, bool isOn, bool? isEdit) { + static Widget _buildFunctionSwitch( + BuildContext context, bool isOn, bool? isEdit) { return Row( children: [ Text( 'Function:', - style: context.textTheme.bodySmall!.copyWith(color: ColorsManager.grayColor), + style: context.textTheme.bodySmall! + .copyWith(color: ColorsManager.grayColor), ), const SizedBox(width: 10), Radio( value: true, groupValue: isOn, onChanged: (bool? value) { - context.read().add(const UpdateFunctionOnEvent(true)); + context + .read() + .add(const UpdateFunctionOnEvent(true)); }, ), const Text('On'), @@ -233,7 +246,9 @@ class ScheduleDialogHelper { value: false, groupValue: isOn, onChanged: (bool? value) { - context.read().add(const UpdateFunctionOnEvent(false)); + context + .read() + .add(const UpdateFunctionOnEvent(false)); }, ), const Text('Off'), diff --git a/lib/pages/device_managment/water_heater/models/schedule_entry.dart b/lib/pages/device_managment/water_heater/models/schedule_entry.dart index a2a109af..4a379009 100644 --- a/lib/pages/device_managment/water_heater/models/schedule_entry.dart +++ b/lib/pages/device_managment/water_heater/models/schedule_entry.dart @@ -58,7 +58,8 @@ class ScheduleEntry { String toJson() => json.encode(toMap()); - factory ScheduleEntry.fromJson(String source) => ScheduleEntry.fromMap(json.decode(source)); + factory ScheduleEntry.fromJson(String source) => + ScheduleEntry.fromMap(json.decode(source)); @override bool operator ==(Object other) { @@ -73,6 +74,9 @@ class ScheduleEntry { @override int get hashCode { - return category.hashCode ^ time.hashCode ^ function.hashCode ^ days.hashCode; + return category.hashCode ^ + time.hashCode ^ + function.hashCode ^ + days.hashCode; } } diff --git a/lib/pages/device_managment/water_heater/models/schedule_model.dart b/lib/pages/device_managment/water_heater/models/schedule_model.dart index 3d05a3e0..b90cf921 100644 --- a/lib/pages/device_managment/water_heater/models/schedule_model.dart +++ b/lib/pages/device_managment/water_heater/models/schedule_model.dart @@ -1,7 +1,8 @@ import 'dart:convert'; + +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart'; -import 'package:flutter/foundation.dart'; class ScheduleModel { final String scheduleId; @@ -93,8 +94,8 @@ class ScheduleModel { static List convertSelectedDaysToStrings(List selectedDays) { const allDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - List result = []; - for (int i = 0; i < selectedDays.length; i++) { + final result = []; + for (var i = 0; i < selectedDays.length; i++) { if (selectedDays[i]) { result.add(allDays[i]); } diff --git a/lib/pages/device_managment/water_heater/models/water_heater_status_model.dart b/lib/pages/device_managment/water_heater/models/water_heater_status_model.dart index c535bda2..e4b48b5d 100644 --- a/lib/pages/device_managment/water_heater/models/water_heater_status_model.dart +++ b/lib/pages/device_managment/water_heater/models/water_heater_status_model.dart @@ -16,7 +16,7 @@ class WaterHeaterStatusModel extends Equatable { final String cycleTiming; final List schedules; - const WaterHeaterStatusModel({ + const WaterHeaterStatusModel({ required this.uuid, required this.heaterSwitch, required this.countdownHours, @@ -30,13 +30,13 @@ class WaterHeaterStatusModel extends Equatable { }); factory WaterHeaterStatusModel.fromJson(String id, List jsonList) { - late bool heaterSwitch = false; - late int countdownInSeconds = 0; - late String relayStatus = ''; - late String cycleTiming = ''; - late ScheduleModes scheduleMode = ScheduleModes.countdown; + late var heaterSwitch = false; + late var countdownInSeconds = 0; + late var relayStatus = ''; + late var cycleTiming = ''; + late var scheduleMode = ScheduleModes.countdown; - for (var status in jsonList) { + for (final status in jsonList) { switch (status.code) { case 'switch_1': heaterSwitch = status.value ?? false; diff --git a/lib/pages/device_managment/water_heater/view/water_heater_batch_control.dart b/lib/pages/device_managment/water_heater/view/water_heater_batch_control.dart index 3c8a3858..97ef6302 100644 --- a/lib/pages/device_managment/water_heater/view/water_heater_batch_control.dart +++ b/lib/pages/device_managment/water_heater/view/water_heater_batch_control.dart @@ -37,7 +37,8 @@ class WaterHEaterBatchControlView extends StatelessWidget ); } - Widget _buildStatusControls(BuildContext context, WaterHeaterStatusModel status) { + Widget _buildStatusControls( + BuildContext context, WaterHeaterStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); diff --git a/lib/pages/device_managment/water_heater/view/water_heater_device_control.dart b/lib/pages/device_managment/water_heater/view/water_heater_device_control.dart index f1e56136..f654e62c 100644 --- a/lib/pages/device_managment/water_heater/view/water_heater_device_control.dart +++ b/lib/pages/device_managment/water_heater/view/water_heater_device_control.dart @@ -35,7 +35,8 @@ class WaterHeaterDeviceControlView extends StatelessWidget state is WaterHeaterBatchFailedState) { return const Center(child: Text('Error fetching status')); } else { - return const SizedBox(height: 200, child: Center(child: SizedBox())); + return const SizedBox( + height: 200, child: Center(child: SizedBox())); } }, )); diff --git a/lib/pages/device_managment/water_heater/widgets/count_down_button.dart b/lib/pages/device_managment/water_heater/widgets/count_down_button.dart index e60c7def..4107b6ce 100644 --- a/lib/pages/device_managment/water_heater/widgets/count_down_button.dart +++ b/lib/pages/device_managment/water_heater/widgets/count_down_button.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/device_managment/water_heater/bloc/water_heater_bloc.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; class CountdownModeButtons extends StatelessWidget { diff --git a/lib/pages/device_managment/water_heater/widgets/inching_mode_buttons.dart b/lib/pages/device_managment/water_heater/widgets/inching_mode_buttons.dart index 8eec5cca..5257dddc 100644 --- a/lib/pages/device_managment/water_heater/widgets/inching_mode_buttons.dart +++ b/lib/pages/device_managment/water_heater/widgets/inching_mode_buttons.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/device_managment/water_heater/bloc/water_heater_bloc.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; class InchingModeButtons extends StatelessWidget { @@ -12,12 +12,12 @@ class InchingModeButtons extends StatelessWidget { final int minutes; const InchingModeButtons({ - Key? key, + super.key, required this.isActive, required this.deviceId, required this.hours, required this.minutes, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/pages/device_managment/water_heater/widgets/schedule_managment_ui.dart b/lib/pages/device_managment/water_heater/widgets/schedule_managment_ui.dart index 1710c439..0b2657c5 100644 --- a/lib/pages/device_managment/water_heater/widgets/schedule_managment_ui.dart +++ b/lib/pages/device_managment/water_heater/widgets/schedule_managment_ui.dart @@ -28,7 +28,7 @@ class ScheduleManagementUI extends StatelessWidget { padding: 2, backgroundColor: ColorsManager.graysColor, borderRadius: 15, - onPressed: () => onAddSchedule(), + onPressed: onAddSchedule, child: Row( children: [ const Icon(Icons.add, color: ColorsManager.primaryColor), diff --git a/lib/pages/device_managment/water_heater/widgets/schedule_mode_selector.dart b/lib/pages/device_managment/water_heater/widgets/schedule_mode_selector.dart index bb9ddc8f..fb73eaf4 100644 --- a/lib/pages/device_managment/water_heater/widgets/schedule_mode_selector.dart +++ b/lib/pages/device_managment/water_heater/widgets/schedule_mode_selector.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/water_heater/bloc/water_heater_bloc.dart'; +import 'package:syncrow_web/pages/device_managment/water_heater/models/water_heater_status_model.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; -import 'package:syncrow_web/pages/device_managment/water_heater/models/water_heater_status_model.dart'; class ScheduleModeSelector extends StatelessWidget { final WaterHeaterDeviceStatusLoaded state; diff --git a/lib/pages/device_managment/water_heater/widgets/schedule_table.dart b/lib/pages/device_managment/water_heater/widgets/schedule_table.dart index 18cbbe5a..576ebc2b 100644 --- a/lib/pages/device_managment/water_heater/widgets/schedule_table.dart +++ b/lib/pages/device_managment/water_heater/widgets/schedule_table.dart @@ -2,14 +2,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:syncrow_web/pages/device_managment/water_heater/bloc/water_heater_bloc.dart'; +import 'package:syncrow_web/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart'; import 'package:syncrow_web/pages/device_managment/water_heater/models/schedule_model.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/format_date_time.dart'; -import '../helper/add_schedule_dialog_helper.dart'; - class ScheduleTableWidget extends StatelessWidget { final WaterHeaterDeviceStatusLoaded state; @@ -211,8 +210,8 @@ class ScheduleTableWidget extends StatelessWidget { String _getSelectedDays(List selectedDays) { final days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - List selectedDaysStr = []; - for (int i = 0; i < selectedDays.length; i++) { + final selectedDaysStr = []; + for (var i = 0; i < selectedDays.length; i++) { if (selectedDays[i]) { selectedDaysStr.add(days[i]); } diff --git a/lib/pages/device_managment/water_leak/bloc/water_leak_bloc.dart b/lib/pages/device_managment/water_leak/bloc/water_leak_bloc.dart index 6d3ca9a6..ee1390a7 100644 --- a/lib/pages/device_managment/water_leak/bloc/water_leak_bloc.dart +++ b/lib/pages/device_managment/water_leak/bloc/water_leak_bloc.dart @@ -1,13 +1,11 @@ +import 'dart:async'; + import 'package:bloc/bloc.dart'; import 'package:firebase_database/firebase_database.dart'; -import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart'; import 'package:syncrow_web/pages/device_managment/water_leak/bloc/water_leak_event.dart'; import 'package:syncrow_web/pages/device_managment/water_leak/bloc/water_leak_state.dart'; import 'package:syncrow_web/pages/device_managment/water_leak/model/water_leak_status_model.dart'; - -import 'dart:async'; - import 'package:syncrow_web/services/devices_mang_api.dart'; class WaterLeakBloc extends Bloc { @@ -39,17 +37,15 @@ class WaterLeakBloc extends Bloc { } } - _listenToChanges() { + void _listenToChanges() { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$deviceId'); - Stream stream = ref.onValue; + final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + final stream = ref.onValue; stream.listen((DatabaseEvent event) { - Map usersMap = - event.snapshot.value as Map; + final usersMap = event.snapshot.value! as Map; - List statusList = []; + final statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); @@ -195,9 +191,8 @@ class WaterLeakBloc extends Bloc { .subtract(const Duration(days: 30)) .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final DeviceReport records = - await DevicesManagementApi.getDeviceReportsByDate( - event.deviceId, event.code, from.toString(), to.toString()); + final records = await DevicesManagementApi.getDeviceReportsByDate( + event.deviceId, event.code, from.toString(), to.toString()); emit(WaterLeakReportsLoadedState(records)); } catch (e) { emit(WaterLeakReportsFailedState(e.toString())); diff --git a/lib/pages/device_managment/water_leak/view/water_leak_batch_control_view.dart b/lib/pages/device_managment/water_leak/view/water_leak_batch_control_view.dart index 1eb795e5..30b077bf 100644 --- a/lib/pages/device_managment/water_leak/view/water_leak_batch_control_view.dart +++ b/lib/pages/device_managment/water_leak/view/water_leak_batch_control_view.dart @@ -10,16 +10,17 @@ import 'package:syncrow_web/pages/device_managment/water_leak/bloc/water_leak_st import 'package:syncrow_web/pages/device_managment/water_leak/model/water_leak_status_model.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class WaterLeakBatchControlView extends StatelessWidget with HelperResponsiveLayout { +class WaterLeakBatchControlView extends StatelessWidget + with HelperResponsiveLayout { final List deviceIds; - const WaterLeakBatchControlView({Key? key, required this.deviceIds}) : super(key: key); + const WaterLeakBatchControlView({super.key, required this.deviceIds}); @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => - WaterLeakBloc(deviceIds.first)..add(FetchWaterLeakBatchStatusEvent(deviceIds)), + create: (context) => WaterLeakBloc(deviceIds.first) + ..add(FetchWaterLeakBatchStatusEvent(deviceIds)), child: BlocBuilder( builder: (context, state) { if (state is WaterLeakLoadingState) { @@ -36,7 +37,8 @@ class WaterLeakBatchControlView extends StatelessWidget with HelperResponsiveLay ); } - Widget _buildStatusControls(BuildContext context, WaterLeakStatusModel status) { + Widget _buildStatusControls( + BuildContext context, WaterLeakStatusModel status) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ diff --git a/lib/pages/device_managment/water_leak/view/water_leak_control_view.dart b/lib/pages/device_managment/water_leak/view/water_leak_control_view.dart index 6b9dc564..51fd5880 100644 --- a/lib/pages/device_managment/water_leak/view/water_leak_control_view.dart +++ b/lib/pages/device_managment/water_leak/view/water_leak_control_view.dart @@ -13,7 +13,7 @@ import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_la class WaterLeakView extends StatelessWidget with HelperResponsiveLayout { final String deviceId; - const WaterLeakView({Key? key, required this.deviceId}) : super(key: key); + const WaterLeakView({super.key, required this.deviceId}); @override Widget build(BuildContext context) { @@ -21,7 +21,8 @@ class WaterLeakView extends StatelessWidget with HelperResponsiveLayout { final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); return BlocProvider( - create: (context) => WaterLeakBloc(deviceId)..add(FetchWaterLeakStatusEvent(deviceId)), + create: (context) => + WaterLeakBloc(deviceId)..add(FetchWaterLeakStatusEvent(deviceId)), child: BlocBuilder( builder: (context, state) { if (state is WaterLeakLoadingState) { @@ -44,21 +45,31 @@ class WaterLeakView extends StatelessWidget with HelperResponsiveLayout { children: [ IconNameStatusContainer( isFullIcon: false, - name: state.status.watersensorState == 'normal' ? 'Normal' : 'Leak Detection', - icon: state.status.watersensorState == 'normal' ? Assets.waterLeakNormal : Assets.waterLeakDetected, + name: state.status.watersensorState == 'normal' + ? 'Normal' + : 'Leak Detection', + icon: state.status.watersensorState == 'normal' + ? Assets.waterLeakNormal + : Assets.waterLeakDetected, onTap: () {}, status: state.status.watersensorState == 'normal', - textColor: state.status.watersensorState == 'normal' ? ColorsManager.blackColor : ColorsManager.red, + textColor: state.status.watersensorState == 'normal' + ? ColorsManager.blackColor + : ColorsManager.red, ), IconNameStatusContainer( isFullIcon: false, name: 'Records', icon: Assets.records, onTap: () { - context.read().add(FetchWaterLeakReportsEvent( + context + .read() + .add(FetchWaterLeakReportsEvent( deviceId: deviceId, code: 'watersensor_state', - from: DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch, + from: DateTime.now() + .subtract(const Duration(days: 30)) + .millisecondsSinceEpoch, to: DateTime.now().millisecondsSinceEpoch, )); }, @@ -98,7 +109,9 @@ class WaterLeakView extends StatelessWidget with HelperResponsiveLayout { waterLeak: true, onRowTap: (index) {}, onClose: () { - context.read().add(FetchWaterLeakStatusEvent(deviceId)); + context + .read() + .add(FetchWaterLeakStatusEvent(deviceId)); }, ); } else if (state is WaterLeakReportsFailedState) { diff --git a/lib/pages/device_managment/water_leak/widgets/water_leak_notifi_dialog.dart b/lib/pages/device_managment/water_leak/widgets/water_leak_notifi_dialog.dart index 0e3e325f..924973c5 100644 --- a/lib/pages/device_managment/water_leak/widgets/water_leak_notifi_dialog.dart +++ b/lib/pages/device_managment/water_leak/widgets/water_leak_notifi_dialog.dart @@ -6,7 +6,8 @@ class WaterLeakNotificationDialog extends StatefulWidget { const WaterLeakNotificationDialog({super.key}); @override - State createState() => _NotificationDialogState(); + State createState() => + _NotificationDialogState(); } class _NotificationDialogState extends State { @@ -53,7 +54,7 @@ class _NotificationDialogState extends State { ), ), child: IconButton( - padding: EdgeInsets.all(1), + padding: const EdgeInsets.all(1), icon: const Icon( Icons.close, color: Colors.grey, diff --git a/lib/pages/home/bloc/home_bloc.dart b/lib/pages/home/bloc/home_bloc.dart index ad6ed4d8..d422f318 100644 --- a/lib/pages/home/bloc/home_bloc.dart +++ b/lib/pages/home/bloc/home_bloc.dart @@ -13,14 +13,13 @@ import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/services/home_api.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart'; -import 'package:syncrow_web/utils/navigation_service.dart'; class HomeBloc extends Bloc { UserModel? user; String terms = ''; String policy = ''; - HomeBloc() : super((HomeInitial())) { + HomeBloc() : super(HomeInitial()) { // on(_createNode); on(_fetchUserInfo); on(_fetchTerms); @@ -30,13 +29,12 @@ class HomeBloc extends Bloc { Future _fetchUserInfo(FetchUserInfo event, Emitter emit) async { try { - var uuid = + final uuid = await const FlutterSecureStorage().read(key: UserModel.userUuidKey); user = await HomeApi().fetchUserInfo(uuid); if (user != null && user!.project != null) { await ProjectManager.setProjectUUID(user!.project!.uuid); - } add(FetchTermEvent()); add(FetchPolicyEvent()); @@ -63,7 +61,7 @@ class HomeBloc extends Bloc { policy = await HomeApi().fetchPolicy(); emit(HomeInitial()); } catch (e) { - debugPrint("Error fetching policy: $e"); + debugPrint('Error fetching policy: $e'); return; } } @@ -72,7 +70,7 @@ class HomeBloc extends Bloc { ConfirmUserAgreementEvent event, Emitter emit) async { try { emit(LoadingHome()); - var uuid = + final uuid = await const FlutterSecureStorage().read(key: UserModel.userUuidKey); policy = await HomeApi().confirmUserAgreements(uuid); emit(PolicyAgreement()); @@ -146,21 +144,21 @@ class HomeBloc extends Bloc { // icon: Assets.energyIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withOpacity(0.2), + // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), // ), // HomeItemModel( // title: 'Integrations', // icon: Assets.integrationsIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withOpacity(0.2), + // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), // ), // HomeItemModel( // title: 'Asset', // icon: Assets.assetIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withOpacity(0.2), + // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), // ), ]; } diff --git a/lib/pages/home/view/agreement_and_privacy_dialog.dart b/lib/pages/home/view/agreement_and_privacy_dialog.dart index 6b72c300..61e8a150 100644 --- a/lib/pages/home/view/agreement_and_privacy_dialog.dart +++ b/lib/pages/home/view/agreement_and_privacy_dialog.dart @@ -1,9 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:go_router/go_router.dart'; import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -89,7 +87,7 @@ class _AgreementAndPrivacyDialogState extends State { controller: _scrollController, padding: const EdgeInsets.all(25), child: Html( - data: "$_dialogContent $staticText", + data: '$_dialogContent $staticText', onLinkTap: (url, attributes, element) async { if (url != null) { final uri = Uri.parse(url); @@ -97,10 +95,10 @@ class _AgreementAndPrivacyDialogState extends State { } }, style: { - "body": Style( + 'body': Style( fontSize: FontSize(14), color: Colors.black87, - lineHeight: LineHeight(1.5), + lineHeight: const LineHeight(1.5), ), }, ), @@ -110,7 +108,7 @@ class _AgreementAndPrivacyDialogState extends State { } Widget _buildActionButton() { - final String buttonText = _currentPage == 2 ? "I Agree" : "Next"; + final buttonText = _currentPage == 2 ? 'I Agree' : 'Next'; return InkWell( onTap: _isAtEnd @@ -167,7 +165,7 @@ class _AgreementAndPrivacyDialogState extends State { AuthBloc.logout(context); context.go(RoutesConst.auth); }, - child: const Text("Cancel"), + child: const Text('Cancel'), ), _buildActionButton(), ], diff --git a/lib/pages/home/view/home_page.dart b/lib/pages/home/view/home_page.dart index 9159011f..9652f0b6 100644 --- a/lib/pages/home/view/home_page.dart +++ b/lib/pages/home/view/home_page.dart @@ -11,7 +11,7 @@ class HomePage extends StatelessWidget with HelperResponsiveLayout { final isSmallScreen = isSmallScreenSize(context); final isMediumScreen = isMediumScreenSize(context); return isSmallScreen || isMediumScreen - ? HomeMobilePage() + ? const HomeMobilePage() : const HomeWebPage(); } } diff --git a/lib/pages/home/view/home_page_mobile.dart b/lib/pages/home/view/home_page_mobile.dart index ad019ea8..2b1d502b 100644 --- a/lib/pages/home/view/home_page_mobile.dart +++ b/lib/pages/home/view/home_page_mobile.dart @@ -4,16 +4,15 @@ import 'package:flutter_svg/svg.dart'; import 'package:syncrow_web/pages/home/bloc/home_bloc.dart'; import 'package:syncrow_web/pages/home/bloc/home_state.dart'; import 'package:syncrow_web/pages/home/view/home_card.dart'; -import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/web_layout/web_scaffold.dart'; class HomeMobilePage extends StatelessWidget { - HomeMobilePage({super.key}); + const HomeMobilePage({super.key}); @override Widget build(BuildContext context) { - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; return PopScope( canPop: false, onPopInvoked: (didPop) => false, @@ -41,7 +40,8 @@ class HomeMobilePage extends StatelessWidget { SizedBox(height: size.height * 0.05), const Text( 'ACCESS YOUR APPS', - style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700), + style: + TextStyle(fontSize: 20, fontWeight: FontWeight.w700), ), const SizedBox(height: 30), Expanded( @@ -63,8 +63,8 @@ class HomeMobilePage extends StatelessWidget { index: index, active: true, color: homeBloc.homeItems[index].color, - name: homeBloc.homeItems[index].title!, - img: homeBloc.homeItems[index].icon!, + name: homeBloc.homeItems[index].title!, + img: homeBloc.homeItems[index].icon!, onTap: () => homeBloc.homeItems[index].onPress(context), ); diff --git a/lib/pages/home/view/home_page_web.dart b/lib/pages/home/view/home_page_web.dart index 53a994f6..5adb5a12 100644 --- a/lib/pages/home/view/home_page_web.dart +++ b/lib/pages/home/view/home_page_web.dart @@ -20,11 +20,9 @@ class _HomeWebPageState extends State { // Flag to track whether the dialog is already shown. bool _dialogShown = false; - - @override Widget build(BuildContext context) { - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; final homeBloc = BlocProvider.of(context); return PopScope( diff --git a/lib/pages/home/view/tree_page.dart b/lib/pages/home/view/tree_page.dart index 9458e361..f8dc9c33 100644 --- a/lib/pages/home/view/tree_page.dart +++ b/lib/pages/home/view/tree_page.dart @@ -144,7 +144,7 @@ // borderRadius: BorderRadius.circular(10.0), // boxShadow: [ // BoxShadow( -// color: Colors.grey.withOpacity(0.5), +// color: Colors.grey.withValues(alpha:0.5), // spreadRadius: 2, // blurRadius: 5, // offset: Offset(0, 3), // changes position of shadow diff --git a/lib/pages/roles_and_permission/bloc/roles_permission_bloc.dart b/lib/pages/roles_and_permission/bloc/roles_permission_bloc.dart index 4f4988b3..15787fd7 100644 --- a/lib/pages/roles_and_permission/bloc/roles_permission_bloc.dart +++ b/lib/pages/roles_and_permission/bloc/roles_permission_bloc.dart @@ -29,7 +29,7 @@ class RolesPermissionBloc bool tapSelect = true; - changeTapSelected( + void changeTapSelected( ChangeTapSelected event, Emitter emit) { try { emit(RolesLoadingState()); diff --git a/lib/pages/roles_and_permission/model/role_type_model.dart b/lib/pages/roles_and_permission/model/role_type_model.dart index 16b24ec5..61a52f9d 100644 --- a/lib/pages/roles_and_permission/model/role_type_model.dart +++ b/lib/pages/roles_and_permission/model/role_type_model.dart @@ -16,7 +16,7 @@ class RoleTypeModel { uuid: json['uuid'], createdAt: json['createdAt'], updatedAt: json['updatedAt'], - type: json['type'].toString().toLowerCase().replaceAll("_", " "), + type: json['type'].toString().toLowerCase().replaceAll('_', ' '), ); } } diff --git a/lib/pages/roles_and_permission/model/roles_user_model.dart b/lib/pages/roles_and_permission/model/roles_user_model.dart index e502370a..98049bcb 100644 --- a/lib/pages/roles_and_permission/model/roles_user_model.dart +++ b/lib/pages/roles_and_permission/model/roles_user_model.dart @@ -36,14 +36,14 @@ class RolesUserModel { email: json['email'], firstName: json['firstName'], lastName: json['lastName'], - roleType: json['roleType'].toString().toLowerCase().replaceAll("_", " "), + roleType: json['roleType'].toString().toLowerCase().replaceAll('_', ' '), status: json['status'], isEnabled: json['isEnabled'], invitedBy: - json['invitedBy'].toString().toLowerCase().replaceAll("_", " "), + json['invitedBy'].toString().toLowerCase().replaceAll('_', ' '), phoneNumber: json['phoneNumber'], - jobTitle: json['jobTitle'] == null || json['jobTitle'] == " " - ? "_" + jobTitle: json['jobTitle'] == null || json['jobTitle'] == ' ' + ? '_' : json['jobTitle'], createdDate: json['createdDate'], createdTime: json['createdTime'], diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart index 54187152..00e8605d 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart @@ -1,4 +1,3 @@ -import 'package:bloc/bloc.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; @@ -11,7 +10,6 @@ import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialo import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; import 'package:syncrow_web/services/space_mana_api.dart'; import 'package:syncrow_web/services/user_permission.dart'; @@ -66,7 +64,7 @@ class UsersBloc extends Bloc { void isCompleteSpacesFun( CheckSpacesStepStatus event, Emitter emit) { emit(UsersLoadingState()); - var spaceBloc = + final spaceBloc = NavigationService.navigatorKey.currentContext!.read(); isCompleteSpaces = spaceBloc.state.selectedCommunities.isNotEmpty; @@ -83,26 +81,25 @@ class UsersBloc extends Bloc { String communityUuid) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - return await CommunitySpaceManagementApi() + return CommunitySpaceManagementApi() .getSpaceHierarchy(communityUuid, projectUuid); } List updatedCommunities = []; List spacesNodes = []; List communityIds = []; - _onLoadCommunityAndSpaces( + Future _onLoadCommunityAndSpaces( LoadCommunityAndSpacesEvent event, Emitter emit) async { try { emit(UsersLoadingState()); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - List communities = + final communities = await CommunitySpaceManagementApi().fetchCommunities(projectUuid); communityIds = communities.map((community) => community.uuid).toList(); updatedCommunities = await Future.wait( communities.map((community) async { - List spaces = - await _fetchSpacesForCommunity(community.uuid); + final spaces = await _fetchSpacesForCommunity(community.uuid); spacesNodes = _buildTreeNodes(spaces); return TreeNode( uuid: community.uuid, @@ -129,7 +126,7 @@ class UsersBloc extends Bloc { // Build tree nodes from your data model. List _buildTreeNodes(List spaces) { return spaces.map((space) { - List childNodes = + final childNodes = space.children.isNotEmpty ? _buildTreeNodes(space.children) : []; return TreeNode( uuid: space.uuid!, @@ -170,7 +167,7 @@ class UsersBloc extends Bloc { _clearHighlights(updatedCommunities); } else { // Start with a fresh clone of the original tree. - List freshClone = _cloneNodes(originalCommunities); + final freshClone = _cloneNodes(originalCommunities); _searchAndHighlightNodes(freshClone, event.searchTerm!); @@ -180,7 +177,7 @@ class UsersBloc extends Bloc { } void _clearHighlights(List nodes) { - for (var node in nodes) { + for (final node in nodes) { node.isHighlighted = false; if (node.children.isNotEmpty) { _clearHighlights(node.children); @@ -189,11 +186,11 @@ class UsersBloc extends Bloc { } bool _searchAndHighlightNodes(List nodes, String searchTerm) { - bool anyMatch = false; - for (var node in nodes) { - bool isMatch = + var anyMatch = false; + for (final node in nodes) { + final isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - bool childMatch = _searchAndHighlightNodes(node.children, searchTerm); + final childMatch = _searchAndHighlightNodes(node.children, searchTerm); node.isHighlighted = isMatch || childMatch; anyMatch = anyMatch || node.isHighlighted; @@ -202,11 +199,11 @@ class UsersBloc extends Bloc { } List _filterNodes(List nodes, String searchTerm) { - List filteredNodes = []; - for (var node in nodes) { - bool isMatch = + final filteredNodes = []; + for (final node in nodes) { + final isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - List filteredChildren = _filterNodes(node.children, searchTerm); + final filteredChildren = _filterNodes(node.children, searchTerm); if (isMatch || filteredChildren.isNotEmpty) { node.isHighlighted = isMatch; node.children = filteredChildren; @@ -289,8 +286,8 @@ class UsersBloc extends Bloc { List selectedIds = []; List getSelectedIds(List nodes) { - List selectedIds = []; - for (var node in nodes) { + final selectedIds = []; + for (final node in nodes) { if (node.isChecked) { selectedIds.add(node.uuid); } @@ -304,7 +301,8 @@ class UsersBloc extends Bloc { List roles = []; List permissions = []; - _getRolePermission(RoleEvent event, Emitter emit) async { + Future _getRolePermission( + RoleEvent event, Emitter emit) async { try { emit(UsersLoadingState()); roles = await UserPermissionApi().fetchRoles(); @@ -314,11 +312,12 @@ class UsersBloc extends Bloc { } } - _getPermissions(PermissionEvent event, Emitter emit) async { + Future _getPermissions( + PermissionEvent event, Emitter emit) async { try { emit(UsersLoadingState()); permissions = await UserPermissionApi().fetchPermission( - event.roleUuid == "" ? roles.first.uuid : event.roleUuid); + event.roleUuid == '' ? roles.first.uuid : event.roleUuid); roleSelected = event.roleUuid!; emit(RolePermissionInitial()); } catch (e) { @@ -327,18 +326,19 @@ class UsersBloc extends Bloc { } bool _searchRolePermission(List nodes, String searchTerm) { - bool anyMatch = false; - for (var node in nodes) { - bool isMatch = + var anyMatch = false; + for (final node in nodes) { + final isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - bool childMatch = _searchRolePermission(node.subOptions, searchTerm); + final childMatch = _searchRolePermission(node.subOptions, searchTerm); node.isHighlighted = isMatch || childMatch; anyMatch = anyMatch || node.isHighlighted; } return anyMatch; } - void _sendInvitUser(SendInviteUsers event, Emitter emit) async { + Future _sendInvitUser( + SendInviteUsers event, Emitter emit) async { try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -346,10 +346,10 @@ class UsersBloc extends Bloc { // List selectedIds = // getSelectedIds(updatedCommunities).where((id) => !communityIds.contains(id)).toList(); - List selectedSpacesId = getSelectedSpacesIds(); + final selectedSpacesId = getSelectedSpacesIds(); // List selectedIds = getSelectedIds(updatedCommunities); - bool res = await UserPermissionApi().sendInviteUser( + final res = await UserPermissionApi().sendInviteUser( email: emailController.text, firstName: firstNameController.text, jobTitle: jobTitleController.text, @@ -363,9 +363,9 @@ class UsersBloc extends Bloc { showCustomDialog( barrierDismissible: false, context: event.context, - message: "The invite was sent successfully.", + message: 'The invite was sent successfully.', iconPath: Assets.deviceNoteIcon, - title: "Invite Success", + title: 'Invite Success', dialogHeight: MediaQuery.of(event.context).size.height * 0.3, actions: [ TextButton( @@ -382,27 +382,28 @@ class UsersBloc extends Bloc { } emit(SaveState()); } catch (e) { - emit(ErrorState('Failed to send invite: ${e.toString()}')); + emit(ErrorState('Failed to send invite: $e')); } } List getSelectedSpacesIds() { - List selectedSpacesId = []; - var spaceBloc = + final selectedSpacesId = []; + final spaceBloc = NavigationService.navigatorKey.currentContext!.read(); - for (var community in spaceBloc.state.selectedCommunities) { + for (final community in spaceBloc.state.selectedCommunities) { selectedSpacesId .addAll(spaceBloc.state.selectedCommunityAndSpaces[community] ?? []); } return selectedSpacesId; } - _editInviteUser(EditInviteUsers event, Emitter emit) async { + Future _editInviteUser( + EditInviteUsers event, Emitter emit) async { try { emit(UsersLoadingState()); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - bool res = await UserPermissionApi().editInviteUser( + final res = await UserPermissionApi().editInviteUser( userId: event.userId, firstName: firstNameController.text, jobTitle: jobTitleController.text, @@ -415,9 +416,9 @@ class UsersBloc extends Bloc { showCustomDialog( barrierDismissible: false, context: event.context, - message: "The invite was sent successfully.", + message: 'The invite was sent successfully.', iconPath: Assets.deviceNoteIcon, - title: "Invite Success", + title: 'Invite Success', dialogHeight: MediaQuery.of(event.context).size.height * 0.3, actions: [ TextButton( @@ -436,7 +437,7 @@ class UsersBloc extends Bloc { } emit(SaveState()); } catch (e) { - emit(ErrorState('Failed to send invite: ${e.toString()}')); + emit(ErrorState('Failed to send invite: $e')); } } @@ -455,7 +456,7 @@ class UsersBloc extends Bloc { Future checkEmail( CheckEmailEvent event, Emitter emit) async { emit(UsersLoadingState()); - String? res = await UserPermissionApi().checkEmail( + final res = await UserPermissionApi().checkEmail( emailController.text, ); checkEmailValid = res!; @@ -469,8 +470,8 @@ class UsersBloc extends Bloc { final emailRegex = RegExp( r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', ); - bool isEmailValid = emailRegex.hasMatch(emailController.text); - bool isEmailServerValid = checkEmailValid == 'Valid email'; + final isEmailValid = emailRegex.hasMatch(emailController.text); + final isEmailServerValid = checkEmailValid == 'Valid email'; isCompleteBasics = firstNameController.text.isNotEmpty && lastNameController.text.isNotEmpty && emailController.text.isNotEmpty && @@ -486,7 +487,7 @@ class UsersBloc extends Bloc { } void _clearHighlightsRolePermission(List nodes) { - for (var node in nodes) { + for (final node in nodes) { node.isHighlighted = false; if (node.subOptions.isNotEmpty) { _clearHighlightsRolePermission(node.subOptions); @@ -515,7 +516,7 @@ class UsersBloc extends Bloc { emit(UsersLoadingState()); try { - var spaceBloc = + final spaceBloc = NavigationService.navigatorKey.currentContext!.read(); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -533,9 +534,9 @@ class UsersBloc extends Bloc { res.roleType; res.spaces.map((space) { selectedIds.add(space.uuid); - CommunityModel community = spaceBloc.state.communityList + final community = spaceBloc.state.communityList .firstWhere((item) => item.uuid == space.communityUuid); - spaceBloc.add(OnSpaceSelected(community, space.uuid, [])); + spaceBloc.add(OnSpaceSelected(community, space.uuid, const [])); }).toList(); // if (updatedCommunities.isNotEmpty) { @@ -548,7 +549,7 @@ class UsersBloc extends Bloc { final roleId = roles .firstWhere((element) => element.type == - res.roleType.toString().toLowerCase().replaceAll("_", " ")) + res.roleType.toLowerCase().replaceAll('_', ' ')) .uuid; debugPrint('Role ID: $roleId'); roleSelected = roleId; @@ -604,14 +605,14 @@ class UsersBloc extends Bloc { } void _updateChildrenCheckStatus(TreeNode node, bool isChecked) { - for (var child in node.children) { + for (final child in node.children) { child.isChecked = isChecked; _updateChildrenCheckStatus(child, isChecked); } } void _updateParentCheckStatus(TreeNode node) { - TreeNode? parent = _findParent(updatedCommunities, node); + final parent = _findParent(updatedCommunities, node); if (parent != null) { parent.isChecked = _areAllChildrenChecked(parent); _updateParentCheckStatus(parent); @@ -626,7 +627,7 @@ class UsersBloc extends Bloc { } TreeNode? _findParent(List nodes, TreeNode target) { - for (var node in nodes) { + for (final node in nodes) { if (node.children.contains(target)) { return node; } diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart index 2e82168c..b7dbebd6 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart @@ -48,7 +48,7 @@ class RoleEvent extends UsersEvent { class PermissionEvent extends UsersEvent { final String? roleUuid; - const PermissionEvent({this.roleUuid = ""}); + const PermissionEvent({this.roleUuid = ''}); @override List get props => [roleUuid]; } diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart index 4141ccdd..2769fc09 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart @@ -17,7 +17,7 @@ class PermissionOption { return PermissionOption( id: json['id'] ?? '', title: json['title'] != null - ? json['title'].toString().toLowerCase().replaceAll("_", " ") + ? json['title'].toString().toLowerCase().replaceAll('_', ' ') : '', isChecked: json['isChecked'] ?? false, isHighlighted: json['isHighlighted'] ?? false, diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart index a5e622dc..6f715b5b 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart @@ -14,4 +14,4 @@ class TreeNode { this.isExpanded = false, this.children = const [], }); -} \ No newline at end of file +} diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/add_user_dialog.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/add_user_dialog.dart index 44ba81ff..7d39858c 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/add_user_dialog.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/add_user_dialog.dart @@ -29,12 +29,13 @@ class _AddNewUserDialogState extends State { child: BlocConsumer( listener: (context, state) {}, builder: (context, state) { - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); return Dialog( child: Container( decoration: const BoxDecoration( - color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20))), + color: Colors.white, + borderRadius: BorderRadius.all(Radius.circular(20))), width: 900, child: Column( children: [ @@ -43,7 +44,7 @@ class _AddNewUserDialogState extends State { padding: EdgeInsets.all(8.0), child: SizedBox( child: Text( - "Add New User", + 'Add New User', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w700, @@ -61,9 +62,10 @@ class _AddNewUserDialogState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildStep1Indicator(1, "Basics", _blocRole), - _buildStep2Indicator(2, "Spaces", _blocRole), - _buildStep3Indicator(3, "Role & Permissions", _blocRole), + _buildStep1Indicator(1, 'Basics', blocRole), + _buildStep2Indicator(2, 'Spaces', blocRole), + _buildStep3Indicator( + 3, 'Role & Permissions', blocRole), ], ), ), @@ -101,31 +103,35 @@ class _AddNewUserDialogState extends State { onTap: () { Navigator.of(context).pop(); }, - child: const Text("Cancel"), + child: const Text('Cancel'), ), InkWell( onTap: () { - _blocRole.add(const CheckEmailEvent()); + blocRole.add(const CheckEmailEvent()); setState(() { if (currentStep < 3) { currentStep++; if (currentStep == 2) { - _blocRole.add(const CheckStepStatus(isEditUser: false)); + blocRole.add(const CheckStepStatus( + isEditUser: false)); } else if (currentStep == 3) { - _blocRole.add(const CheckSpacesStepStatus()); + blocRole.add(const CheckSpacesStepStatus()); } } else { - _blocRole.add(SendInviteUsers(context: context)); + blocRole + .add(SendInviteUsers(context: context)); } }); }, child: Text( - currentStep < 3 ? "Next" : "Save", + currentStep < 3 ? 'Next' : 'Save', style: TextStyle( - color: (_blocRole.isCompleteSpaces == false || - _blocRole.isCompleteBasics == false || - _blocRole.isCompleteRolePermissions == false) && + color: (blocRole.isCompleteSpaces == false || + blocRole.isCompleteBasics == + false || + blocRole.isCompleteRolePermissions == + false) && currentStep == 3 ? ColorsManager.grayColor : ColorsManager.secondaryColor), @@ -196,8 +202,12 @@ class _AddNewUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], @@ -260,8 +270,12 @@ class _AddNewUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], @@ -291,7 +305,7 @@ class _AddNewUserDialogState extends State { currentStep = step; step3 = step; bloc.add(const CheckSpacesStepStatus()); - bloc.add(CheckStepStatus(isEditUser: false)); + bloc.add(const CheckStepStatus(isEditUser: false)); }); }, child: Column( @@ -318,8 +332,12 @@ class _AddNewUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/basics_view.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/basics_view.dart index fa04c051..e5933995 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/basics_view.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/basics_view.dart @@ -15,12 +15,12 @@ class BasicsView extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder(builder: (context, state) { - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); if (state is BasicsStepInvalidState) { - _blocRole.formKey.currentState?.validate(); + blocRole.formKey.currentState?.validate(); } return Form( - key: _blocRole.formKey, + key: blocRole.formKey, child: ListView( shrinkWrap: true, children: [ @@ -57,7 +57,7 @@ class BasicsView extends StatelessWidget { child: Row( children: [ const Text( - " * ", + ' * ', style: TextStyle( color: ColorsManager.red, fontWeight: FontWeight.w900, @@ -84,9 +84,9 @@ class BasicsView extends StatelessWidget { // _blocRole.add(const ValidateBasicsStep()); // }); // }, - controller: _blocRole.firstNameController, + controller: blocRole.firstNameController, decoration: inputTextFormDeco( - hintText: "Enter first name", + hintText: 'Enter first name', ).copyWith( hintStyle: context.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, @@ -117,7 +117,7 @@ class BasicsView extends StatelessWidget { child: Row( children: [ const Text( - " * ", + ' * ', style: TextStyle( color: ColorsManager.red, fontWeight: FontWeight.w900, @@ -140,10 +140,10 @@ class BasicsView extends StatelessWidget { // _blocRole.add(ValidateBasicsStep()); // }); // }, - controller: _blocRole.lastNameController, + controller: blocRole.lastNameController, style: const TextStyle(color: Colors.black), decoration: - inputTextFormDeco(hintText: "Enter last name") + inputTextFormDeco(hintText: 'Enter last name') .copyWith( hintStyle: context.textTheme.bodyMedium ?.copyWith( @@ -172,7 +172,7 @@ class BasicsView extends StatelessWidget { child: Row( children: [ const Text( - " * ", + ' * ', style: TextStyle( color: ColorsManager.red, fontWeight: FontWeight.w900, @@ -199,9 +199,9 @@ class BasicsView extends StatelessWidget { // _blocRole.add(ValidateBasicsStep()); // }); // }, - controller: _blocRole.emailController, + controller: blocRole.emailController, style: const TextStyle(color: ColorsManager.blackColor), - decoration: inputTextFormDeco(hintText: "name@example.com") + decoration: inputTextFormDeco(hintText: 'name@example.com') .copyWith( hintStyle: context.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, @@ -218,9 +218,10 @@ class BasicsView extends StatelessWidget { if (!emailRegex.hasMatch(value)) { return 'Enter a valid Email Address'; } - if (_blocRole.checkEmailValid != "Valid email") { - return _blocRole.checkEmailValid; + if (blocRole.checkEmailValid != 'Valid email') { + return blocRole.checkEmailValid; } + return null; // return null; }, ), @@ -254,7 +255,7 @@ class BasicsView extends StatelessWidget { const TextStyle(color: ColorsManager.blackColor), textInputAction: TextInputAction.done, decoration: inputTextFormDeco( - hintText: "05x xxx xxxx", + hintText: '05x xxx xxxx', ).copyWith( hintStyle: context.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, @@ -264,32 +265,32 @@ class BasicsView extends StatelessWidget { initialCountryCode: 'AE', countries: const [ Country( - name: "United Arab Emirates", + name: 'United Arab Emirates', nameTranslations: { - "en": "United Arab Emirates", - "ar": "الإمارات العربية المتحدة", + 'en': 'United Arab Emirates', + 'ar': 'الإمارات العربية المتحدة', }, - flag: "🇦🇪", - code: "AE", - dialCode: "971", + flag: '🇦🇪', + code: 'AE', + dialCode: '971', minLength: 9, maxLength: 9, ), Country( - name: "Saudi Arabia", + name: 'Saudi Arabia', nameTranslations: { - "en": "Saudi Arabia", - "ar": "السعودية", + 'en': 'Saudi Arabia', + 'ar': 'السعودية', }, - flag: "🇸🇦", - code: "SA", - dialCode: "966", + flag: '🇸🇦', + code: 'SA', + dialCode: '966', minLength: 9, maxLength: 9, ), ], style: const TextStyle(color: Colors.black), - controller: _blocRole.phoneController, + controller: blocRole.phoneController, ) ], ), @@ -314,11 +315,11 @@ class BasicsView extends StatelessWidget { Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( - controller: _blocRole.jobTitleController, + controller: blocRole.jobTitleController, style: const TextStyle(color: ColorsManager.blackColor), decoration: inputTextFormDeco( - hintText: "Job Title (Optional)") + hintText: 'Job Title (Optional)') .copyWith( hintStyle: context.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/build_tree_view.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/build_tree_view.dart index cbe15ecd..789e88e2 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/build_tree_view.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/build_tree_view.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart'; @@ -19,7 +18,7 @@ class TreeView extends StatelessWidget { @override Widget build(BuildContext context) { - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); return BlocProvider( create: (_) => UsersBloc(), // ..add(const LoadCommunityAndSpacesEvent()), @@ -34,7 +33,7 @@ class TreeView extends StatelessWidget { return const Center(child: CircularProgressIndicator()); } return SingleChildScrollView( - child: _buildTree(_blocRole.updatedCommunities, _blocRole), + child: _buildTree(blocRole.updatedCommunities, blocRole), ); }, ), @@ -48,7 +47,7 @@ class TreeView extends StatelessWidget { }) { return Column( children: nodes.map((node) { - return Container( + return ColoredBox( color: node.isHighlighted ? Colors.blue.shade50 : Colors.transparent, child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/delete_user_dialog.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/delete_user_dialog.dart index 10e8c273..fd6666c5 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/delete_user_dialog.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/delete_user_dialog.dart @@ -1,10 +1,9 @@ import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; import 'package:syncrow_web/utils/color_manager.dart'; class DeleteUserDialog extends StatefulWidget { final Function()? onTapDelete; - DeleteUserDialog({super.key, this.onTapDelete}); + const DeleteUserDialog({super.key, this.onTapDelete}); @override _DeleteUserDialogState createState() => _DeleteUserDialogState(); @@ -35,7 +34,7 @@ class _DeleteUserDialogState extends State { padding: EdgeInsets.all(8.0), child: SizedBox( child: Text( - "Delete User", + 'Delete User', style: TextStyle( color: ColorsManager.red, fontSize: 18, @@ -54,7 +53,7 @@ class _DeleteUserDialogState extends State { child: Padding( padding: EdgeInsets.only(left: 25, right: 25, top: 10, bottom: 10), child: Text( - "Are you sure you want to delete this user?", + 'Are you sure you want to delete this user?', textAlign: TextAlign.center, ), )), diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/edit_user_dialog.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/edit_user_dialog.dart index 071de067..50ae1d7c 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/edit_user_dialog.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/edit_user_dialog.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart'; @@ -31,15 +30,17 @@ class _EditUserDialogState extends State { ..add(GetUserByIdEvent(uuid: widget.userId)), child: BlocConsumer(listener: (context, state) { if (state is SpacesLoadedState) { - BlocProvider.of(context).add(GetUserByIdEvent(uuid: widget.userId)); + BlocProvider.of(context) + .add(GetUserByIdEvent(uuid: widget.userId)); } }, builder: (context, state) { - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); return Dialog( child: Container( decoration: const BoxDecoration( - color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20))), + color: Colors.white, + borderRadius: BorderRadius.all(Radius.circular(20))), width: 900, child: Column( children: [ @@ -48,7 +49,7 @@ class _EditUserDialogState extends State { padding: EdgeInsets.all(8.0), child: SizedBox( child: Text( - "Edit User", + 'Edit User', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w700, @@ -66,9 +67,10 @@ class _EditUserDialogState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildStep1Indicator(1, "Basics", _blocRole), - _buildStep2Indicator(2, "Spaces", _blocRole), - _buildStep3Indicator(3, "Role & Permissions", _blocRole), + _buildStep1Indicator(1, 'Basics', blocRole), + _buildStep2Indicator(2, 'Spaces', blocRole), + _buildStep3Indicator( + 3, 'Role & Permissions', blocRole), ], ), ), @@ -106,7 +108,7 @@ class _EditUserDialogState extends State { onTap: () { Navigator.of(context).pop(); }, - child: const Text("Cancel"), + child: const Text('Cancel'), ), InkWell( onTap: () { @@ -116,22 +118,24 @@ class _EditUserDialogState extends State { if (currentStep < 3) { currentStep++; if (currentStep == 2) { - _blocRole.add(CheckStepStatus(isEditUser: true)); + blocRole.add( + const CheckStepStatus(isEditUser: true)); } else if (currentStep == 3) { - _blocRole.add(const CheckSpacesStepStatus()); + blocRole.add(const CheckSpacesStepStatus()); } } else { - _blocRole - .add(EditInviteUsers(context: context, userId: widget.userId!)); + blocRole.add(EditInviteUsers( + context: context, userId: widget.userId!)); } }); }, child: Text( - currentStep < 3 ? "Next" : "Save", + currentStep < 3 ? 'Next' : 'Save', style: TextStyle( - color: (_blocRole.isCompleteSpaces == false || - _blocRole.isCompleteBasics == false || - _blocRole.isCompleteRolePermissions == false) && + color: (blocRole.isCompleteSpaces == false || + blocRole.isCompleteBasics == false || + blocRole.isCompleteRolePermissions == + false) && currentStep == 3 ? ColorsManager.grayColor : ColorsManager.secondaryColor), @@ -172,7 +176,7 @@ class _EditUserDialogState extends State { bloc.add(const CheckSpacesStepStatus()); currentStep = step; Future.delayed(const Duration(milliseconds: 500), () { - bloc.add(ValidateBasicsStep()); + bloc.add(const ValidateBasicsStep()); }); }); @@ -204,8 +208,12 @@ class _EditUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], @@ -233,7 +241,7 @@ class _EditUserDialogState extends State { onTap: () { setState(() { currentStep = step; - bloc.add(CheckStepStatus(isEditUser: true)); + bloc.add(const CheckStepStatus(isEditUser: true)); if (step3 == 3) { bloc.add(const CheckRoleStepStatus()); } @@ -263,8 +271,12 @@ class _EditUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], @@ -294,7 +306,7 @@ class _EditUserDialogState extends State { currentStep = step; step3 = step; bloc.add(const CheckSpacesStepStatus()); - bloc.add(CheckStepStatus(isEditUser: true)); + bloc.add(const CheckStepStatus(isEditUser: true)); }); }, child: Column( @@ -321,8 +333,12 @@ class _EditUserDialogState extends State { label, style: TextStyle( fontSize: 16, - color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor, - fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal, + color: currentStep == step + ? ColorsManager.blackColor + : ColorsManager.greyColor, + fontWeight: currentStep == step + ? FontWeight.bold + : FontWeight.normal, ), ), ], diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/permission_management.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/permission_management.dart index aee84ed4..76bacad9 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/permission_management.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/permission_management.dart @@ -7,7 +7,7 @@ import 'package:syncrow_web/utils/extension/build_context_x.dart'; class PermissionManagement extends StatefulWidget { final UsersBloc? bloc; - const PermissionManagement({Key? key, this.bloc}) : super(key: key); + const PermissionManagement({super.key, this.bloc}); @override _PermissionManagementState createState() => _PermissionManagementState(); @@ -16,25 +16,25 @@ class PermissionManagement extends StatefulWidget { class _PermissionManagementState extends State { void toggleOptionById(String id) { setState(() { - for (var mainOption in widget.bloc!.permissions) { + for (final mainOption in widget.bloc!.permissions) { if (mainOption.id == id) { final isChecked = checkifOneOfthemChecked(mainOption) == CheckState.all; mainOption.isChecked = !isChecked; - for (var subOption in mainOption.subOptions) { + for (final subOption in mainOption.subOptions) { subOption.isChecked = !isChecked; - for (var child in subOption.subOptions) { + for (final child in subOption.subOptions) { child.isChecked = !isChecked; } } return; } - for (var subOption in mainOption.subOptions) { + for (final subOption in mainOption.subOptions) { if (subOption.id == id) { subOption.isChecked = !subOption.isChecked; - for (var child in subOption.subOptions) { + for (final child in subOption.subOptions) { child.isChecked = subOption.isChecked; } mainOption.isChecked = @@ -42,7 +42,7 @@ class _PermissionManagementState extends State { return; } - for (var child in subOption.subOptions) { + for (final child in subOption.subOptions) { if (child.id == id) { child.isChecked = !child.isChecked; subOption.isChecked = @@ -58,17 +58,17 @@ class _PermissionManagementState extends State { } CheckState checkifOneOfthemChecked(PermissionOption mainOption) { - bool allSelected = true; - bool someSelected = false; + var allSelected = true; + var someSelected = false; - for (var subOption in mainOption.subOptions) { + for (final subOption in mainOption.subOptions) { if (subOption.isChecked) { someSelected = true; } else { allSelected = false; } - for (var child in subOption.subOptions) { + for (final child in subOption.subOptions) { if (child.isChecked) { someSelected = true; } else { @@ -143,7 +143,7 @@ class _PermissionManagementState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( + ColoredBox( color: option.isHighlighted ? Colors.blue.shade50 : Colors.white, @@ -208,7 +208,7 @@ class _PermissionManagementState extends State { itemCount: subOption.subOptions.length, itemBuilder: (context, index) { final child = subOption.subOptions[index]; - return Container( + return ColoredBox( color: option.isHighlighted ? Colors.blue.shade50 : Colors.white, @@ -260,7 +260,7 @@ class _PermissionManagementState extends State { ) ], ); - }).toList(), + }), ], ); }, @@ -268,28 +268,27 @@ class _PermissionManagementState extends State { } } - - // Container( - // height: 50, - // width: 120, - // child: CheckboxListTile( - // activeColor: ColorsManager.dialogBlueTitle, - // selectedTileColor: child.isHighlighted - // ? Colors.blue.shade50 - // : Colors.white, - // dense: true, - // controlAffinity: - // ListTileControlAffinity.leading, - // title: Text( - // child.title, - // style: context.textTheme.bodyMedium?.copyWith( - // fontWeight: FontWeight.w400, - // fontSize: 12, - // color: ColorsManager.lightGreyColor), - // ), - // value: child.isChecked, - // onChanged: (value) => - // toggleOptionById(child.id), - // enabled: false, - // ), - // ), \ No newline at end of file +// Container( +// height: 50, +// width: 120, +// child: CheckboxListTile( +// activeColor: ColorsManager.dialogBlueTitle, +// selectedTileColor: child.isHighlighted +// ? Colors.blue.shade50 +// : Colors.white, +// dense: true, +// controlAffinity: +// ListTileControlAffinity.leading, +// title: Text( +// child.title, +// style: context.textTheme.bodyMedium?.copyWith( +// fontWeight: FontWeight.w400, +// fontSize: 12, +// color: ColorsManager.lightGreyColor), +// ), +// value: child.isChecked, +// onChanged: (value) => +// toggleOptionById(child.id), +// enabled: false, +// ), +// ), diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/popup_menu_filter.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/popup_menu_filter.dart index a7f6c2b5..e79249d7 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/popup_menu_filter.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/popup_menu_filter.dart @@ -47,9 +47,9 @@ Future showPopUpFilterMenu({ width: 25, ), title: Text( - "Sort A to Z", + 'Sort A to Z', style: TextStyle( - color: isSelected == "Asc" + color: isSelected == 'Asc' ? ColorsManager.blackColor : ColorsManager.grayColor), ), @@ -72,16 +72,16 @@ Future showPopUpFilterMenu({ width: 25, ), title: Text( - "Sort Z to A", + 'Sort Z to A', style: TextStyle( - color: isSelected == "Desc" + color: isSelected == 'Desc' ? ColorsManager.blackColor : ColorsManager.grayColor), ), ), const Divider(), const Text( - "Filter by ", + 'Filter by ', style: TextStyle(fontWeight: FontWeight.bold), ), Container( @@ -113,7 +113,8 @@ Future showPopUpFilterMenu({ ), Text( item, - style: TextStyle(color: ColorsManager.grayColor), + style: const TextStyle( + color: ColorsManager.grayColor), ), ], ); @@ -136,12 +137,12 @@ Future showPopUpFilterMenu({ onTap: () { Navigator.of(context).pop(); // Close the menu }, - child: const Text("Cancel"), + child: const Text('Cancel'), ), GestureDetector( onTap: onOkPressed, child: const Text( - "OK", + 'OK', style: TextStyle( color: ColorsManager.spaceColor, ), diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/role_dropdown.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/role_dropdown.dart index 3a5ac65c..80ea8677 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/role_dropdown.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/role_dropdown.dart @@ -31,7 +31,7 @@ class _RoleDropdownState extends State { const Row( children: [ Text( - " * ", + ' * ', style: TextStyle( color: ColorsManager.red, fontWeight: FontWeight.w900, @@ -39,7 +39,7 @@ class _RoleDropdownState extends State { ), ), Text( - "Role", + 'Role', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, @@ -77,7 +77,7 @@ class _RoleDropdownState extends State { hint: const Padding( padding: EdgeInsets.only(left: 10), child: Text( - "Please Select", + 'Please Select', style: TextStyle( color: ColorsManager.textGray, ), diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/roles_and_permission.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/roles_and_permission.dart index f4b91747..a5e140b4 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/roles_and_permission.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/roles_and_permission.dart @@ -16,11 +16,11 @@ class RolesAndPermission extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder(builder: (context, state) { - final _blocRole = BlocProvider.of(context); - return Container( + final blocRole = BlocProvider.of(context); + return ColoredBox( color: Colors.white, child: Form( - key: _blocRole.formKey, + key: blocRole.formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, @@ -39,7 +39,7 @@ class RolesAndPermission extends StatelessWidget { width: 350, height: 100, child: RoleDropdown( - bloc: _blocRole, + bloc: blocRole, )), const SizedBox(height: 10), Expanded( @@ -69,11 +69,10 @@ class RolesAndPermission extends StatelessWidget { child: TextFormField( style: const TextStyle(color: Colors.black), - controller: - _blocRole.roleSearchController, + controller: blocRole.roleSearchController, onChanged: (value) { - _blocRole.add(SearchPermission( - nodes: _blocRole.permissions, + blocRole.add(SearchPermission( + nodes: blocRole.permissions, searchTerm: value)); }, decoration: textBoxDecoration(radios: 20)! @@ -107,10 +106,10 @@ class RolesAndPermission extends StatelessWidget { child: Container( color: ColorsManager.circleRolesBackground, padding: const EdgeInsets.all(8.0), - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: PermissionManagement( - bloc: _blocRole, + bloc: blocRole, )))) ], ), diff --git a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/spaces_access_view.dart b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/spaces_access_view.dart index 63f870e6..dfd59ae8 100644 --- a/lib/pages/roles_and_permission/users_page/add_user_dialog/view/spaces_access_view.dart +++ b/lib/pages/roles_and_permission/users_page/add_user_dialog/view/spaces_access_view.dart @@ -11,19 +11,21 @@ class SpacesAccessView extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder(builder: (context, state) { - final _blocRole = BlocProvider.of(context); - return Container( + final blocRole = BlocProvider.of(context); + return ColoredBox( color: Colors.white, child: Form( - key: _blocRole.formKey, + key: blocRole.formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( 'Spaces access', - style: context.textTheme.bodyLarge - ?.copyWith(fontWeight: FontWeight.w700, fontSize: 20, color: Colors.black), + style: context.textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w700, + fontSize: 20, + color: Colors.black), ), const SizedBox( height: 35, diff --git a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_bloc.dart b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_bloc.dart index e7eda606..e032f6e4 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_bloc.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_bloc.dart @@ -6,8 +6,6 @@ import 'package:syncrow_web/pages/roles_and_permission/model/roles_user_model.da import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart'; import 'package:syncrow_web/services/user_permission.dart'; -import 'package:syncrow_web/utils/constants/strings_manager.dart'; -import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart'; class UserTableBloc extends Bloc { UserTableBloc() : super(TableInitial()) { @@ -60,20 +58,20 @@ class UserTableBloc extends Bloc { final dateB = _parseDateTime(b.createdDate); return dateB.compareTo(dateA); }); - for (var user in users) { + for (final user in users) { roleTypes.add(user.roleType.toString()); } - for (var user in users) { + for (final user in users) { jobTitle.add(user.jobTitle.toString()); } - for (var user in users) { - createdBy.add(user.invitedBy.toString()); + for (final user in users) { + createdBy.add(user.invitedBy); } initialUsers = List.from(users); roleTypes = roleTypes.toSet().toList(); jobTitle = jobTitle.toSet().toList(); createdBy = createdBy.toSet().toList(); - _handlePageChange(ChangePage(1), emit); + _handlePageChange(const ChangePage(1), emit); totalUsersCount = initialUsers; add(ChangePage(currentPage)); emit(UsersLoadedState(users: users)); @@ -86,7 +84,7 @@ class UserTableBloc extends Bloc { DeleteUserEvent event, Emitter emit) async { emit(UsersLoadingState()); try { - bool res = await UserPermissionApi().deleteUserById(event.userId); + final res = await UserPermissionApi().deleteUserById(event.userId); if (res == true) { Navigator.of(event.context).pop(true); } else { @@ -104,8 +102,8 @@ class UserTableBloc extends Bloc { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; emit(UsersLoadingState()); - bool res = await UserPermissionApi().changeUserStatusById(event.userId, - event.newStatus == "disabled" ? false : true, projectUuid); + final res = await UserPermissionApi().changeUserStatusById(event.userId, + event.newStatus == 'disabled' ? false : true, projectUuid); if (res == true) { add(const GetUsers()); } @@ -121,13 +119,13 @@ class UserTableBloc extends Bloc { selectedJobTitles.clear(); selectedCreatedBy.clear(); selectedStatuses.clear(); - if (currentSortOrder == "Asc") { + if (currentSortOrder == 'Asc') { emit(UsersLoadingState()); - currentSortOrder = ""; + currentSortOrder = ''; users = List.from(users); } else { emit(UsersLoadingState()); - currentSortOrder = "Asc"; + currentSortOrder = 'Asc'; users.sort((a, b) => a.firstName .toString() .toLowerCase() @@ -146,13 +144,13 @@ class UserTableBloc extends Bloc { selectedJobTitles.clear(); selectedCreatedBy.clear(); selectedStatuses.clear(); - if (currentSortOrder == "Desc") { + if (currentSortOrder == 'Desc') { emit(UsersLoadingState()); - currentSortOrder = ""; + currentSortOrder = ''; users = List.from(initialUsers); } else { emit(UsersLoadingState()); - currentSortOrder = "Desc"; + currentSortOrder = 'Desc'; users.sort((a, b) => b.firstName!.compareTo(a.firstName!)); } currentSortJopTitle = ''; @@ -168,15 +166,15 @@ class UserTableBloc extends Bloc { selectedJobTitles.clear(); selectedCreatedBy.clear(); selectedStatuses.clear(); - if (currentSortOrderDate == "NewestToOldest") { + if (currentSortOrderDate == 'NewestToOldest') { emit(UsersLoadingState()); - currentSortOrder = ""; - currentSortOrderDate = ""; + currentSortOrder = ''; + currentSortOrderDate = ''; users = List.from(initialUsers); emit(UsersLoadedState(users: users)); } else { emit(UsersLoadingState()); - currentSortOrder = "NewestToOldest"; + currentSortOrder = 'NewestToOldest'; users.sort((a, b) { final dateA = _parseDateTime(a.createdDate); final dateB = _parseDateTime(b.createdDate); @@ -192,10 +190,10 @@ class UserTableBloc extends Bloc { selectedJobTitles.clear(); selectedCreatedBy.clear(); selectedStatuses.clear(); - if (currentSortOrderDate == "OldestToNewest") { + if (currentSortOrderDate == 'OldestToNewest') { emit(UsersLoadingState()); - currentSortOrder = ""; - currentSortOrderDate = ""; + currentSortOrder = ''; + currentSortOrderDate = ''; users = List.from(initialUsers); emit(UsersLoadedState(users: users)); } else { @@ -205,7 +203,7 @@ class UserTableBloc extends Bloc { final dateB = _parseDateTime(b.createdDate); return dateA.compareTo(dateB); }); - currentSortOrder = "OldestToNewest"; + currentSortOrder = 'OldestToNewest'; emit(UsersLoadedState(users: users)); } } @@ -228,7 +226,7 @@ class UserTableBloc extends Bloc { emit(TableSearch()); final query = event.query.toLowerCase(); final filteredUsers = initialUsers.where((user) { - final fullName = "${user.firstName} ${user.lastName}".toLowerCase(); + final fullName = '${user.firstName} ${user.lastName}'.toLowerCase(); final email = user.email.toLowerCase(); return fullName.contains(query) || email.contains(query); }).toList(); @@ -283,22 +281,22 @@ class UserTableBloc extends Bloc { return selectedRoles.contains(user.roleType); }).toList(); - if (event.sortOrder == "Asc") { - currentSortOrder = "Asc"; + if (event.sortOrder == 'Asc') { + currentSortOrder = 'Asc'; filteredUsers.sort((a, b) => a.firstName .toString() .toLowerCase() .compareTo(b.firstName.toString().toLowerCase())); - } else if (event.sortOrder == "Desc") { - currentSortOrder = "Desc"; + } else if (event.sortOrder == 'Desc') { + currentSortOrder = 'Desc'; filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); } else {} - currentSortOrder = ""; + currentSortOrder = ''; currentSortCreatedDate = ''; currentSortStatus = ''; currentSortCreatedBy = ''; currentSortJopTitle = ''; - currentSortOrderDate = ""; + currentSortOrderDate = ''; totalUsersCount = filteredUsers; @@ -313,22 +311,22 @@ class UserTableBloc extends Bloc { if (selectedJobTitles.isEmpty) return true; return selectedJobTitles.contains(user.jobTitle); }).toList(); - if (event.sortOrder == "Asc") { - currentSortOrder = "Asc"; + if (event.sortOrder == 'Asc') { + currentSortOrder = 'Asc'; filteredUsers.sort((a, b) => a.firstName .toString() .toLowerCase() .compareTo(b.firstName.toString().toLowerCase())); - } else if (event.sortOrder == "Desc") { - currentSortOrder = "Desc"; + } else if (event.sortOrder == 'Desc') { + currentSortOrder = 'Desc'; filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); } else {} - currentSortOrder = ""; + currentSortOrder = ''; currentSortCreatedDate = ''; currentSortStatus = ''; currentSortCreatedBy = ''; currentSortRole = ''; - currentSortOrderDate = ""; + currentSortOrderDate = ''; totalUsersCount = filteredUsers; @@ -344,21 +342,21 @@ class UserTableBloc extends Bloc { return selectedCreatedBy.contains(user.invitedBy); }).toList(); - if (event.sortOrder == "Asc") { - currentSortOrder = "Asc"; + if (event.sortOrder == 'Asc') { + currentSortOrder = 'Asc'; filteredUsers.sort((a, b) => a.firstName .toString() .toLowerCase() .compareTo(b.firstName.toString().toLowerCase())); - } else if (event.sortOrder == "Desc") { - currentSortOrder = "Desc"; + } else if (event.sortOrder == 'Desc') { + currentSortOrder = 'Desc'; filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); } else {} currentSortOrder = ''; currentSortRole = ''; currentSortCreatedDate = ''; currentSortStatus = ''; - currentSortOrderDate = ""; + currentSortOrderDate = ''; totalUsersCount = filteredUsers; @@ -386,14 +384,14 @@ class UserTableBloc extends Bloc { } }); }).toList(); - if (event.sortOrder == "Asc") { - currentSortOrder = "Asc"; + if (event.sortOrder == 'Asc') { + currentSortOrder = 'Asc'; filteredUsers.sort((a, b) => a.firstName .toString() .toLowerCase() .compareTo(b.firstName.toString().toLowerCase())); - } else if (event.sortOrder == "Desc") { - currentSortOrder = "Desc"; + } else if (event.sortOrder == 'Desc') { + currentSortOrder = 'Desc'; filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); totalUsersCount = filteredUsers; } else {} @@ -401,7 +399,7 @@ class UserTableBloc extends Bloc { currentSortRole = ''; currentSortCreatedDate = ''; currentSortCreatedBy = ''; - currentSortOrderDate = ""; + currentSortOrderDate = ''; emit(UsersLoadedState(users: filteredUsers)); } diff --git a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart index 1d9567cf..aea65950 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart @@ -64,7 +64,7 @@ class DateOldestToNewestEvent extends UserTableEvent { class SearchUsers extends UserTableEvent { final String query; - SearchUsers(this.query); + const SearchUsers(this.query); @override List get props => []; } @@ -72,7 +72,7 @@ class SearchUsers extends UserTableEvent { class ChangePage extends UserTableEvent { final int pageNumber; - ChangePage(this.pageNumber); + const ChangePage(this.pageNumber); @override List get props => [pageNumber]; @@ -93,6 +93,7 @@ class FilterUsersByRoleEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByRoleEvent({this.selectedRoles, this.sortOrder}); + @override List get props => [selectedRoles, sortOrder]; } @@ -101,6 +102,7 @@ class FilterUsersByJobEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByJobEvent({this.selectedJob, this.sortOrder}); + @override List get props => [selectedJob, sortOrder]; } @@ -110,6 +112,7 @@ class FilterUsersByCreatedEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByCreatedEvent({this.selectedCreatedBy, this.sortOrder}); + @override List get props => [selectedCreatedBy, sortOrder]; } @@ -118,6 +121,7 @@ class FilterUsersByDeActevateEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByDeActevateEvent({this.selectedActivate, this.sortOrder}); + @override List get props => [selectedActivate, sortOrder]; } @@ -125,14 +129,14 @@ class FilterOptionsEvent extends UserTableEvent { final String query; final List fullOptions; - FilterOptionsEvent({required this.query, required this.fullOptions}); + const FilterOptionsEvent({required this.query, required this.fullOptions}); @override List get props => [query, fullOptions]; } class FilterClearEvent extends UserTableEvent { - FilterClearEvent(); + const FilterClearEvent(); @override List get props => []; } diff --git a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart index ae99af3a..9d71602b 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart @@ -9,10 +9,12 @@ final class TableInitial extends UserTableState { @override List get props => []; } + final class TableSearch extends UserTableState { @override List get props => []; } + final class RolesLoadingState extends UserTableState { @override List get props => []; diff --git a/lib/pages/roles_and_permission/users_page/users_table/view/creation_date_filter.dart b/lib/pages/roles_and_permission/users_page/users_table/view/creation_date_filter.dart index 7b7da0bd..198049f0 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/view/creation_date_filter.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/view/creation_date_filter.dart @@ -8,9 +8,8 @@ Future showDateFilterMenu({ Function()? zToaTap, String? isSelected, }) async { - final RenderBox overlay = - Overlay.of(context).context.findRenderObject() as RenderBox; - final RelativeRect position = RelativeRect.fromRect( + final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; + final position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 3, 240, @@ -39,9 +38,9 @@ Future showDateFilterMenu({ width: 25, ), title: Text( - "Sort from newest to oldest", + 'Sort from newest to oldest', style: TextStyle( - color: isSelected == "NewestToOldest" + color: isSelected == 'NewestToOldest' ? Colors.black : Colors.blueGrey), ), @@ -55,9 +54,9 @@ Future showDateFilterMenu({ width: 25, ), title: Text( - "Sort from oldest to newest", + 'Sort from oldest to newest', style: TextStyle( - color: isSelected == "OldestToNewest" + color: isSelected == 'OldestToNewest' ? Colors.black : Colors.blueGrey), ), diff --git a/lib/pages/roles_and_permission/users_page/users_table/view/de_activate_filter.dart b/lib/pages/roles_and_permission/users_page/users_table/view/de_activate_filter.dart index c8742ea5..166e1ca9 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/view/de_activate_filter.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/view/de_activate_filter.dart @@ -8,9 +8,8 @@ Future showDeActivateFilterMenu({ Function()? zToaTap, String? isSelected, }) async { - final RenderBox overlay = - Overlay.of(context).context.findRenderObject() as RenderBox; - final RelativeRect position = RelativeRect.fromRect( + final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; + final position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 2, 240, @@ -39,9 +38,9 @@ Future showDeActivateFilterMenu({ width: 25, ), title: Text( - "Sort A to Z", + 'Sort A to Z', style: TextStyle( - color: isSelected == "NewestToOldest" + color: isSelected == 'NewestToOldest' ? Colors.black : Colors.blueGrey), ), @@ -55,9 +54,9 @@ Future showDeActivateFilterMenu({ width: 25, ), title: Text( - "Sort Z to A", + 'Sort Z to A', style: TextStyle( - color: isSelected == "OldestToNewest" + color: isSelected == 'OldestToNewest' ? Colors.black : Colors.blueGrey), ), diff --git a/lib/pages/roles_and_permission/users_page/users_table/view/name_filter.dart b/lib/pages/roles_and_permission/users_page/users_table/view/name_filter.dart index f551cf3c..a047fe97 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/view/name_filter.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/view/name_filter.dart @@ -8,9 +8,8 @@ Future showNameMenu({ Function()? zToATap, String? isSelected, }) async { - final RenderBox overlay = - Overlay.of(context).context.findRenderObject() as RenderBox; - final RelativeRect position = RelativeRect.fromRect( + final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; + final position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 35, 240, @@ -39,9 +38,9 @@ Future showNameMenu({ width: 25, ), title: Text( - "Sort A to Z", + 'Sort A to Z', style: TextStyle( - color: isSelected == "Asc" ? Colors.black : Colors.blueGrey), + color: isSelected == 'Asc' ? Colors.black : Colors.blueGrey), ), ), ), @@ -53,9 +52,9 @@ Future showNameMenu({ width: 25, ), title: Text( - "Sort Z to A", + 'Sort Z to A', style: TextStyle( - color: isSelected == "Desc" ? Colors.black : Colors.blueGrey), + color: isSelected == 'Desc' ? Colors.black : Colors.blueGrey), ), ), ), diff --git a/lib/pages/roles_and_permission/users_page/users_table/view/user_table.dart b/lib/pages/roles_and_permission/users_page/users_table/view/user_table.dart index 9b10b5d4..624a57f7 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/view/user_table.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/view/user_table.dart @@ -17,8 +17,7 @@ class _HeaderColumn extends StatelessWidget { required this.showFilter, required this.onResize, this.onFilter, - Key? key, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -71,8 +70,7 @@ class _TableRow extends StatelessWidget { required this.cells, required this.columnWidths, required this.isLast, - Key? key, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -116,9 +114,9 @@ class DynamicTableScreen extends StatefulWidget { required this.titles, required this.rows, required this.onFilter, - Key? key, + super.key, required this.tableSize, - }) : super(key: key); + }); @override _DynamicTableScreenState createState() => _DynamicTableScreenState(); @@ -139,12 +137,12 @@ class _DynamicTableScreenState extends State { void _handleColumnResize(int index, double delta) { setState(() { - double newWidth = columnWidths[index] + delta; + var newWidth = columnWidths[index] + delta; newWidth = newWidth.clamp(_minColumnWidth, _maxColumnWidth); - double actualDelta = newWidth - columnWidths[index]; + final actualDelta = newWidth - columnWidths[index]; if (actualDelta == 0) return; - int nextIndex = (index + 1) % columnWidths.length; + final nextIndex = (index + 1) % columnWidths.length; columnWidths[index] = newWidth; columnWidths[nextIndex] = (columnWidths[nextIndex] - actualDelta) .clamp(_minColumnWidth, _maxColumnWidth); @@ -256,7 +254,7 @@ class _DynamicTableScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildHeader(), - Container(height: widget.tableSize - 37, child: _buildBody()), + SizedBox(height: widget.tableSize - 37, child: _buildBody()), ], ), ), diff --git a/lib/pages/roles_and_permission/users_page/users_table/view/users_page.dart b/lib/pages/roles_and_permission/users_page/users_table/view/users_page.dart index 735ce839..d007baf2 100644 --- a/lib/pages/roles_and_permission/users_page/users_table/view/users_page.dart +++ b/lib/pages/roles_and_permission/users_page/users_table/view/users_page.dart @@ -21,11 +21,11 @@ import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/style.dart'; class UsersPage extends StatelessWidget { - UsersPage({super.key}); + const UsersPage({super.key}); @override Widget build(BuildContext context) { - final TextEditingController searchController = TextEditingController(); + final searchController = TextEditingController(); Widget actionButton( {bool isActive = false, required String title, Function()? onTap}) { @@ -36,9 +36,9 @@ class UsersPage extends StatelessWidget { child: Text( title, style: Theme.of(context).textTheme.bodySmall?.copyWith( - color: isActive == false && title != "Delete" + color: isActive == false && title != 'Delete' ? Colors.grey - : title == "Delete" + : title == 'Delete' ? ColorsManager.red : ColorsManager.spaceColor, fontWeight: FontWeight.w400, @@ -54,11 +54,11 @@ class UsersPage extends StatelessWidget { padding: const EdgeInsets.only(left: 5, right: 5, bottom: 5, top: 5), decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(20)), - color: status == "invited" - ? ColorsManager.invitedOrange.withOpacity(0.5) - : status == "active" - ? ColorsManager.activeGreen.withOpacity(0.5) - : ColorsManager.disabledPink.withOpacity(0.5), + color: status == 'invited' + ? ColorsManager.invitedOrange.withValues(alpha: 0.5) + : status == 'active' + ? ColorsManager.activeGreen.withValues(alpha: 0.5) + : ColorsManager.disabledPink.withValues(alpha: 0.5), ), child: Padding( padding: @@ -70,9 +70,9 @@ class UsersPage extends StatelessWidget { Text( status, style: Theme.of(context).textTheme.bodySmall?.copyWith( - color: status == "invited" + color: status == 'invited' ? ColorsManager.invitedOrangeText - : status == "active" + : status == 'active' ? ColorsManager.activeGreenText : ColorsManager.disabledRedText, fontWeight: FontWeight.w400, @@ -96,9 +96,9 @@ class UsersPage extends StatelessWidget { padding: const EdgeInsets.only(left: 5, right: 5, bottom: 5, top: 5), child: SvgPicture.asset( - status == "invited" + status == 'invited' ? Assets.invitedIcon - : status == "active" + : status == 'active' ? Assets.activeUser : Assets.deActiveUser, height: 35, @@ -111,7 +111,7 @@ class UsersPage extends StatelessWidget { return BlocBuilder( builder: (context, state) { final screenSize = MediaQuery.of(context).size; - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); if (state is UsersLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is UsersLoadedState) { @@ -134,10 +134,10 @@ class UsersPage extends StatelessWidget { controller: searchController, onChanged: (value) { final bloc = context.read(); - bloc.add(FilterClearEvent()); + bloc.add(const FilterClearEvent()); bloc.add(SearchUsers(value)); if (value == '') { - bloc.add(ChangePage(1)); + bloc.add(const ChangePage(1)); } }, style: const TextStyle(color: Colors.black), @@ -170,7 +170,7 @@ class UsersPage extends StatelessWidget { }, ).then((v) { if (v != null) { - _blocRole.add(const GetUsers()); + blocRole.add(const GetUsers()); } }); }, @@ -193,7 +193,7 @@ class UsersPage extends StatelessWidget { ], ), const SizedBox(height: 20), - Container( + SizedBox( height: screenSize.height * 0.65, child: DynamicTableScreen( tableSize: screenSize.height * 0.65, @@ -201,7 +201,7 @@ class UsersPage extends StatelessWidget { if (columnIndex == 0) { showNameMenu( context: context, - isSelected: _blocRole.currentSortOrder, + isSelected: blocRole.currentSortOrder, aToZTap: () { context .read() @@ -215,13 +215,13 @@ class UsersPage extends StatelessWidget { ); } if (columnIndex == 2) { - final Map checkboxStates = { - for (var item in _blocRole.jobTitle) - item: _blocRole.selectedJobTitles.contains(item), + final checkboxStates = { + for (final item in blocRole.jobTitle) + item: blocRole.selectedJobTitles.contains(item), }; - final RenderBox overlay = Overlay.of(context) + final overlay = Overlay.of(context) .context - .findRenderObject() as RenderBox; + .findRenderObject()! as RenderBox; showPopUpFilterMenu( position: RelativeRect.fromLTRB( @@ -230,40 +230,40 @@ class UsersPage extends StatelessWidget { overlay.size.width / 4, 0, ), - list: _blocRole.jobTitle, + list: blocRole.jobTitle, context: context, checkboxStates: checkboxStates, - isSelected: _blocRole.currentSortJopTitle, + isSelected: blocRole.currentSortJopTitle, onOkPressed: () { searchController.clear(); - _blocRole.add(FilterClearEvent()); + blocRole.add(const FilterClearEvent()); final selectedItems = checkboxStates.entries .where((entry) => entry.value) .map((entry) => entry.key) .toList(); Navigator.of(context).pop(); - _blocRole.add(FilterUsersByJobEvent( + blocRole.add(FilterUsersByJobEvent( selectedJob: selectedItems, - sortOrder: _blocRole.currentSortJopTitle, + sortOrder: blocRole.currentSortJopTitle, )); }, onSortAtoZ: (v) { - _blocRole.currentSortJopTitle = v; + blocRole.currentSortJopTitle = v; }, onSortZtoA: (v) { - _blocRole.currentSortJopTitle = v; + blocRole.currentSortJopTitle = v; }, ); } if (columnIndex == 3) { - final Map checkboxStates = { - for (var item in _blocRole.roleTypes) - item: _blocRole.selectedRoles.contains(item), + final checkboxStates = { + for (final item in blocRole.roleTypes) + item: blocRole.selectedRoles.contains(item), }; - final RenderBox overlay = Overlay.of(context) + final overlay = Overlay.of(context) .context - .findRenderObject() as RenderBox; + .findRenderObject()! as RenderBox; showPopUpFilterMenu( position: RelativeRect.fromLTRB( overlay.size.width / 4, @@ -271,13 +271,13 @@ class UsersPage extends StatelessWidget { overlay.size.width / 4, 0, ), - list: _blocRole.roleTypes, + list: blocRole.roleTypes, context: context, checkboxStates: checkboxStates, - isSelected: _blocRole.currentSortRole, + isSelected: blocRole.currentSortRole, onOkPressed: () { searchController.clear(); - _blocRole.add(FilterClearEvent()); + blocRole.add(const FilterClearEvent()); final selectedItems = checkboxStates.entries .where((entry) => entry.value) .map((entry) => entry.key) @@ -286,20 +286,20 @@ class UsersPage extends StatelessWidget { context.read().add( FilterUsersByRoleEvent( selectedRoles: selectedItems, - sortOrder: _blocRole.currentSortRole)); + sortOrder: blocRole.currentSortRole)); }, onSortAtoZ: (v) { - _blocRole.currentSortRole = v; + blocRole.currentSortRole = v; }, onSortZtoA: (v) { - _blocRole.currentSortRole = v; + blocRole.currentSortRole = v; }, ); } if (columnIndex == 4) { showDateFilterMenu( context: context, - isSelected: _blocRole.currentSortOrder, + isSelected: blocRole.currentSortOrder, aToZTap: () { context .read() @@ -313,13 +313,13 @@ class UsersPage extends StatelessWidget { ); } if (columnIndex == 6) { - final Map checkboxStates = { - for (var item in _blocRole.createdBy) - item: _blocRole.selectedCreatedBy.contains(item), + final checkboxStates = { + for (final item in blocRole.createdBy) + item: blocRole.selectedCreatedBy.contains(item), }; - final RenderBox overlay = Overlay.of(context) + final overlay = Overlay.of(context) .context - .findRenderObject() as RenderBox; + .findRenderObject()! as RenderBox; showPopUpFilterMenu( position: RelativeRect.fromLTRB( overlay.size.width / 1, @@ -327,39 +327,39 @@ class UsersPage extends StatelessWidget { overlay.size.width / 4, 0, ), - list: _blocRole.createdBy, + list: blocRole.createdBy, context: context, checkboxStates: checkboxStates, - isSelected: _blocRole.currentSortCreatedBy, + isSelected: blocRole.currentSortCreatedBy, onOkPressed: () { searchController.clear(); - _blocRole.add(FilterClearEvent()); + blocRole.add(const FilterClearEvent()); final selectedItems = checkboxStates.entries .where((entry) => entry.value) .map((entry) => entry.key) .toList(); Navigator.of(context).pop(); - _blocRole.add(FilterUsersByCreatedEvent( + blocRole.add(FilterUsersByCreatedEvent( selectedCreatedBy: selectedItems, - sortOrder: _blocRole.currentSortCreatedBy)); + sortOrder: blocRole.currentSortCreatedBy)); }, onSortAtoZ: (v) { - _blocRole.currentSortCreatedBy = v; + blocRole.currentSortCreatedBy = v; }, onSortZtoA: (v) { - _blocRole.currentSortCreatedBy = v; + blocRole.currentSortCreatedBy = v; }, ); } if (columnIndex == 7) { - final Map checkboxStates = { - for (var item in _blocRole.status) - item: _blocRole.selectedStatuses.contains(item), + final checkboxStates = { + for (final item in blocRole.status) + item: blocRole.selectedStatuses.contains(item), }; - final RenderBox overlay = Overlay.of(context) + final overlay = Overlay.of(context) .context - .findRenderObject() as RenderBox; + .findRenderObject()! as RenderBox; showPopUpFilterMenu( position: RelativeRect.fromLTRB( overlay.size.width / 0, @@ -367,34 +367,34 @@ class UsersPage extends StatelessWidget { overlay.size.width / 5, 0, ), - list: _blocRole.status, + list: blocRole.status, context: context, checkboxStates: checkboxStates, - isSelected: _blocRole.currentSortStatus, + isSelected: blocRole.currentSortStatus, onOkPressed: () { searchController.clear(); - _blocRole.add(FilterClearEvent()); + blocRole.add(const FilterClearEvent()); final selectedItems = checkboxStates.entries .where((entry) => entry.value) .map((entry) => entry.key) .toList(); Navigator.of(context).pop(); - _blocRole.add(FilterUsersByDeActevateEvent( + blocRole.add(FilterUsersByDeActevateEvent( selectedActivate: selectedItems, - sortOrder: _blocRole.currentSortStatus)); + sortOrder: blocRole.currentSortStatus)); }, onSortAtoZ: (v) { - _blocRole.currentSortStatus = v; + blocRole.currentSortStatus = v; }, onSortZtoA: (v) { - _blocRole.currentSortStatus = v; + blocRole.currentSortStatus = v; }, ); } if (columnIndex == 8) { showDeActivateFilterMenu( context: context, - isSelected: _blocRole.currentSortOrderDate, + isSelected: blocRole.currentSortOrderDate, aToZTap: () { context .read() @@ -409,16 +409,16 @@ class UsersPage extends StatelessWidget { } }, titles: const [ - "Full Name", - "Email Address", - "Job Title", - "Role", - "Creation Date", - "Creation Time", - "Created By", - "Status", - "De/Activate", - "Action" + 'Full Name', + 'Email Address', + 'Job Title', + 'Role', + 'Creation Date', + 'Creation Time', + 'Created By', + 'Status', + 'De/Activate', + 'Action' ], rows: state.users.map((user) { return [ @@ -439,7 +439,7 @@ class UsersPage extends StatelessWidget { ? 'disabled' : user.status, userId: user.uuid, - onTap: user.status != "invited" + onTap: user.status != 'invited' ? () { context.read().add( ChangeUserStatus( @@ -452,35 +452,36 @@ class UsersPage extends StatelessWidget { ), Row( children: [ - user.isEnabled != false - ? actionButton( - isActive: true, - title: "Edit", - onTap: () { - context - .read() - .add(ClearCachedData()); - showDialog( - context: context, - barrierDismissible: false, - builder: (BuildContext context) { - return EditUserDialog( - userId: user.uuid); - }, - ).then((v) { - if (v != null) { - if (v != null) { - _blocRole.add(const GetUsers()); - } - } - }); + if (user.isEnabled != false) + actionButton( + isActive: true, + title: 'Edit', + onTap: () { + context + .read() + .add(ClearCachedData()); + showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) { + return EditUserDialog( + userId: user.uuid); }, - ) - : actionButton( - title: "Edit", - ), + ).then((v) { + if (v != null) { + if (v != null) { + blocRole.add(const GetUsers()); + } + } + }); + }, + ) + else + actionButton( + title: 'Edit', + ), actionButton( - title: "Delete", + title: 'Delete', onTap: () { showDialog( context: context, @@ -489,7 +490,7 @@ class UsersPage extends StatelessWidget { return DeleteUserDialog( onTapDelete: () async { try { - _blocRole.add(DeleteUserEvent( + blocRole.add(DeleteUserEvent( user.uuid, context)); await Future.delayed( const Duration(seconds: 2)); @@ -501,7 +502,7 @@ class UsersPage extends StatelessWidget { }, ).then((v) { if (v != null) { - _blocRole.add(const GetUsers()); + blocRole.add(const GetUsers()); } }); }, @@ -529,10 +530,10 @@ class UsersPage extends StatelessWidget { const Icon(Icons.keyboard_double_arrow_right), firstPageIcon: const Icon(Icons.keyboard_double_arrow_left), - totalPages: (_blocRole.totalUsersCount.length / - _blocRole.itemsPerPage) + totalPages: (blocRole.totalUsersCount.length / + blocRole.itemsPerPage) .ceil(), - currentPage: _blocRole.currentPage, + currentPage: blocRole.currentPage, onPageChanged: (int pageNumber) { context .read() diff --git a/lib/pages/roles_and_permission/view/create_role_card.dart b/lib/pages/roles_and_permission/view/create_role_card.dart index e69de29b..8b137891 100644 --- a/lib/pages/roles_and_permission/view/create_role_card.dart +++ b/lib/pages/roles_and_permission/view/create_role_card.dart @@ -0,0 +1 @@ + diff --git a/lib/pages/roles_and_permission/view/role_card.dart b/lib/pages/roles_and_permission/view/role_card.dart index b08b14ea..866b0345 100644 --- a/lib/pages/roles_and_permission/view/role_card.dart +++ b/lib/pages/roles_and_permission/view/role_card.dart @@ -13,7 +13,8 @@ class RoleCard extends StatelessWidget { borderRadius: BorderRadius.circular(20), // Rounded corners boxShadow: [ BoxShadow( - color: ColorsManager.blackColor.withOpacity(0.2), // Shadow color + color: + ColorsManager.blackColor.withValues(alpha: 0.2), // Shadow color blurRadius: 20, // Spread of the shadow offset: const Offset(2, 2), // No directional bias spreadRadius: 1, // Ensures the shadow is more noticeable @@ -23,7 +24,7 @@ class RoleCard extends StatelessWidget { child: Container( decoration: BoxDecoration( color: ColorsManager.whiteColors, - borderRadius: BorderRadius.circular(20), + borderRadius: BorderRadius.circular(20), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, diff --git a/lib/pages/roles_and_permission/view/roles_and_permission_page.dart b/lib/pages/roles_and_permission/view/roles_and_permission_page.dart index 4ba83cc1..b7a510d0 100644 --- a/lib/pages/roles_and_permission/view/roles_and_permission_page.dart +++ b/lib/pages/roles_and_permission/view/roles_and_permission_page.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart'; import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_state.dart'; @@ -22,7 +21,7 @@ class RolesAndPermissionPage extends StatelessWidget { child: BlocConsumer( listener: (context, state) {}, builder: (context, state) { - final _blocRole = BlocProvider.of(context); + final blocRole = BlocProvider.of(context); return state is RolesLoadingState ? const Center(child: CircularProgressIndicator()) @@ -65,10 +64,10 @@ class RolesAndPermissionPage extends StatelessWidget { child: Text( 'Users', style: context.textTheme.titleMedium?.copyWith( - color: (_blocRole.tapSelect == true) + color: (blocRole.tapSelect == true) ? ColorsManager.whiteColors : ColorsManager.grayColor, - fontWeight: (_blocRole.tapSelect == true) + fontWeight: (blocRole.tapSelect == true) ? FontWeight.w700 : FontWeight.w400, ), @@ -78,7 +77,7 @@ class RolesAndPermissionPage extends StatelessWidget { ), scaffoldBody: BlocProvider( create: (context) => UserTableBloc()..add(const GetUsers()), - child: UsersPage(), + child: const UsersPage(), ) // _blocRole.tapSelect == false // ? UsersPage( diff --git a/lib/pages/roles_and_permission/view/roles_page.dart b/lib/pages/roles_and_permission/view/roles_page.dart index 9c8ef0cd..b8c977e3 100644 --- a/lib/pages/roles_and_permission/view/roles_page.dart +++ b/lib/pages/roles_and_permission/view/roles_page.dart @@ -13,10 +13,10 @@ class RolesPage extends StatelessWidget { @override Widget build(BuildContext context) { - final TextEditingController searchController = TextEditingController(); - double screenWidth = MediaQuery.of(context).size.width; + final searchController = TextEditingController(); + final screenWidth = MediaQuery.of(context).size.width; - int crossAxisCount = (screenWidth ~/ 200).clamp(1, 6); + final crossAxisCount = (screenWidth ~/ 200).clamp(1, 6); return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -54,9 +54,6 @@ class RolesPage extends StatelessWidget { itemCount: blocRole.roleModel.length ?? 0, itemBuilder: (context, index) { final role = blocRole.roleModel[index]; - if (role == null) { - return const SizedBox.shrink(); - } return RoleCard( name: role.roleName ?? 'Unknown', ); diff --git a/lib/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart b/lib/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart index c664c2c4..b5326a40 100644 --- a/lib/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart +++ b/lib/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart @@ -1,4 +1,3 @@ - import 'dart:convert'; class AutomationStatusUpdate { @@ -17,23 +16,23 @@ class AutomationStatusUpdate { factory AutomationStatusUpdate.fromJson(Map json) => AutomationStatusUpdate( - spaceUuid: json["spaceUuid"], - isEnable: json["isEnable"], + spaceUuid: json['spaceUuid'], + isEnable: json['isEnable'], ); Map toJson() => { - "spaceUuid": spaceUuid, - "isEnable": isEnable, + 'spaceUuid': spaceUuid, + 'isEnable': isEnable, }; factory AutomationStatusUpdate.fromMap(Map map) => AutomationStatusUpdate( - spaceUuid: map["spaceUuid"], - isEnable: map["isEnable"], + spaceUuid: map['spaceUuid'], + isEnable: map['isEnable'], ); Map toMap() => { - "spaceUuid": spaceUuid, - "isEnable": isEnable, + 'spaceUuid': spaceUuid, + 'isEnable': isEnable, }; } diff --git a/lib/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart b/lib/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart index b472d034..ab154342 100644 --- a/lib/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart +++ b/lib/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart @@ -36,7 +36,7 @@ class CreateRoutineBloc extends Bloc { } } - saveSpaceIdCommunityId( + void saveSpaceIdCommunityId( SaveCommunityIdAndSpaceIdEvent event, Emitter emit) { emit(const SpaceWithDeviceLoadingState()); selectedSpaceId = event.spaceID!; @@ -44,7 +44,8 @@ class CreateRoutineBloc extends Bloc { emit(const SelectedState()); } - resetSelected(ResetSelectedEvent event, Emitter emit) { + void resetSelected( + ResetSelectedEvent event, Emitter emit) { emit(const SpaceWithDeviceLoadingState()); selectedSpaceId = ''; selectedCommunityId = ''; diff --git a/lib/pages/routines/bloc/create_routine_bloc/create_routine_event.dart b/lib/pages/routines/bloc/create_routine_bloc/create_routine_event.dart index ba901497..4b39fe62 100644 --- a/lib/pages/routines/bloc/create_routine_bloc/create_routine_event.dart +++ b/lib/pages/routines/bloc/create_routine_bloc/create_routine_event.dart @@ -42,10 +42,9 @@ class ResetSelectedEvent extends CreateRoutineEvent { List get props => []; } - class FetchCommunityEvent extends CreateRoutineEvent { const FetchCommunityEvent(); @override List get props => []; -} \ No newline at end of file +} diff --git a/lib/pages/routines/bloc/create_routine_bloc/create_routine_state.dart b/lib/pages/routines/bloc/create_routine_bloc/create_routine_state.dart index 5ebc20f7..208b5e02 100644 --- a/lib/pages/routines/bloc/create_routine_bloc/create_routine_state.dart +++ b/lib/pages/routines/bloc/create_routine_bloc/create_routine_state.dart @@ -1,4 +1,3 @@ - import 'package:equatable/equatable.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; @@ -39,7 +38,6 @@ class SelectedState extends CreateRoutineState { const SelectedState(); } - class ResetSelectedState extends CreateRoutineState { const ResetSelectedState(); } @@ -50,4 +48,4 @@ class CommunityLoadedState extends CreateRoutineState { class CommunitiesLoadingState extends CreateRoutineState { const CommunitiesLoadingState(); -} \ No newline at end of file +} diff --git a/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart b/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart index fd56d232..af429f7d 100644 --- a/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart +++ b/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart @@ -25,7 +25,8 @@ class EffectPeriodBloc extends Bloc { on(_setAllDays); } - void _initialEvent(InitialEffectPeriodEvent event, Emitter emit) { + void _initialEvent( + InitialEffectPeriodEvent event, Emitter emit) { add(SetCustomTime(event.effectiveTime.start, event.effectiveTime.end)); emit(state.copyWith( selectedDaysBinary: event.effectiveTime.loops, @@ -35,8 +36,8 @@ class EffectPeriodBloc extends Bloc { } void _onSetPeriod(SetPeriod event, Emitter emit) { - String startTime = ''; - String endTime = ''; + var startTime = ''; + var endTime = ''; switch (event.period) { case EnumEffectivePeriodOptions.allDay: @@ -60,7 +61,9 @@ class EffectPeriodBloc extends Bloc { } emit(state.copyWith( - selectedPeriod: event.period, customStartTime: startTime, customEndTime: endTime)); + selectedPeriod: event.period, + customStartTime: startTime, + customEndTime: endTime)); } void _onToggleDay(ToggleDay event, Emitter emit) { @@ -76,8 +79,8 @@ class EffectPeriodBloc extends Bloc { } void _onSetCustomTime(SetCustomTime event, Emitter emit) { - String startTime = event.startTime; - String endTime = event.endTime; + final startTime = event.startTime; + final endTime = event.endTime; EnumEffectivePeriodOptions period; // Determine the period based on start and end times @@ -91,11 +94,14 @@ class EffectPeriodBloc extends Bloc { period = EnumEffectivePeriodOptions.custom; } - emit( - state.copyWith(customStartTime: startTime, customEndTime: endTime, selectedPeriod: period)); + emit(state.copyWith( + customStartTime: startTime, + customEndTime: endTime, + selectedPeriod: period)); } - void _onResetEffectivePeriod(ResetEffectivePeriod event, Emitter emit) { + void _onResetEffectivePeriod( + ResetEffectivePeriod event, Emitter emit) { emit(state.copyWith( selectedPeriod: EnumEffectivePeriodOptions.allDay, customStartTime: '00:00', diff --git a/lib/pages/routines/bloc/effective_period/effect_period_state.dart b/lib/pages/routines/bloc/effective_period/effect_period_state.dart index 2f8b66c8..4ecb83b9 100644 --- a/lib/pages/routines/bloc/effective_period/effect_period_state.dart +++ b/lib/pages/routines/bloc/effective_period/effect_period_state.dart @@ -17,9 +17,9 @@ class EffectPeriodState extends Equatable { factory EffectPeriodState.initial() { return const EffectPeriodState( selectedPeriod: EnumEffectivePeriodOptions.allDay, - selectedDaysBinary: "1111111", // All days selected - customStartTime: "00:00", - customEndTime: "23:59", + selectedDaysBinary: '1111111', // All days selected + customStartTime: '00:00', + customEndTime: '23:59', ); } @@ -50,5 +50,6 @@ class EffectPeriodState extends Equatable { } @override - List get props => [selectedPeriod, selectedDaysBinary, customStartTime, customEndTime]; + List get props => + [selectedPeriod, selectedDaysBinary, customStartTime, customEndTime]; } diff --git a/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart b/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart index ca8aac06..b58b953d 100644 --- a/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart +++ b/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart @@ -1,11 +1,9 @@ import 'dart:async'; -import 'package:bloc/bloc.dart'; -import 'package:dio/dio.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart'; import 'package:syncrow_web/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart'; import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart'; @@ -75,7 +73,7 @@ class RoutineBloc extends Bloc { } } - _resetErrorMessage( + void _resetErrorMessage( ResetErrorMessage event, Emitter emit, ) { @@ -93,7 +91,7 @@ class RoutineBloc extends Bloc { final updatedIfItems = List>.from(state.ifItems); // Find the index of the item in teh current itemsList - int index = updatedIfItems.indexWhere( + final index = updatedIfItems.indexWhere( (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); // Replace the map if the index is valid if (index != -1) { @@ -116,7 +114,7 @@ class RoutineBloc extends Bloc { final currentItems = List>.from(state.thenItems); // Find the index of the item in teh current itemsList - int index = currentItems.indexWhere( + final index = currentItems.indexWhere( (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); // Replace the map if the index is valid if (index != -1) { @@ -135,7 +133,7 @@ class RoutineBloc extends Bloc { // List selectedFunction = List.from(event.functions); - Map> currentSelectedFunctions = + final currentSelectedFunctions = Map>.from(state.selectedFunctions); // if (currentSelectedFunctions.containsKey(event.uniqueCustomId)) { @@ -176,18 +174,18 @@ class RoutineBloc extends Bloc { Future _onLoadScenes( LoadScenes event, Emitter emit) async { emit(state.copyWith(isLoading: true, errorMessage: null)); - List scenes = []; + final scenes = []; try { - BuildContext context = NavigationService.navigatorKey.currentContext!; - var createRoutineBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final createRoutineBloc = context.read(); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - var spaceBloc = context.read(); - for (var communityId in spaceBloc.state.selectedCommunities) { - List spacesList = + final spaceBloc = context.read(); + for (final communityId in spaceBloc.state.selectedCommunities) { + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (var spaceId in spacesList) { + for (final spaceId in spacesList) { scenes.addAll( await SceneApi.getScenes(spaceId, communityId, projectUuid)); } @@ -216,19 +214,19 @@ class RoutineBloc extends Bloc { Future _onLoadAutomation( LoadAutomation event, Emitter emit) async { emit(state.copyWith(isLoading: true, errorMessage: null)); - List automations = []; + final automations = []; final projectId = await ProjectManager.getProjectUUID() ?? ''; - BuildContext context = NavigationService.navigatorKey.currentContext!; - var createRoutineBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final createRoutineBloc = context.read(); try { if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - var spaceBloc = context.read(); - for (var communityId in spaceBloc.state.selectedCommunities) { - List spacesList = + final spaceBloc = context.read(); + for (final communityId in spaceBloc.state.selectedCommunities) { + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (var spaceId in spacesList) { + for (final spaceId in spacesList) { automations.addAll( await SceneApi.getAutomation(spaceId, communityId, projectId)); } @@ -336,8 +334,8 @@ class RoutineBloc extends Bloc { }); }).toList(); - BuildContext context = NavigationService.navigatorKey.currentContext!; - var createRoutineBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final createRoutineBloc = context.read(); final createSceneModel = CreateSceneModel( spaceUuid: createRoutineBloc.selectedSpaceId, @@ -361,7 +359,7 @@ class RoutineBloc extends Bloc { } } on APIException catch (e) { final errorData = e.message; - String errorMessage = errorData; + final errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -400,7 +398,7 @@ class RoutineBloc extends Bloc { return; } emit(state.copyWith(isLoading: true, errorMessage: null)); - int i = 0; + var i = 0; final conditions = state.ifItems.expand((item) { final functions = state.selectedFunctions[item['uniqueCustomId']] ?? []; return functions.map((function) { @@ -468,8 +466,8 @@ class RoutineBloc extends Bloc { ); }); }).toList(); - BuildContext context = NavigationService.navigatorKey.currentContext!; - var createRoutineBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final createRoutineBloc = context.read(); final createAutomationModel = CreateAutomationModel( spaceUuid: createRoutineBloc.selectedSpaceId, @@ -499,7 +497,7 @@ class RoutineBloc extends Bloc { } } on APIException catch (e) { final errorData = e.message; - String errorMessage = errorData; + final errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -705,14 +703,14 @@ class RoutineBloc extends Bloc { final List> thenItems; final List> ifItems; - final Map> updatedFunctions = + final updatedFunctions = Map>.from(state.selectedFunctions); - final Map> deviceCards = {}; + final deviceCards = >{}; - for (var action in sceneDetails.actions) { + for (final action in sceneDetails.actions) { AllDevicesModel? matchingDevice; - for (var device in state.devices) { + for (final device in state.devices) { if (device.uuid == action.entityId) { matchingDevice = device; break; @@ -777,7 +775,7 @@ class RoutineBloc extends Bloc { action.actionExecutor != 'delay') { final functions = matchingDevice?.functions ?? []; final functionCode = action.executorProperty?.functionCode; - for (DeviceFunction function in functions) { + for (final function in functions) { if (function.code == functionCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -871,8 +869,8 @@ class RoutineBloc extends Bloc { final projectId = await ProjectManager.getProjectUUID() ?? ''; emit(state.copyWith(isLoading: true)); - BuildContext context = NavigationService.navigatorKey.currentContext!; - var spaceBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final spaceBloc = context.read(); if (state.isTabToRun) { await SceneApi.deleteScene( unitUuid: spaceBloc.state.selectedSpaces[0], @@ -901,7 +899,7 @@ class RoutineBloc extends Bloc { emit(state.copyWith(isLoading: false, createRoutineView: false)); } on APIException catch (e) { final errorData = e.message; - String errorMessage = errorData; + final errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -929,17 +927,17 @@ class RoutineBloc extends Bloc { emit(state.copyWith(isLoading: true)); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - List devices = []; - BuildContext context = NavigationService.navigatorKey.currentContext!; - var createRoutineBloc = context.read(); - var spaceBloc = context.read(); + final devices = []; + final context = NavigationService.navigatorKey.currentContext!; + final createRoutineBloc = context.read(); + final spaceBloc = context.read(); if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - for (var communityId in spaceBloc.state.selectedCommunities) { - List spacesList = + for (final communityId in spaceBloc.state.selectedCommunities) { + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (var spaceId in spacesList) { + for (final spaceId in spacesList) { devices.addAll(await DevicesManagementApi() .fetchDevices(communityId, spaceId, projectUuid)); } @@ -1071,7 +1069,7 @@ class RoutineBloc extends Bloc { return; } emit(state.copyWith(isLoading: true, errorMessage: null)); - int i = 0; + var i = 0; final conditions = state.ifItems.expand((item) { final functions = state.selectedFunctions[item['uniqueCustomId']] ?? []; return functions.map((function) { @@ -1142,8 +1140,8 @@ class RoutineBloc extends Bloc { }); }).toList(); - BuildContext context = NavigationService.navigatorKey.currentContext!; - var spaceBloc = context.read(); + final context = NavigationService.navigatorKey.currentContext!; + final spaceBloc = context.read(); final createAutomationModel = CreateAutomationModel( spaceUuid: spaceBloc.selectedSpaceId, @@ -1163,8 +1161,8 @@ class RoutineBloc extends Bloc { if (result['success']) { add(ResetRoutineState()); - add(LoadAutomation()); - add(LoadScenes()); + add(const LoadAutomation()); + add(const LoadScenes()); } else { emit(state.copyWith( isLoading: false, @@ -1197,14 +1195,14 @@ class RoutineBloc extends Bloc { final automationDetails = await SceneApi.getAutomationDetails(event.automationId, projectUuid); - final Map> deviceIfCards = {}; - final Map> deviceThenCards = {}; + final deviceIfCards = >{}; + final deviceThenCards = >{}; - final Map> updatedFunctions = + final updatedFunctions = Map>.from(state.selectedFunctions); - for (RoutineCondition condition in automationDetails.conditions ?? []) { - AllDevicesModel? matchingDevice = state.devices.firstWhere( + for (final condition in automationDetails.conditions ?? []) { + final matchingDevice = state.devices.firstWhere( (device) => device.uuid == condition.entityId, orElse: () => AllDevicesModel( uuid: condition.entityId, @@ -1241,7 +1239,7 @@ class RoutineBloc extends Bloc { } final functions = matchingDevice.functions; - for (var function in functions) { + for (final function in functions) { if (function.code == condition.expr.statusCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -1257,8 +1255,8 @@ class RoutineBloc extends Bloc { } // Process actions (thenItems) - for (var action in automationDetails.actions) { - AllDevicesModel? matchingDevice = state.devices.firstWhere( + for (final action in automationDetails.actions) { + final matchingDevice = state.devices.firstWhere( (device) => device.uuid == action.entityId, orElse: () => AllDevicesModel( uuid: action.entityId, @@ -1312,7 +1310,7 @@ class RoutineBloc extends Bloc { action.actionExecutor != 'delay') { final functions = matchingDevice.functions; final functionCode = action.executorProperty!.functionCode; - for (var function in functions) { + for (final function in functions) { if (function.code == functionCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -1403,7 +1401,7 @@ class RoutineBloc extends Bloc { } catch (e) { emit(state.copyWith( loadingSceneId: null, - errorMessage: 'Trigger error: ${e.toString()}', + errorMessage: 'Trigger error: $e', )); } } @@ -1448,7 +1446,7 @@ class RoutineBloc extends Bloc { ..remove(event.automationId); emit(state.copyWith( loadingAutomationIds: updatedLoadingIds, - errorMessage: 'Update error: ${e.toString()}', + errorMessage: 'Update error: $e', )); } } diff --git a/lib/pages/routines/bloc/routine_bloc/routine_event.dart b/lib/pages/routines/bloc/routine_bloc/routine_event.dart index b532235d..dd7adf71 100644 --- a/lib/pages/routines/bloc/routine_bloc/routine_event.dart +++ b/lib/pages/routines/bloc/routine_bloc/routine_event.dart @@ -86,7 +86,8 @@ class RemoveDragCard extends RoutineEvent { final int index; final bool isFromThen; final String key; - const RemoveDragCard({required this.index, required this.isFromThen, required this.key}); + const RemoveDragCard( + {required this.index, required this.isFromThen, required this.key}); @override List get props => [index, isFromThen, key]; } @@ -211,9 +212,6 @@ class ClearFunctions extends RoutineEvent {} class ResetErrorMessage extends RoutineEvent {} - - - class SceneTrigger extends RoutineEvent { final String? sceneId; final String? name; @@ -221,7 +219,7 @@ class SceneTrigger extends RoutineEvent { const SceneTrigger({this.sceneId, this.name}); @override - List get props => [sceneId!,name!]; + List get props => [sceneId!, name!]; } //updateAutomationStatus @@ -230,7 +228,10 @@ class UpdateAutomationStatus extends RoutineEvent { final AutomationStatusUpdate automationStatusUpdate; final String communityId; - const UpdateAutomationStatus({required this.automationStatusUpdate, required this.automationId, required this.communityId}); + const UpdateAutomationStatus( + {required this.automationStatusUpdate, + required this.automationId, + required this.communityId}); @override List get props => [automationStatusUpdate]; diff --git a/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart b/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart index 843b35df..b35e3b21 100644 --- a/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart +++ b/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart @@ -15,37 +15,44 @@ class SettingBloc extends Bloc { on(_selectIcon); } - void _initialSetting(InitialEvent event, Emitter emit) async { + Future _initialSetting( + InitialEvent event, Emitter emit) async { try { emit(const LoadingState()); selectedIcon = event.selectedIcon; emit(TabToRunSettingLoaded( - showInDevice: true, selectedIcon: event.selectedIcon, iconList: iconModelList)); + showInDevice: true, + selectedIcon: event.selectedIcon, + iconList: iconModelList)); } catch (e) { emit(const FailedState(error: 'Something went wrong')); } } - void _fetchIcons(FetchIcons event, Emitter emit) async { + Future _fetchIcons(FetchIcons event, Emitter emit) async { try { isExpanded = event.expanded; emit(const LoadingState()); if (isExpanded) { iconModelList = await SceneApi.getIcon(); emit(TabToRunSettingLoaded( - showInDevice: true, selectedIcon: selectedIcon, iconList: iconModelList)); + showInDevice: true, + selectedIcon: selectedIcon, + iconList: iconModelList)); } } catch (e) { emit(const FailedState(error: 'Something went wrong')); } } - void _selectIcon(SelectIcon event, Emitter emit) async { + Future _selectIcon(SelectIcon event, Emitter emit) async { try { emit(const LoadingState()); selectedIcon = event.iconId; emit(TabToRunSettingLoaded( - showInDevice: true, selectedIcon: event.iconId, iconList: iconModelList)); + showInDevice: true, + selectedIcon: event.iconId, + iconList: iconModelList)); } catch (e) { emit(const FailedState(error: 'Something went wrong')); } diff --git a/lib/pages/routines/create_new_routines/commu_dropdown.dart b/lib/pages/routines/create_new_routines/commu_dropdown.dart index 6fd562b0..a3424013 100644 --- a/lib/pages/routines/create_new_routines/commu_dropdown.dart +++ b/lib/pages/routines/create_new_routines/commu_dropdown.dart @@ -1,11 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/routines/create_new_routines/dropdown_menu_content.dart'; +import 'package:syncrow_web/pages/routines/create_new_routines/space_tree_dropdown_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'space_tree_dropdown_bloc.dart'; class SpaceTreeDropdown extends StatefulWidget { final String? selectedSpaceId; @@ -68,7 +68,7 @@ class _SpaceTreeDropdownState extends State { Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text( - "Community", + 'Community', style: Theme.of(context).textTheme.bodyMedium!.copyWith( fontWeight: FontWeight.w400, fontSize: 13, diff --git a/lib/pages/routines/create_new_routines/create_new_routines.dart b/lib/pages/routines/create_new_routines/create_new_routines.dart index fe207910..adaff718 100644 --- a/lib/pages/routines/create_new_routines/create_new_routines.dart +++ b/lib/pages/routines/create_new_routines/create_new_routines.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart'; import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_event.dart'; import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_state.dart'; -import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart'; import 'package:syncrow_web/pages/routines/create_new_routines/commu_dropdown.dart'; import 'package:syncrow_web/pages/routines/create_new_routines/space_dropdown.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -27,11 +27,11 @@ class _CreateNewRoutinesDialogState extends State { CreateRoutineBloc()..add(const FetchCommunityEvent()), child: BlocBuilder( builder: (context, state) { - final _bloc = BlocProvider.of(context); - final spaces = _bloc.spacesOnlyWithDevices; + final bloc = BlocProvider.of(context); + final spaces = bloc.spacesOnlyWithDevices; final isLoadingCommunities = state is CommunitiesLoadingState; final isLoadingSpaces = state is SpaceWithDeviceLoadingState; - String spaceHint = 'Please Select'; + var spaceHint = 'Please Select'; if (_selectedCommunity != null) { if (isLoadingSpaces) { spaceHint = 'Loading spaces...'; @@ -77,9 +77,9 @@ class _CreateNewRoutinesDialogState extends State { SpaceTreeDropdown( selectedSpaceId: _selectedId, onChanged: (String? newValue) { - setState(() => _selectedId = newValue!); + setState(() => _selectedId = newValue); if (_selectedId != null) { - _bloc.add(SpaceOnlyWithDevicesEvent( + bloc.add(SpaceOnlyWithDevicesEvent( _selectedId!)); } }, diff --git a/lib/pages/routines/create_new_routines/dropdown_menu_content.dart b/lib/pages/routines/create_new_routines/dropdown_menu_content.dart index 70c88087..1ae5be86 100644 --- a/lib/pages/routines/create_new_routines/dropdown_menu_content.dart +++ b/lib/pages/routines/create_new_routines/dropdown_menu_content.dart @@ -1,7 +1,3 @@ - - - - import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; @@ -14,6 +10,7 @@ class DropdownMenuContent extends StatefulWidget { final VoidCallback onClose; const DropdownMenuContent({ + super.key, required this.selectedSpaceId, required this.onChanged, required this.onClose, @@ -45,7 +42,7 @@ class _DropdownMenuContentState extends State { final state = bloc.state; if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 30) { - if (state is SpaceTreeState && !state.paginationIsLoading) { + if (!state.paginationIsLoading) { bloc.add(PaginationEvent(state.paginationModel, state.communityList)); } } @@ -126,7 +123,7 @@ class _DropdownMenuContentState extends State { _searchController.text.isEmpty ? context .read() - .add(SearchQueryEvent('')) + .add(const SearchQueryEvent('')) : context.read().add( SearchQueryEvent(_searchController.text)); }); diff --git a/lib/pages/routines/create_new_routines/space_dropdown.dart b/lib/pages/routines/create_new_routines/space_dropdown.dart index 1d11b02d..5af30f28 100644 --- a/lib/pages/routines/create_new_routines/space_dropdown.dart +++ b/lib/pages/routines/create_new_routines/space_dropdown.dart @@ -10,12 +10,12 @@ class SpaceDropdown extends StatelessWidget { final String hintMessage; const SpaceDropdown({ - Key? key, + super.key, required this.spaces, required this.selectedValue, required this.onChanged, required this.hintMessage, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -25,7 +25,7 @@ class SpaceDropdown extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Space", + 'Space', style: Theme.of(context).textTheme.bodyMedium!.copyWith( fontWeight: FontWeight.w400, fontSize: 13, @@ -67,7 +67,7 @@ class SpaceDropdown extends StatelessWidget { ); }).toList(), onChanged: onChanged, - style: TextStyle(color: Colors.black), + style: const TextStyle(color: Colors.black), hint: Padding( padding: const EdgeInsets.only(left: 10), child: Text( diff --git a/lib/pages/routines/create_new_routines/space_tree_dropdown_bloc.dart b/lib/pages/routines/create_new_routines/space_tree_dropdown_bloc.dart index be2a7e9b..da835e4b 100644 --- a/lib/pages/routines/create_new_routines/space_tree_dropdown_bloc.dart +++ b/lib/pages/routines/create_new_routines/space_tree_dropdown_bloc.dart @@ -24,4 +24,4 @@ class SpaceTreeDropdownBloc ) { emit(SpaceTreeDropdownState(selectedSpaceId: event.initialId)); } -} \ No newline at end of file +} diff --git a/lib/pages/routines/create_new_routines/space_tree_dropdown_event.dart b/lib/pages/routines/create_new_routines/space_tree_dropdown_event.dart index dec701dc..69cf3d3f 100644 --- a/lib/pages/routines/create_new_routines/space_tree_dropdown_event.dart +++ b/lib/pages/routines/create_new_routines/space_tree_dropdown_event.dart @@ -12,4 +12,4 @@ class SpaceTreeDropdownResetEvent extends SpaceTreeDropdownEvent { final String? initialId; SpaceTreeDropdownResetEvent(this.initialId); -} \ No newline at end of file +} diff --git a/lib/pages/routines/create_new_routines/space_tree_dropdown_state.dart b/lib/pages/routines/create_new_routines/space_tree_dropdown_state.dart index dd22d095..c815da17 100644 --- a/lib/pages/routines/create_new_routines/space_tree_dropdown_state.dart +++ b/lib/pages/routines/create_new_routines/space_tree_dropdown_state.dart @@ -4,4 +4,4 @@ class SpaceTreeDropdownState { final String? selectedSpaceId; SpaceTreeDropdownState({this.selectedSpaceId}); -} \ No newline at end of file +} diff --git a/lib/pages/routines/helper/save_routine_helper.dart b/lib/pages/routines/helper/save_routine_helper.dart index f8b52dab..2b506620 100644 --- a/lib/pages/routines/helper/save_routine_helper.dart +++ b/lib/pages/routines/helper/save_routine_helper.dart @@ -17,9 +17,10 @@ class SaveRoutineHelper { builder: (context) { return BlocBuilder( builder: (context, state) { - final selectedConditionLabel = state.selectedAutomationOperator == 'and' - ? 'All Conditions are met' - : 'Any Condition is met'; + final selectedConditionLabel = + state.selectedAutomationOperator == 'and' + ? 'All Conditions are met' + : 'Any Condition is met'; return AlertDialog( contentPadding: EdgeInsets.zero, @@ -37,10 +38,11 @@ class SaveRoutineHelper { Text( 'Create a scene: ${state.routineName ?? ""}', textAlign: TextAlign.center, - style: Theme.of(context).textTheme.headlineMedium!.copyWith( - color: ColorsManager.primaryColorWithOpacity, - fontWeight: FontWeight.bold, - ), + style: + Theme.of(context).textTheme.headlineMedium!.copyWith( + color: ColorsManager.primaryColorWithOpacity, + fontWeight: FontWeight.bold, + ), ), const SizedBox(height: 18), _buildDivider(), @@ -58,7 +60,8 @@ class SaveRoutineHelper { _buildIfConditions(state, context), Container( width: 1, - color: ColorsManager.greyColor.withValues(alpha: 0.8), + color: ColorsManager.greyColor + .withValues(alpha: 0.8), ), _buildThenActions(state, context), ], @@ -97,7 +100,8 @@ class SaveRoutineHelper { child: Row( spacing: 16, children: [ - Expanded(child: Text('IF: $selectedConditionLabel', style: textStyle)), + Expanded( + child: Text('IF: $selectedConditionLabel', style: textStyle)), const Expanded(child: Text('THEN:', style: textStyle)), ], ), @@ -109,7 +113,7 @@ class SaveRoutineHelper { spacing: 16, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - DialogFooterButton( + DialogFooterButton( text: 'Back', onTap: () => Navigator.pop(context), ), @@ -143,7 +147,8 @@ class SaveRoutineHelper { child: ListView( // shrinkWrap: true, children: state.thenItems.map((item) { - final functions = state.selectedFunctions[item['uniqueCustomId']] ?? []; + final functions = + state.selectedFunctions[item['uniqueCustomId']] ?? []; return functionRow(item, context, functions); }).toList(), ), @@ -203,19 +208,20 @@ class SaveRoutineHelper { ), ), child: Center( - child: item['type'] == 'tap_to_run' || item['type'] == 'scene' - ? Image.memory( - base64Decode(item['icon']), - width: 12, - height: 22, - fit: BoxFit.scaleDown, - ) - : SvgPicture.asset( - item['imagePath'], - width: 12, - height: 12, - fit: BoxFit.scaleDown, - ), + child: + item['type'] == 'tap_to_run' || item['type'] == 'scene' + ? Image.memory( + base64Decode(item['icon']), + width: 12, + height: 22, + fit: BoxFit.scaleDown, + ) + : SvgPicture.asset( + item['imagePath'], + width: 12, + height: 12, + fit: BoxFit.scaleDown, + ), ), ), Flexible( diff --git a/lib/pages/routines/models/ac/ac_function.dart b/lib/pages/routines/models/ac/ac_function.dart index edc377dd..e92b6dee 100644 --- a/lib/pages/routines/models/ac/ac_function.dart +++ b/lib/pages/routines/models/ac/ac_function.dart @@ -37,12 +37,12 @@ class SwitchFunction extends ACFunction { List getOperationalValues() => [ ACOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), ACOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -62,17 +62,17 @@ class ModeFunction extends ACFunction { List getOperationalValues() => [ ACOperationalValue( icon: Assets.assetsAcCooling, - description: "Cooling", + description: 'Cooling', value: TempModes.cold.name, ), ACOperationalValue( icon: Assets.assetsAcHeating, - description: "Heating", + description: 'Heating', value: TempModes.hot.name, ), ACOperationalValue( icon: Assets.assetsFanSpeed, - description: "Ventilation", + description: 'Ventilation', value: TempModes.wind.name, ), ]; @@ -90,22 +90,23 @@ class TempSetFunction extends ACFunction { min: 200, max: 300, step: 1, - unit: "°C", + unit: '°C', ); @override List getOperationalValues() { - List values = []; - for (int temp = min!.toInt(); temp <= max!; temp += step!.toInt()) { + final values = []; + for (var temp = min!.toInt(); temp <= max!; temp += step!.toInt()) { values.add(ACOperationalValue( icon: Assets.assetsTempreture, - description: "${temp / 10}°C", + description: '${temp / 10}°C', value: temp, )); } return values; } } + class LevelFunction extends ACFunction { LevelFunction( {required super.deviceId, required super.deviceName, required type}) @@ -120,22 +121,22 @@ class LevelFunction extends ACFunction { List getOperationalValues() => [ ACOperationalValue( icon: Assets.assetsAcFanLow, - description: "LOW", + description: 'LOW', value: FanSpeeds.low.name, ), ACOperationalValue( icon: Assets.assetsAcFanMiddle, - description: "MIDDLE", + description: 'MIDDLE', value: FanSpeeds.middle.name, ), ACOperationalValue( icon: Assets.assetsAcFanHigh, - description: "HIGH", + description: 'HIGH', value: FanSpeeds.high.name, ), ACOperationalValue( icon: Assets.assetsAcFanAuto, - description: "AUTO", + description: 'AUTO', value: FanSpeeds.auto.name, ), ]; @@ -155,22 +156,26 @@ class ChildLockFunction extends ACFunction { List getOperationalValues() => [ ACOperationalValue( icon: Assets.assetsSceneChildLock, - description: "Lock", + description: 'Lock', value: true, ), ACOperationalValue( icon: Assets.assetsSceneChildUnlock, - description: "Unlock", + description: 'Unlock', value: false, ), ]; } class CurrentTempFunction extends ACFunction { + @override final double min; + @override final double max; + @override final double step; - final String unit = "°C"; + @override + final String unit = '°C'; CurrentTempFunction( {required super.deviceId, required super.deviceName, required type}) @@ -186,11 +191,11 @@ class CurrentTempFunction extends ACFunction { @override List getOperationalValues() { - List values = []; - for (int temp = min.toInt(); temp <= max; temp += step.toInt()) { + final values = []; + for (var temp = min.toInt(); temp <= max; temp += step.toInt()) { values.add(ACOperationalValue( icon: Assets.currentTemp, - description: "${temp / 10}°C", + description: '${temp / 10}°C', value: temp, )); } diff --git a/lib/pages/routines/models/ceiling_presence_sensor_functions.dart b/lib/pages/routines/models/ceiling_presence_sensor_functions.dart index 122d8ea1..f364abdb 100644 --- a/lib/pages/routines/models/ceiling_presence_sensor_functions.dart +++ b/lib/pages/routines/models/ceiling_presence_sensor_functions.dart @@ -6,12 +6,10 @@ class CpsOperationalValue { final String description; final dynamic value; - CpsOperationalValue({ required this.icon, required this.description, required this.value, - }); } @@ -45,12 +43,12 @@ final class CpsRadarSwitchFunction extends CpsFunctions { List getOperationalValues() => [ CpsOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), CpsOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -71,12 +69,12 @@ final class CpsSpatialParameterSwitchFunction extends CpsFunctions { List getOperationalValues() => [ CpsOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), CpsOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -96,8 +94,11 @@ final class CpsSensitivityFunction extends CpsFunctions { icon: Assets.sensitivity, ); + @override final double min; + @override final double max; + @override final double step; static const _images = [ @@ -144,8 +145,11 @@ final class CpsMovingSpeedFunction extends CpsFunctions { icon: Assets.speedoMeter, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -175,8 +179,11 @@ final class CpsSpatialStaticValueFunction extends CpsFunctions { icon: Assets.spatialStaticValue, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -206,8 +213,11 @@ final class CpsSpatialMotionValueFunction extends CpsFunctions { icon: Assets.spatialMotionValue, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -237,8 +247,11 @@ final class CpsMaxDistanceOfDetectionFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -247,7 +260,7 @@ final class CpsMaxDistanceOfDetectionFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.currentDistanceIcon, description: '${value.toStringAsFixed(1)} M', @@ -272,8 +285,11 @@ final class CpsMaxDistanceOfStaticDetectionFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -282,7 +298,7 @@ final class CpsMaxDistanceOfStaticDetectionFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.currentDistanceIcon, description: '${value.toStringAsFixed(1)} M', @@ -307,8 +323,11 @@ final class CpsDetectionRangeFunction extends CpsFunctions { icon: Assets.farDetection, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -317,7 +336,7 @@ final class CpsDetectionRangeFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.farDetection, description: '${value.toStringAsFixed(1)} M', @@ -342,8 +361,11 @@ final class CpsDistanceOfMovingObjectsFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -352,7 +374,7 @@ final class CpsDistanceOfMovingObjectsFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.currentDistanceIcon, description: '${value.toStringAsFixed(1)} M', @@ -377,8 +399,11 @@ final class CpsPresenceJudgementThrsholdFunction extends CpsFunctions { icon: Assets.presenceJudgementThrshold, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -408,8 +433,11 @@ final class CpsMotionAmplitudeTriggerThresholdFunction extends CpsFunctions { icon: Assets.presenceJudgementThrshold, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -439,8 +467,11 @@ final class CpsPerpetualBoundaryFunction extends CpsFunctions { icon: Assets.boundary, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -449,7 +480,7 @@ final class CpsPerpetualBoundaryFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.boundary, description: '${value.toStringAsFixed(1)}M', @@ -474,8 +505,11 @@ final class CpsMotionTriggerBoundaryFunction extends CpsFunctions { icon: Assets.motionMeter, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -484,7 +518,7 @@ final class CpsMotionTriggerBoundaryFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.motionMeter, description: '${value.toStringAsFixed(1)} M', @@ -509,8 +543,11 @@ final class CpsMotionTriggerTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -519,7 +556,7 @@ final class CpsMotionTriggerTimeFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.motionMeter, description: '${value.toStringAsFixed(3)} sec', @@ -544,8 +581,11 @@ final class CpsMotionToStaticTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -554,7 +594,7 @@ final class CpsMotionToStaticTimeFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.motionMeter, description: '${value.toStringAsFixed(0)} sec', @@ -579,8 +619,11 @@ final class CpsEnteringNoBodyStateTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -589,7 +632,7 @@ final class CpsEnteringNoBodyStateTimeFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.motionMeter, description: '${value.toStringAsFixed(0)} sec', @@ -869,8 +912,11 @@ final class CpsSportsParaFunction extends CpsFunctions { icon: Assets.sportsPara, ); + @override final double min; + @override final double max; + @override final double step; @override @@ -879,7 +925,7 @@ final class CpsSportsParaFunction extends CpsFunctions { return List.generate( count, (index) { - final value = (min + (index * step)); + final value = min + (index * step); return CpsOperationalValue( icon: Assets.motionMeter, description: value.toStringAsFixed(0), diff --git a/lib/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart b/lib/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart index 81ee1096..835d8886 100644 --- a/lib/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart +++ b/lib/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart @@ -112,7 +112,7 @@ class CreateSceneAction { CreateSceneExecutorProperty? executorProperty, }) { return CreateSceneAction( - actionType: actionType ?? this.actionType, + actionType: actionType ?? actionType, entityId: entityId ?? this.entityId, actionExecutor: actionExecutor ?? this.actionExecutor, executorProperty: executorProperty ?? this.executorProperty, @@ -128,7 +128,7 @@ class CreateSceneAction { }; } else { return { - "actionType": actionType, + 'actionType': actionType, 'entityId': entityId, 'actionExecutor': actionExecutor, }; diff --git a/lib/pages/routines/models/delay/delay_fucntions.dart b/lib/pages/routines/models/delay/delay_fucntions.dart index 428825f4..28c87a25 100644 --- a/lib/pages/routines/models/delay/delay_fucntions.dart +++ b/lib/pages/routines/models/delay/delay_fucntions.dart @@ -14,7 +14,7 @@ class DelayFunction extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "Duration in seconds", + description: 'Duration in seconds', value: 0.0, minValue: 0, maxValue: 43200, diff --git a/lib/pages/routines/models/flush/flush_functions.dart b/lib/pages/routines/models/flush/flush_functions.dart index a8f6ccd4..6f4b01a6 100644 --- a/lib/pages/routines/models/flush/flush_functions.dart +++ b/lib/pages/routines/models/flush/flush_functions.dart @@ -24,8 +24,7 @@ class FlushPresenceDelayFunction extends FlushFunctions { required super.deviceId, required super.deviceName, required super.type, - }) : - super( + }) : super( code: FlushMountedPresenceSensorModel.codePresenceState, operationName: 'Presence State', icon: Assets.presenceStateIcon, @@ -37,7 +36,7 @@ class FlushPresenceDelayFunction extends FlushFunctions { FlushOperationalValue( icon: Assets.nobodyTime, description: 'None', - value: "none", + value: 'none', ), FlushOperationalValue( icon: Assets.presenceStateIcon, @@ -49,8 +48,11 @@ class FlushPresenceDelayFunction extends FlushFunctions { } class FlushSensiReduceFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; FlushSensiReduceFunction({ @@ -79,8 +81,11 @@ class FlushSensiReduceFunction extends FlushFunctions { } class FlushNoneDelayFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final String unit; FlushNoneDelayFunction({ @@ -109,8 +114,11 @@ class FlushNoneDelayFunction extends FlushFunctions { } class FlushIlluminanceFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; FlushIlluminanceFunction({ @@ -128,11 +136,11 @@ class FlushIlluminanceFunction extends FlushFunctions { @override List getOperationalValues() { - List values = []; - for (int lux = min.toInt(); lux <= max; lux += step.toInt()) { + final values = []; + for (var lux = min.toInt(); lux <= max; lux += step.toInt()) { values.add(FlushOperationalValue( icon: Assets.IlluminanceIcon, - description: "$lux Lux", + description: '$lux Lux', value: lux, )); } @@ -141,8 +149,11 @@ class FlushIlluminanceFunction extends FlushFunctions { } class FlushOccurDistReduceFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; FlushOccurDistReduceFunction({ @@ -172,8 +183,11 @@ class FlushOccurDistReduceFunction extends FlushFunctions { // ==== then functions ==== class FlushSensitivityFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; FlushSensitivityFunction({ @@ -202,9 +216,13 @@ class FlushSensitivityFunction extends FlushFunctions { } class FlushNearDetectionFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushNearDetectionFunction({ @@ -224,7 +242,7 @@ class FlushNearDetectionFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min.toDouble(); value <= max; value += step) { + for (var value = min; value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -236,9 +254,13 @@ class FlushNearDetectionFunction extends FlushFunctions { } class FlushMaxDetectDistFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushMaxDetectDistFunction({ @@ -270,9 +292,13 @@ class FlushMaxDetectDistFunction extends FlushFunctions { } class FlushTargetConfirmTimeFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushTargetConfirmTimeFunction({ @@ -292,7 +318,7 @@ class FlushTargetConfirmTimeFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min.toDouble(); value <= max; value += step) { + for (var value = min; value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -304,9 +330,13 @@ class FlushTargetConfirmTimeFunction extends FlushFunctions { } class FlushDisappeDelayFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushDisappeDelayFunction({ @@ -326,7 +356,7 @@ class FlushDisappeDelayFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min.toDouble(); value <= max; value += step) { + for (var value = min; value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -338,9 +368,13 @@ class FlushDisappeDelayFunction extends FlushFunctions { } class FlushIndentLevelFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushIndentLevelFunction({ @@ -360,7 +394,7 @@ class FlushIndentLevelFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min.toDouble(); value <= max; value += step) { + for (var value = min; value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -372,9 +406,13 @@ class FlushIndentLevelFunction extends FlushFunctions { } class FlushTriggerLevelFunction extends FlushFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; FlushTriggerLevelFunction({ @@ -394,7 +432,7 @@ class FlushTriggerLevelFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min.toDouble(); value <= max; value += step) { + for (var value = min; value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', diff --git a/lib/pages/routines/models/gang_switches/one_gang_switch/one_gang_switch.dart b/lib/pages/routines/models/gang_switches/one_gang_switch/one_gang_switch.dart index 9451f89f..78d32069 100644 --- a/lib/pages/routines/models/gang_switches/one_gang_switch/one_gang_switch.dart +++ b/lib/pages/routines/models/gang_switches/one_gang_switch/one_gang_switch.dart @@ -14,12 +14,12 @@ class OneGangSwitchFunction extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -37,7 +37,7 @@ class OneGangCountdownFunction extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, diff --git a/lib/pages/routines/models/gang_switches/three_gang_switch/three_gang_switch.dart b/lib/pages/routines/models/gang_switches/three_gang_switch/three_gang_switch.dart index 9bdd30b4..eee0019d 100644 --- a/lib/pages/routines/models/gang_switches/three_gang_switch/three_gang_switch.dart +++ b/lib/pages/routines/models/gang_switches/three_gang_switch/three_gang_switch.dart @@ -3,8 +3,11 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operation import 'package:syncrow_web/utils/constants/assets.dart'; class ThreeGangSwitch1Function extends BaseSwitchFunction { - ThreeGangSwitch1Function({required super.deviceId, required super.deviceName ,required type}) - : super( + ThreeGangSwitch1Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'switch_1', operationName: 'Light 1 Switch', icon: Assets.assetsAcPower, @@ -14,20 +17,23 @@ class ThreeGangSwitch1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; } class ThreeGangCountdown1Function extends BaseSwitchFunction { - ThreeGangCountdown1Function({required super.deviceId, required super.deviceName ,required type}) - : super( + ThreeGangCountdown1Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'countdown_1', operationName: 'Light 1 Countdown', icon: Assets.assetsLightCountdown, @@ -37,7 +43,7 @@ class ThreeGangCountdown1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, @@ -47,8 +53,11 @@ class ThreeGangCountdown1Function extends BaseSwitchFunction { } class ThreeGangSwitch2Function extends BaseSwitchFunction { - ThreeGangSwitch2Function({required super.deviceId, required super.deviceName, required type}) - : super( + ThreeGangSwitch2Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'switch_2', operationName: 'Light 2 Switch', icon: Assets.assetsAcPower, @@ -58,20 +67,23 @@ class ThreeGangSwitch2Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; } class ThreeGangCountdown2Function extends BaseSwitchFunction { - ThreeGangCountdown2Function({required super.deviceId, required super.deviceName ,required type}) - : super( + ThreeGangCountdown2Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'countdown_2', operationName: 'Light 2 Countdown', icon: Assets.assetsLightCountdown, @@ -81,7 +93,7 @@ class ThreeGangCountdown2Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, @@ -91,8 +103,11 @@ class ThreeGangCountdown2Function extends BaseSwitchFunction { } class ThreeGangSwitch3Function extends BaseSwitchFunction { - ThreeGangSwitch3Function({required super.deviceId, required super.deviceName ,required type}) - : super( + ThreeGangSwitch3Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'switch_3', operationName: 'Light 3 Switch', icon: Assets.assetsAcPower, @@ -102,20 +117,23 @@ class ThreeGangSwitch3Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; } class ThreeGangCountdown3Function extends BaseSwitchFunction { - ThreeGangCountdown3Function({required super.deviceId, required super.deviceName ,required type}) - : super( + ThreeGangCountdown3Function({ + required super.deviceId, + required super.deviceName, + required String type, + }) : super( code: 'countdown_3', operationName: 'Light 3 Countdown', icon: Assets.assetsLightCountdown, @@ -125,7 +143,7 @@ class ThreeGangCountdown3Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, diff --git a/lib/pages/routines/models/gang_switches/two_gang_switch/two_gang_switch.dart b/lib/pages/routines/models/gang_switches/two_gang_switch/two_gang_switch.dart index 95de1122..a5f78436 100644 --- a/lib/pages/routines/models/gang_switches/two_gang_switch/two_gang_switch.dart +++ b/lib/pages/routines/models/gang_switches/two_gang_switch/two_gang_switch.dart @@ -14,12 +14,12 @@ class TwoGangSwitch1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -37,19 +37,20 @@ class TwoGangSwitch2Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), SwitchOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; } class TwoGangCountdown1Function extends BaseSwitchFunction { - TwoGangCountdown1Function({required super.deviceId, required super.deviceName}) + TwoGangCountdown1Function( + {required super.deviceId, required super.deviceName}) : super( code: 'countdown_1', operationName: 'Light 1 Countdown', @@ -60,7 +61,7 @@ class TwoGangCountdown1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, @@ -70,7 +71,8 @@ class TwoGangCountdown1Function extends BaseSwitchFunction { } class TwoGangCountdown2Function extends BaseSwitchFunction { - TwoGangCountdown2Function({required super.deviceId, required super.deviceName}) + TwoGangCountdown2Function( + {required super.deviceId, required super.deviceName}) : super( code: 'countdown_2', operationName: 'Light 2 Countdown', @@ -81,7 +83,7 @@ class TwoGangCountdown2Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: "sec", + description: 'sec', value: 0.0, minValue: 0, maxValue: 43200, diff --git a/lib/pages/routines/models/gateway.dart b/lib/pages/routines/models/gateway.dart index b1a70d2e..06dc6f52 100644 --- a/lib/pages/routines/models/gateway.dart +++ b/lib/pages/routines/models/gateway.dart @@ -13,7 +13,8 @@ class GatewayOperationalValue { }); } -abstract class GatewayFunctions extends DeviceFunction { +abstract class GatewayFunctions + extends DeviceFunction { final String type; GatewayFunctions({ @@ -43,12 +44,12 @@ final class GatewaySwitchAlarmSound extends GatewayFunctions { List getOperationalValues() => [ GatewayOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), GatewayOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; @@ -70,12 +71,12 @@ final class GatewayMasterState extends GatewayFunctions { return [ GatewayOperationalValue( icon: Assets.assetsAcPower, - description: "Normal", + description: 'Normal', value: 'normal', ), GatewayOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "Alarm", + description: 'Alarm', value: 'alarm', ), ]; @@ -98,12 +99,12 @@ final class GatewayFactoryReset extends GatewayFunctions { return [ GatewayOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), GatewayOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; diff --git a/lib/pages/routines/models/pc/energy_clamp_functions.dart b/lib/pages/routines/models/pc/energy_clamp_functions.dart index 4bf3ddd8..5945faa4 100644 --- a/lib/pages/routines/models/pc/energy_clamp_functions.dart +++ b/lib/pages/routines/models/pc/energy_clamp_functions.dart @@ -35,7 +35,7 @@ class TotalEnergyConsumedStatusFunction extends EnergyClampFunctions { min: 0.00, max: 20000000.00, step: 1, - unit: "kWh", + unit: 'kWh', ); @override @@ -54,7 +54,7 @@ class TotalActivePowerConsumedStatusFunction extends EnergyClampFunctions { min: -19800000, max: 19800000, step: 0.1, - unit: "kW", + unit: 'kW', ); @override @@ -101,7 +101,7 @@ class TotalCurrentStatusFunction extends EnergyClampFunctions { min: 0.000, max: 9000.000, step: 1, - unit: "A", + unit: 'A', ); @override @@ -120,7 +120,7 @@ class FrequencyStatusFunction extends EnergyClampFunctions { min: 0, max: 80, step: 1, - unit: "Hz", + unit: 'Hz', ); @override @@ -140,7 +140,7 @@ class EnergyConsumedAStatusFunction extends EnergyClampFunctions { min: 0.00, max: 20000000.00, step: 1, - unit: "kWh", + unit: 'kWh', ); @override @@ -159,7 +159,7 @@ class ActivePowerAStatusFunction extends EnergyClampFunctions { min: 200, max: 300, step: 1, - unit: "kW", + unit: 'kW', ); @override @@ -178,7 +178,7 @@ class VoltageAStatusFunction extends EnergyClampFunctions { min: 0.0, max: 500, step: 1, - unit: "V", + unit: 'V', ); @override @@ -197,7 +197,7 @@ class PowerFactorAStatusFunction extends EnergyClampFunctions { min: 0.00, max: 1.00, step: 0.1, - unit: "", + unit: '', ); @override @@ -216,7 +216,7 @@ class CurrentAStatusFunction extends EnergyClampFunctions { min: 0.000, max: 3000.000, step: 1, - unit: "A", + unit: 'A', ); @override @@ -236,7 +236,7 @@ class EnergyConsumedBStatusFunction extends EnergyClampFunctions { min: 0.00, max: 20000000.00, step: 1, - unit: "kWh", + unit: 'kWh', ); @override @@ -255,7 +255,7 @@ class ActivePowerBStatusFunction extends EnergyClampFunctions { min: -6600000, max: 6600000, step: 1, - unit: "kW", + unit: 'kW', ); @override @@ -274,7 +274,7 @@ class VoltageBStatusFunction extends EnergyClampFunctions { min: 0.0, max: 500, step: 1, - unit: "V", + unit: 'V', ); @override @@ -293,7 +293,7 @@ class CurrentBStatusFunction extends EnergyClampFunctions { min: 0.000, max: 3000.000, step: 1, - unit: "A", + unit: 'A', ); @override @@ -312,7 +312,7 @@ class PowerFactorBStatusFunction extends EnergyClampFunctions { min: 0.0, max: 1.0, step: 0.1, - unit: "", + unit: '', ); @override @@ -332,7 +332,7 @@ class EnergyConsumedCStatusFunction extends EnergyClampFunctions { min: 0.00, max: 20000000.00, step: 1, - unit: "kWh", + unit: 'kWh', ); @override @@ -351,7 +351,7 @@ class ActivePowerCStatusFunction extends EnergyClampFunctions { min: -6600000, max: 6600000, step: 1, - unit: "kW", + unit: 'kW', ); @override @@ -370,7 +370,7 @@ class VoltageCStatusFunction extends EnergyClampFunctions { min: 0.00, max: 500, step: 0.1, - unit: "V", + unit: 'V', ); @override @@ -389,7 +389,7 @@ class CurrentCStatusFunction extends EnergyClampFunctions { min: 0.000, max: 3000.000, step: 0.1, - unit: "A", + unit: 'A', ); @override @@ -408,7 +408,7 @@ class PowerFactorCStatusFunction extends EnergyClampFunctions { min: 0.00, max: 1.00, step: 0.1, - unit: "", + unit: '', ); @override diff --git a/lib/pages/routines/models/routine_details_model.dart b/lib/pages/routines/models/routine_details_model.dart index c42b4d36..364a5bec 100644 --- a/lib/pages/routines/models/routine_details_model.dart +++ b/lib/pages/routines/models/routine_details_model.dart @@ -48,7 +48,8 @@ class RoutineDetailsModel { spaceUuid: spaceUuid, automationName: name, decisionExpr: decisionExpr, - effectiveTime: effectiveTime ?? EffectiveTime(start: '', end: '', loops: ''), + effectiveTime: + effectiveTime ?? EffectiveTime(start: '', end: '', loops: ''), conditions: conditions?.map((c) => c.toCondition()).toList() ?? [], actions: actions.map((a) => a.toAutomationAction()).toList(), ); @@ -63,7 +64,8 @@ class RoutineDetailsModel { if (iconId != null) 'iconUuid': iconId, if (showInDevice != null) 'showInDevice': showInDevice, if (effectiveTime != null) 'effectiveTime': effectiveTime!.toMap(), - if (conditions != null) 'conditions': conditions!.map((x) => x.toMap()).toList(), + if (conditions != null) + 'conditions': conditions!.map((x) => x.toMap()).toList(), if (type != null) 'type': type, if (sceneId != null) 'sceneId': sceneId, if (automationId != null) 'automationId': automationId, @@ -80,10 +82,12 @@ class RoutineDetailsModel { ), iconId: map['iconUuid'], showInDevice: map['showInDevice'], - effectiveTime: - map['effectiveTime'] != null ? EffectiveTime.fromMap(map['effectiveTime']) : null, + effectiveTime: map['effectiveTime'] != null + ? EffectiveTime.fromMap(map['effectiveTime']) + : null, conditions: map['conditions'] != null - ? List.from(map['conditions'].map((x) => RoutineCondition.fromMap(x))) + ? List.from( + map['conditions'].map((x) => RoutineCondition.fromMap(x))) : null, type: map['type'], sceneId: map['sceneId'], @@ -137,7 +141,8 @@ class RoutineAction { 'actionExecutor': actionExecutor, if (type != null) 'type': type, if (name != null) 'name': name, - if (executorProperty != null) 'executorProperty': executorProperty!.toMap(), + if (executorProperty != null) + 'executorProperty': executorProperty!.toMap(), }; } diff --git a/lib/pages/routines/models/routine_model.dart b/lib/pages/routines/models/routine_model.dart index 2f7c2a24..d1d3cdcd 100644 --- a/lib/pages/routines/models/routine_model.dart +++ b/lib/pages/routines/models/routine_model.dart @@ -42,27 +42,27 @@ class ScenesModel { factory ScenesModel.fromJson(Map json, {bool? isAutomation}) { return ScenesModel( - id: json["id"] ?? json["uuid"] ?? '', - sceneTuyaId: json["sceneTuyaId"] as String?, - name: json["name"] ?? '', - status: json["status"] ?? '', - type: json["type"] ?? '', - spaceName: json["spaceName"] ?? '', - spaceId: json["spaceId"] ?? '', - communityId: json["communityId"] ?? '', + id: json['id'] ?? json['uuid'] ?? '', + sceneTuyaId: json['sceneTuyaId'] as String?, + name: json['name'] ?? '', + status: json['status'] ?? '', + type: json['type'] ?? '', + spaceName: json['spaceName'] ?? '', + spaceId: json['spaceId'] ?? '', + communityId: json['communityId'] ?? '', icon: - isAutomation == true ? Assets.automation : (json["icon"] as String?), + isAutomation == true ? Assets.automation : (json['icon'] as String?), ); } Map toJson() => { - "id": id, - "sceneTuyaId": sceneTuyaId ?? '', - "name": name, - "status": status, - "type": type, - "spaceName": spaceName, - "spaceId": spaceId, - "communityId": communityId, + 'id': id, + 'sceneTuyaId': sceneTuyaId ?? '', + 'name': name, + 'status': status, + 'type': type, + 'spaceName': spaceName, + 'spaceId': spaceId, + 'communityId': communityId, }; } diff --git a/lib/pages/routines/models/water_heater/water_heater_functions.dart b/lib/pages/routines/models/water_heater/water_heater_functions.dart index 7ebea019..6c76a41d 100644 --- a/lib/pages/routines/models/water_heater/water_heater_functions.dart +++ b/lib/pages/routines/models/water_heater/water_heater_functions.dart @@ -29,7 +29,6 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { operationName: 'Restart Status', icon: Assets.refreshStatusIcon, ); - @override List getOperationalValues() { @@ -37,7 +36,7 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { WaterHeaterOperationalValue( icon: Assets.assetsAcPowerOFF, description: 'Power OFF', - value: "off", + value: 'off', ), WaterHeaterOperationalValue( icon: Assets.assetsAcPower, @@ -46,7 +45,7 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { ), WaterHeaterOperationalValue( icon: Assets.refreshStatusIcon, - description: "Restart Memory", + description: 'Restart Memory', value: 'memory', ), ]; @@ -105,8 +104,7 @@ class BacklightFunction extends WaterHeaterFunctions { required super.deviceId, required super.deviceName, required super.type, - }) : - super( + }) : super( code: 'switch_backlight', operationName: 'Backlight', icon: Assets.indicator, diff --git a/lib/pages/routines/models/wps/wps_functions.dart b/lib/pages/routines/models/wps/wps_functions.dart index 101c5cf0..3eae35a8 100644 --- a/lib/pages/routines/models/wps/wps_functions.dart +++ b/lib/pages/routines/models/wps/wps_functions.dart @@ -24,11 +24,11 @@ abstract class WpsFunctions extends DeviceFunction { // For far_detection (75-600cm in 75cm steps) class FarDetectionFunction extends WpsFunctions { - + @override final double min; - @override + @override final double max; - @override + @override final double step; @override final String unit; @@ -62,9 +62,13 @@ class FarDetectionFunction extends WpsFunctions { // For presence_time (0-65535 minutes) class PresenceTimeFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final double step; + @override final String unit; PresenceTimeFunction( @@ -94,8 +98,11 @@ class PresenceTimeFunction extends WpsFunctions { // For motion_sensitivity_value (1-5 levels) class MotionSensitivityFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final double step; MotionSensitivityFunction( @@ -124,8 +131,11 @@ class MotionSensitivityFunction extends WpsFunctions { } class MotionLessSensitivityFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final double step; MotionLessSensitivityFunction( @@ -167,20 +177,23 @@ class IndicatorFunction extends WpsFunctions { List getOperationalValues() => [ WpsOperationalValue( icon: Assets.assetsAcPower, - description: "ON", + description: 'ON', value: true, ), WpsOperationalValue( icon: Assets.assetsAcPowerOFF, - description: "OFF", + description: 'OFF', value: false, ), ]; } class NoOneTimeFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final String unit; NoOneTimeFunction( @@ -221,20 +234,23 @@ class PresenceStateFunction extends WpsFunctions { List getOperationalValues() => [ WpsOperationalValue( icon: Assets.assetsAcPower, - description: "None", + description: 'None', value: 'none', ), WpsOperationalValue( icon: Assets.presenceStateIcon, - description: "Presence", + description: 'Presence', value: 'presence', ), ]; } class CurrentDistanceFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final double step; CurrentDistanceFunction( @@ -251,11 +267,11 @@ class CurrentDistanceFunction extends WpsFunctions { @override List getOperationalValues() { - List values = []; - for (int cm = min.toInt(); cm <= max; cm += step.toInt()) { + final values = []; + for (var cm = min.toInt(); cm <= max; cm += step.toInt()) { values.add(WpsOperationalValue( icon: Assets.assetsTempreture, - description: "${cm}CM", + description: '${cm}CM', value: cm, )); } @@ -264,8 +280,11 @@ class CurrentDistanceFunction extends WpsFunctions { } class IlluminanceValueFunction extends WpsFunctions { + @override final double min; + @override final double max; + @override final double step; IlluminanceValueFunction({ @@ -283,11 +302,11 @@ class IlluminanceValueFunction extends WpsFunctions { @override List getOperationalValues() { - List values = []; - for (int lux = min.toInt(); lux <= max; lux += step.toInt()) { + final values = []; + for (var lux = min.toInt(); lux <= max; lux += step.toInt()) { values.add(WpsOperationalValue( icon: Assets.IlluminanceIcon, - description: "$lux Lux", + description: '$lux Lux', value: lux, )); } diff --git a/lib/pages/routines/view/effective_period_view.dart b/lib/pages/routines/view/effective_period_view.dart index b54e4075..8369d790 100644 --- a/lib/pages/routines/view/effective_period_view.dart +++ b/lib/pages/routines/view/effective_period_view.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart'; import 'package:syncrow_web/pages/routines/widgets/period_option.dart'; import 'package:syncrow_web/pages/routines/widgets/repeat_days.dart'; +import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart'; import 'package:syncrow_web/utils/color_manager.dart'; class EffectivePeriodView extends StatelessWidget { diff --git a/lib/pages/routines/view/routines_view.dart b/lib/pages/routines/view/routines_view.dart index f46ef15f..51176419 100644 --- a/lib/pages/routines/view/routines_view.dart +++ b/lib/pages/routines/view/routines_view.dart @@ -19,7 +19,7 @@ class RoutinesView extends StatefulWidget { } class _RoutinesViewState extends State { - void _handleRoutineCreation(BuildContext context) async { + Future _handleRoutineCreation(BuildContext context) async { final result = await showDialog>( context: context, builder: (context) => const CreateNewRoutinesDialog(), @@ -69,7 +69,7 @@ class _RoutinesViewState extends State { spacing: 16, children: [ Text( - "Create New Routines", + 'Create New Routines', style: Theme.of(context).textTheme.titleLarge?.copyWith( color: ColorsManager.grayColor, diff --git a/lib/pages/routines/widgets/condition_toggle.dart b/lib/pages/routines/widgets/condition_toggle.dart index 541ad431..8a26db83 100644 --- a/lib/pages/routines/widgets/condition_toggle.dart +++ b/lib/pages/routines/widgets/condition_toggle.dart @@ -11,8 +11,8 @@ class ConditionToggle extends StatelessWidget { super.key, }); - static const _conditions = ["<", "==", ">"]; - static const _icons = [ + static const _conditions = ['<', '==', '>']; + static const List _icons = [ Icons.chevron_left, Icons.drag_handle, Icons.chevron_right @@ -20,13 +20,13 @@ class ConditionToggle extends StatelessWidget { @override Widget build(BuildContext context) { - final selectedIndex = _conditions.indexOf(currentCondition ?? "=="); + final selectedIndex = _conditions.indexOf(currentCondition ?? '=='); return Container( height: 30, width: MediaQuery.of(context).size.width * 0.1, decoration: BoxDecoration( - color: ColorsManager.softGray.withOpacity(0.5), + color: ColorsManager.softGray.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(50), ), clipBehavior: Clip.antiAlias, diff --git a/lib/pages/routines/widgets/custom_routines_textbox.dart b/lib/pages/routines/widgets/custom_routines_textbox.dart index f0767df4..f7ceda8f 100644 --- a/lib/pages/routines/widgets/custom_routines_textbox.dart +++ b/lib/pages/routines/widgets/custom_routines_textbox.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:syncrow_web/pages/routines/widgets/condition_toggle.dart'; @@ -45,10 +46,10 @@ class _CustomRoutinesTextboxState extends State { String? errorMessage; int getDecimalPlaces(double step) { - String stepStr = step.toString(); + final stepStr = step.toString(); if (stepStr.contains('.')) { - List parts = stepStr.split('.'); - String decimalPart = parts[1]; + final parts = stepStr.split('.'); + var decimalPart = parts[1]; decimalPart = decimalPart.replaceAll(RegExp(r'0+$'), ''); return decimalPart.isEmpty ? 0 : decimalPart.length; } else { @@ -111,13 +112,11 @@ class _CustomRoutinesTextboxState extends State { } } - - void _validateInput(String value) { final doubleValue = double.tryParse(value); if (doubleValue == null) { setState(() { - errorMessage = "Invalid number"; + errorMessage = 'Invalid number'; hasError = true; }); return; @@ -128,23 +127,23 @@ class _CustomRoutinesTextboxState extends State { if (doubleValue < min) { setState(() { - errorMessage = "Value must be at least $min"; + errorMessage = 'Value must be at least $min'; hasError = true; }); } else if (doubleValue > max) { setState(() { - errorMessage = "Value must be at most $max"; + errorMessage = 'Value must be at most $max'; hasError = true; }); } else { - int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - int factor = pow(10, decimalPlaces).toInt(); - int scaledStep = (widget.stepIncreaseAmount * factor).round(); - int scaledValue = (doubleValue * factor).round(); + final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + final factor = pow(10, decimalPlaces).toInt(); + final scaledStep = (widget.stepIncreaseAmount * factor).round(); + final scaledValue = (doubleValue * factor).round(); if (scaledValue % scaledStep != 0) { setState(() { - errorMessage = "must be a multiple of ${widget.stepIncreaseAmount}"; + errorMessage = 'must be a multiple of ${widget.stepIncreaseAmount}'; hasError = true; }); } else { @@ -156,11 +155,10 @@ class _CustomRoutinesTextboxState extends State { } } - void _correctAndUpdateValue(String value) { final doubleValue = double.tryParse(value) ?? 0.0; - int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - double rounded = (doubleValue / widget.stepIncreaseAmount).round() * + final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + var rounded = (doubleValue / widget.stepIncreaseAmount).round() * widget.stepIncreaseAmount; rounded = rounded.clamp(widget.sliderRange.$1, widget.sliderRange.$2); rounded = double.parse(rounded.toStringAsFixed(decimalPlaces)); @@ -179,9 +177,9 @@ class _CustomRoutinesTextboxState extends State { @override Widget build(BuildContext context) { - int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - List formatters = []; + final formatters = []; if (decimalPlaces == 0) { formatters.add(FilteringTextInputFormatter.digitsOnly); } else { @@ -233,7 +231,7 @@ class _CustomRoutinesTextboxState extends State { color: ColorsManager.lightGrayBorderColor, width: 1), boxShadow: [ BoxShadow( - color: ColorsManager.blackColor.withOpacity(0.05), + color: ColorsManager.blackColor.withValues(alpha: 0.05), blurRadius: 8, offset: const Offset(0, 4), ), diff --git a/lib/pages/routines/widgets/delete_scene.dart b/lib/pages/routines/widgets/delete_scene.dart index 10eeb493..13121493 100644 --- a/lib/pages/routines/widgets/delete_scene.dart +++ b/lib/pages/routines/widgets/delete_scene.dart @@ -33,13 +33,17 @@ class DeleteSceneWidget extends StatelessWidget { alignment: AlignmentDirectional.center, child: Text( 'Cancel', - style: Theme.of(context).textTheme.bodyMedium!.copyWith( + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith( color: ColorsManager.textGray, ), ), ), ), - Container(width: 1, height: 50, color: ColorsManager.greyColor), + Container( + width: 1, height: 50, color: ColorsManager.greyColor), InkWell( onTap: () { context.read().add(const DeleteScene()); @@ -50,7 +54,10 @@ class DeleteSceneWidget extends StatelessWidget { alignment: AlignmentDirectional.center, child: Text( 'Confirm', - style: Theme.of(context).textTheme.bodyMedium!.copyWith( + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith( color: ColorsManager.primaryColorWithOpacity, ), ), diff --git a/lib/pages/routines/widgets/dragable_card.dart b/lib/pages/routines/widgets/dragable_card.dart index 9853df7c..69daa31c 100644 --- a/lib/pages/routines/widgets/dragable_card.dart +++ b/lib/pages/routines/widgets/dragable_card.dart @@ -33,17 +33,18 @@ class DraggableCard extends StatelessWidget { Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { - final deviceFunctions = state.selectedFunctions[deviceData['uniqueCustomId']] ?? []; + final deviceFunctions = + state.selectedFunctions[deviceData['uniqueCustomId']] ?? []; - int index = state.thenItems - .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); + final index = state.thenItems.indexWhere( + (item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); if (index != -1) { return _buildCardContent(context, deviceFunctions, padding: padding); } - int ifIndex = state.ifItems - .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); + final ifIndex = state.ifItems.indexWhere( + (item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); if (ifIndex != -1) { return _buildCardContent(context, deviceFunctions, padding: padding); @@ -53,7 +54,8 @@ class DraggableCard extends StatelessWidget { data: deviceData, feedback: Transform.rotate( angle: -0.1, - child: _buildCardContent(context, deviceFunctions, padding: padding), + child: + _buildCardContent(context, deviceFunctions, padding: padding), ), childWhenDragging: _buildGreyContainer(), child: _buildCardContent(context, deviceFunctions, padding: padding), @@ -62,7 +64,8 @@ class DraggableCard extends StatelessWidget { ); } - Widget _buildCardContent(BuildContext context, List deviceFunctions, + Widget _buildCardContent( + BuildContext context, List deviceFunctions, {EdgeInsetsGeometry? padding}) { return Stack( children: [ @@ -92,7 +95,8 @@ class DraggableCard extends StatelessWidget { ), ), padding: const EdgeInsets.all(8), - child: deviceData['type'] == 'tap_to_run' || deviceData['type'] == 'scene' + child: deviceData['type'] == 'tap_to_run' || + deviceData['type'] == 'scene' ? Image.memory( base64Decode(deviceData['icon']), ) @@ -118,12 +122,15 @@ class DraggableCard extends StatelessWidget { height: 4, ), Visibility( - visible: deviceData['tag'] != null && deviceData['tag'] != '', + visible: + deviceData['tag'] != null && deviceData['tag'] != '', child: Row( spacing: 2, children: [ SizedBox( - width: 8, height: 8, child: SvgPicture.asset(Assets.deviceTagIcon)), + width: 8, + height: 8, + child: SvgPicture.asset(Assets.deviceTagIcon)), Flexible( child: Text( deviceData['tag'] ?? '', @@ -141,20 +148,23 @@ class DraggableCard extends StatelessWidget { ), ), Visibility( - visible: deviceData['subSpace'] != null && deviceData['subSpace'] != '', + visible: deviceData['subSpace'] != null && + deviceData['subSpace'] != '', child: const SizedBox( height: 4, ), ), Visibility( - visible: deviceData['subSpace'] != null && deviceData['subSpace'] != '', + visible: deviceData['subSpace'] != null && + deviceData['subSpace'] != '', child: Row( spacing: 2, children: [ SizedBox( width: 8, height: 8, - child: SvgPicture.asset(Assets.spaceLocationIcon)), + child: + SvgPicture.asset(Assets.spaceLocationIcon)), Flexible( child: Text( deviceData['subSpace'] ?? '', @@ -222,7 +232,8 @@ class DraggableCard extends StatelessWidget { } String _formatFunctionValue(DeviceFunctionData function) { - if (function.functionCode == 'temp_set' || function.functionCode == 'temp_current') { + if (function.functionCode == 'temp_set' || + function.functionCode == 'temp_current') { return '${(function.value / 10).toStringAsFixed(0)}°C'; } else if (function.functionCode.contains('countdown')) { final seconds = function.value?.toInt() ?? 0; diff --git a/lib/pages/routines/widgets/function_slider.dart b/lib/pages/routines/widgets/function_slider.dart index 50167a7b..559d8b20 100644 --- a/lib/pages/routines/widgets/function_slider.dart +++ b/lib/pages/routines/widgets/function_slider.dart @@ -17,12 +17,13 @@ class FunctionSlider extends StatelessWidget { @override Widget build(BuildContext context) { final (min, max) = range; - final bool isValidRange = max > min; - final double value = initialValue is int + final isValidRange = max > min; + final value = initialValue is int ? (initialValue as int).toDouble() : (initialValue as double); - final int? divisions = isValidRange ? ((max - min) / dividendOfRange).round() : null; + final divisions = + isValidRange ? ((max - min) / dividendOfRange).round() : null; return Slider( value: value.clamp(min, max), diff --git a/lib/pages/routines/widgets/if_container.dart b/lib/pages/routines/widgets/if_container.dart index da77c7c2..9832f627 100644 --- a/lib/pages/routines/widgets/if_container.dart +++ b/lib/pages/routines/widgets/if_container.dart @@ -62,7 +62,7 @@ class IfContainer extends StatelessWidget { context: context, data: state.ifItems[index], removeComparetors: false, - dialogType: "IF"); + dialogType: 'IF'); if (result != null) { context.read().add( diff --git a/lib/pages/routines/widgets/main_routine_view/fetch_routine_scenes_automation.dart b/lib/pages/routines/widgets/main_routine_view/fetch_routine_scenes_automation.dart index f9c20c54..d28f88f0 100644 --- a/lib/pages/routines/widgets/main_routine_view/fetch_routine_scenes_automation.dart +++ b/lib/pages/routines/widgets/main_routine_view/fetch_routine_scenes_automation.dart @@ -16,8 +16,9 @@ class FetchRoutineScenesAutomation extends StatelessWidget Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { - if (state.isLoading) + if (state.isLoading) { return const Center(child: CircularProgressIndicator()); + } return SingleChildScrollView( child: Padding( @@ -26,23 +27,23 @@ class FetchRoutineScenesAutomation extends StatelessWidget crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - _buildListTitle(context, "Scenes (Tap to Run)"), + _buildListTitle(context, 'Scenes (Tap to Run)'), const SizedBox(height: 10), Visibility( visible: state.scenes.isNotEmpty, - replacement: _buildEmptyState(context, "No scenes found"), + replacement: _buildEmptyState(context, 'No scenes found'), child: SizedBox( height: 200, child: _buildScenes(state), ), ), const SizedBox(height: 10), - _buildListTitle(context, "Automations"), + _buildListTitle(context, 'Automations'), const SizedBox(height: 3), Visibility( visible: state.automations.isNotEmpty, replacement: - _buildEmptyState(context, "No automations found"), + _buildEmptyState(context, 'No automations found'), child: SizedBox( height: 200, child: _buildAutomations(state), diff --git a/lib/pages/routines/widgets/main_routine_view/routine_view_card.dart b/lib/pages/routines/widgets/main_routine_view/routine_view_card.dart index 4fc4bd0f..8c587aba 100644 --- a/lib/pages/routines/widgets/main_routine_view/routine_view_card.dart +++ b/lib/pages/routines/widgets/main_routine_view/routine_view_card.dart @@ -67,15 +67,15 @@ class _RoutineViewCardState extends State { @override Widget build(BuildContext context) { - final double cardWidth = widget.isSmallScreenSize(context) + final cardWidth = widget.isSmallScreenSize(context) ? 120 : widget.isMediumScreenSize(context) ? 135 : 150; - final double cardHeight = widget.isSmallScreenSize(context) ? 190 : 200; + final cardHeight = widget.isSmallScreenSize(context) ? 190 : 200; - final double iconSize = widget.isSmallScreenSize(context) + final iconSize = widget.isSmallScreenSize(context) ? 70 : widget.isMediumScreenSize(context) ? 80 @@ -99,41 +99,42 @@ class _RoutineViewCardState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - widget.cardType != '' - ? Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - if (widget.isFromScenes ?? false) - InkWell( - onTap: _handleSceneTap, - child: Image.asset( - _showTemporaryCheck - ? Assets.scenesPlayIcon - : Assets.scenesPlayIconCheck, - fit: BoxFit.contain, - ), - ) - else if (widget.isLoading) - const SizedBox( - width: 49, - height: 20, - child: Center( - child: SizedBox( - width: 16, - height: 16, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ) - else - CupertinoSwitch( - activeTrackColor: ColorsManager.primaryColor, - value: widget.status == 'enable', - onChanged: widget.onChanged, - ) - ], - ) - : const SizedBox(), + if (widget.cardType != '') + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + if (widget.isFromScenes ?? false) + InkWell( + onTap: _handleSceneTap, + child: Image.asset( + _showTemporaryCheck + ? Assets.scenesPlayIcon + : Assets.scenesPlayIconCheck, + fit: BoxFit.contain, + ), + ) + else if (widget.isLoading) + const SizedBox( + width: 49, + height: 20, + child: Center( + child: SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ) + else + CupertinoSwitch( + activeTrackColor: ColorsManager.primaryColor, + value: widget.status == 'enable', + onChanged: widget.onChanged, + ) + ], + ) + else + const SizedBox(), Column( children: [ Center( @@ -159,8 +160,9 @@ class _RoutineViewCardState extends State { height: iconSize, width: iconSize, fit: BoxFit.contain, - errorBuilder: (context, error, stackTrace) => - Image.asset( + errorBuilder: + (context, error, stackTrace) => + Image.asset( Assets.logo, height: iconSize, width: iconSize, @@ -203,7 +205,8 @@ class _RoutineViewCardState extends State { maxLines: 1, style: context.textTheme.bodySmall?.copyWith( color: ColorsManager.blackColor, - fontSize: widget.isSmallScreenSize(context) ? 10 : 12, + fontSize: + widget.isSmallScreenSize(context) ? 10 : 12, ), ), if (widget.spaceName != '') @@ -222,8 +225,9 @@ class _RoutineViewCardState extends State { maxLines: 1, style: context.textTheme.bodySmall?.copyWith( color: ColorsManager.blackColor, - fontSize: - widget.isSmallScreenSize(context) ? 10 : 12, + fontSize: widget.isSmallScreenSize(context) + ? 10 + : 12, ), ), ], diff --git a/lib/pages/routines/widgets/period_option.dart b/lib/pages/routines/widgets/period_option.dart index 09ec590e..2e455008 100644 --- a/lib/pages/routines/widgets/period_option.dart +++ b/lib/pages/routines/widgets/period_option.dart @@ -21,9 +21,12 @@ class PeriodOptions extends StatelessWidget { builder: (context, state) { return Column( children: [ - _buildRadioOption(context, EnumEffectivePeriodOptions.allDay, '24 Hours'), - _buildRadioOption(context, EnumEffectivePeriodOptions.daytime, 'Sunrise to Sunset'), - _buildRadioOption(context, EnumEffectivePeriodOptions.night, 'Sunset to Sunrise'), + _buildRadioOption( + context, EnumEffectivePeriodOptions.allDay, '24 Hours'), + _buildRadioOption(context, EnumEffectivePeriodOptions.daytime, + 'Sunrise to Sunset'), + _buildRadioOption( + context, EnumEffectivePeriodOptions.night, 'Sunset to Sunrise'), ListTile( contentPadding: EdgeInsets.zero, onTap: () => showCustomTimePicker(context), @@ -34,7 +37,8 @@ class PeriodOptions extends StatelessWidget { fontWeight: FontWeight.w400, fontSize: 14), ), - subtitle: state.customStartTime != null && state.customEndTime != null + subtitle: state.customStartTime != null && + state.customEndTime != null ? Text( '${"${state.customStartTime}"} - ${"${state.customEndTime}"}', style: Theme.of(context).textTheme.bodyMedium!.copyWith( @@ -78,12 +82,16 @@ class PeriodOptions extends StatelessWidget { title: Text( EffectPeriodHelper.formatEnumValue(value), style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 12), + color: ColorsManager.blackColor, + fontWeight: FontWeight.w400, + fontSize: 12), ), subtitle: Text( subtitle, style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: ColorsManager.textPrimaryColor, fontWeight: FontWeight.w400, fontSize: 10), + color: ColorsManager.textPrimaryColor, + fontWeight: FontWeight.w400, + fontSize: 10), ), trailing: Radio( value: value, diff --git a/lib/pages/routines/widgets/repeat_days.dart b/lib/pages/routines/widgets/repeat_days.dart index 4920408a..ee2389be 100644 --- a/lib/pages/routines/widgets/repeat_days.dart +++ b/lib/pages/routines/widgets/repeat_days.dart @@ -16,7 +16,9 @@ class RepeatDays extends StatelessWidget { children: [ Text('Repeat', style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: ColorsManager.textPrimaryColor, fontWeight: FontWeight.w400, fontSize: 14)), + color: ColorsManager.textPrimaryColor, + fontWeight: FontWeight.w400, + fontSize: 14)), const SizedBox(width: 8), BlocBuilder( builder: (context, state) { @@ -31,7 +33,8 @@ class RepeatDays extends StatelessWidget { final day = entry.key; final abbreviation = entry.value; final dayIndex = effectiveBloc.getDayIndex(day); - final isSelected = state.selectedDaysBinary[dayIndex] == '1'; + final isSelected = + state.selectedDaysBinary[dayIndex] == '1'; return Padding( padding: const EdgeInsets.symmetric(horizontal: 3.0), child: GestureDetector( @@ -42,7 +45,9 @@ class RepeatDays extends StatelessWidget { decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( - color: isSelected ? Colors.grey : Colors.grey.shade300, + color: isSelected + ? Colors.grey + : Colors.grey.shade300, width: 1, ), ), @@ -53,7 +58,9 @@ class RepeatDays extends StatelessWidget { abbreviation, style: TextStyle( fontSize: 16, - color: isSelected ? Colors.grey : Colors.grey.shade300, + color: isSelected + ? Colors.grey + : Colors.grey.shade300, ), ), ), diff --git a/lib/pages/routines/widgets/routine_devices.dart b/lib/pages/routines/widgets/routine_devices.dart index f0b77467..5b054908 100644 --- a/lib/pages/routines/widgets/routine_devices.dart +++ b/lib/pages/routines/widgets/routine_devices.dart @@ -74,15 +74,15 @@ class _RoutineDevicesState extends State { .toLowerCase() .contains(state.searchText!.toLowerCase()) ? DraggableCard( - imagePath: deviceData['imagePath'] as String, - title: deviceData['title'] as String, + imagePath: deviceData['imagePath']! as String, + title: deviceData['title']! as String, deviceData: deviceData, ) : const SizedBox.shrink(); } else { return DraggableCard( - imagePath: deviceData['imagePath'] as String, - title: deviceData['title'] as String, + imagePath: deviceData['imagePath']! as String, + title: deviceData['title']! as String, deviceData: deviceData, ); } diff --git a/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart index cbf13178..220bcde0 100644 --- a/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart @@ -24,8 +24,7 @@ class ACHelper { required bool? removeComparetors, required String dialogType, }) async { - List acFunctions = - functions.whereType().where((function) { + final acFunctions = functions.whereType().where((function) { if (dialogType == 'THEN') { return function.type == 'THEN' || function.type == 'BOTH'; } @@ -371,7 +370,7 @@ class ACHelper { // return Container( // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), // decoration: BoxDecoration( - // color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1), + // color: ColorsManager.primaryColorWithOpacity.withValues(alpha:0.1), // borderRadius: BorderRadius.circular(10), // ), // child: Text( diff --git a/lib/pages/routines/widgets/routine_dialogs/automation_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/automation_dialog.dart index 3c1eb1c2..0ef19067 100644 --- a/lib/pages/routines/widgets/routine_dialogs/automation_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/automation_dialog.dart @@ -3,8 +3,8 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart'; import 'package:syncrow_web/pages/routines/models/device_functions.dart'; -import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; +import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; class AutomationDialog extends StatefulWidget { @@ -31,9 +31,11 @@ class _AutomationDialogState extends State { @override void initState() { super.initState(); - List? functions = - context.read().state.selectedFunctions[widget.uniqueCustomId]; - for (DeviceFunctionData data in functions ?? []) { + final functions = context + .read() + .state + .selectedFunctions[widget.uniqueCustomId]; + for (final data in functions ?? []) { if (data.entityId == widget.automationId) { selectedAutomationActionExecutor = data.value; } @@ -65,7 +67,8 @@ class _AutomationDialogState extends State { }), ), ListTile( - leading: SvgPicture.asset(Assets.acPowerOff, width: 24, height: 24), + leading: + SvgPicture.asset(Assets.acPowerOff, width: 24, height: 24), title: const Text('Disable'), trailing: Radio( value: 'rule_disable', diff --git a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_dialog_value_selector.dart b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_dialog_value_selector.dart index 504017a2..5bcc558d 100644 --- a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_dialog_value_selector.dart +++ b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_dialog_value_selector.dart @@ -45,7 +45,8 @@ class CpsDialogValueSelector extends StatelessWidget { operationName: operationName, value: operation.value, condition: selectedFunctionData?.condition, - valueDescription: selectedFunctionData?.valueDescription, + valueDescription: + selectedFunctionData?.valueDescription, ), ), ); diff --git a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_functions_list.dart b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_functions_list.dart index d11871a7..0ce2fd04 100644 --- a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_functions_list.dart +++ b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_functions_list.dart @@ -57,7 +57,7 @@ class CpsFunctionsList extends StatelessWidget { 'moving_max_dis', 'moving_range', 'presence_range', - if (dialogType == "IF") 'sensitivity', + if (dialogType == 'IF') 'sensitivity', ], ); }); diff --git a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_slider_helpers.dart b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_slider_helpers.dart index fd637c28..4fa2e66c 100644 --- a/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_slider_helpers.dart +++ b/lib/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_slider_helpers.dart @@ -1,5 +1,6 @@ abstract final class CpsSliderHelpers { - static (double min, double max, double step) mappedRange(String functionCode) { + static (double min, double max, double step) mappedRange( + String functionCode) { final (defaultMin, defaultMax) = sliderRange(functionCode); final defaultDivdidend = dividendOfRange(functionCode); return switch (functionCode) { @@ -62,7 +63,10 @@ abstract final class CpsSliderHelpers { 'perceptual_boundary' || 'moving_boundary' => 'M', - 'moving_rigger_time' || 'moving_static_time' || 'none_body_time' => 'sec', + 'moving_rigger_time' || + 'moving_static_time' || + 'none_body_time' => + 'sec', _ => '', }; diff --git a/lib/pages/routines/widgets/routine_dialogs/delay_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/delay_dialog.dart index 4580f6e1..b81c6a80 100644 --- a/lib/pages/routines/widgets/routine_dialogs/delay_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/delay_dialog.dart @@ -9,14 +9,14 @@ import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; class DelayHelper { static Future?> showDelayPickerDialog( BuildContext context, Map data) async { - int hours = 0; - int minutes = 0; + var hours = 0; + var minutes = 0; return showDialog?>( context: context, builder: (BuildContext context) { final routineBloc = context.read(); - int totalSec = 0; + var totalSec = 0; final selectedFunctionData = routineBloc.state.selectedFunctions[data['uniqueCustomId']] ?? []; @@ -43,7 +43,8 @@ class DelayHelper { Expanded( child: CupertinoTimerPicker( mode: CupertinoTimerPickerMode.hm, - initialTimerDuration: Duration(hours: hours, minutes: minutes), + initialTimerDuration: + Duration(hours: hours, minutes: minutes), onTimerDurationChanged: (Duration newDuration) { hours = newDuration.inHours; minutes = newDuration.inMinutes % 60; @@ -55,7 +56,7 @@ class DelayHelper { Navigator.of(context).pop(); }, onConfirm: () { - int totalSeconds = (hours * 3600) + (minutes * 60); + final totalSeconds = (hours * 3600) + (minutes * 60); context.read().add(AddFunctionToRoutine( [ DeviceFunctionData( diff --git a/lib/pages/routines/widgets/routine_dialogs/discard_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/discard_dialog.dart index 40036d32..3a493abd 100644 --- a/lib/pages/routines/widgets/routine_dialogs/discard_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/discard_dialog.dart @@ -38,10 +38,10 @@ class DiscardDialog { color: ColorsManager.red, fontWeight: FontWeight.bold, ), - onDismissText: "Don’t Close", - onConfirmText: "Close", + onDismissText: 'Don’t Close', + onConfirmText: 'Close', onDismissColor: ColorsManager.grayColor, - onConfirmColor: ColorsManager.red.withOpacity(0.8), + onConfirmColor: ColorsManager.red.withValues(alpha: 0.8), onDismiss: () { Navigator.pop(context); }, diff --git a/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart index 5fc31a96..5543ec96 100644 --- a/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart @@ -8,13 +8,14 @@ import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:time_picker_spinner/time_picker_spinner.dart'; class EffectPeriodHelper { - static Future?> showCustomTimePicker(BuildContext context) async { - String selectedStartTime = "00:00"; - String selectedEndTime = "23:59"; - PageController pageController = PageController(initialPage: 0); + static Future?> showCustomTimePicker( + BuildContext context) async { + var selectedStartTime = '00:00'; + var selectedEndTime = '23:59'; + final pageController = PageController(initialPage: 0); - DateTime startDateTime = DateTime(2022, 1, 1, 0, 0); - DateTime endDateTime = DateTime(2022, 1, 1, 23, 59); + final startDateTime = DateTime(2022, 1, 1, 0, 0); + final endDateTime = DateTime(2022, 1, 1, 23, 59); context.customAlertDialog( alertBody: SizedBox( @@ -46,7 +47,7 @@ class EffectPeriodHelper { ], ), ), - title: "Custom", + title: 'Custom', onConfirm: () { context.read().add( SetCustomTime(selectedStartTime, selectedEndTime), @@ -88,7 +89,7 @@ class EffectPeriodHelper { ), TextButton( onPressed: () {}, - child: Text(isStartTime ? "Start" : "End", + child: Text(isStartTime ? 'Start' : 'End', style: Theme.of(context).textTheme.bodyMedium!.copyWith( color: ColorsManager.textPrimaryColor, fontWeight: FontWeight.w400, @@ -135,17 +136,17 @@ class EffectPeriodHelper { static String formatEnumValue(EnumEffectivePeriodOptions value) { switch (value) { case EnumEffectivePeriodOptions.allDay: - return "All Day"; + return 'All Day'; case EnumEffectivePeriodOptions.daytime: - return "Daytime"; + return 'Daytime'; case EnumEffectivePeriodOptions.night: - return "Night"; + return 'Night'; case EnumEffectivePeriodOptions.custom: - return "Custom"; + return 'Custom'; case EnumEffectivePeriodOptions.none: - return "None"; + return 'None'; default: - return ""; + return ''; } } } diff --git a/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_value_selector_widget.dart b/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_value_selector_widget.dart index 7ca89edb..b4fa1080 100644 --- a/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_value_selector_widget.dart +++ b/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_value_selector_widget.dart @@ -7,7 +7,6 @@ import 'package:syncrow_web/pages/routines/models/device_functions.dart'; import 'package:syncrow_web/pages/routines/models/flush/flush_functions.dart'; import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.dart'; import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_operational_values_list.dart'; -import 'package:syncrow_web/pages/routines/widgets/slider_value_selector.dart'; class FlushValueSelectorWidget extends StatelessWidget { final String selectedFunction; @@ -62,7 +61,7 @@ class FlushValueSelectorWidget extends StatelessWidget { selectedFunction == FlushMountedPresenceSensorModel.codeFarDetection; final isDistanceDetection = isNearDetection || isFarDetection; - double initialValue = (functionData.value as num?)?.toDouble() ?? 0.0; + var initialValue = (functionData.value as num?)?.toDouble() ?? 0.0; if (isDistanceDetection) { initialValue = initialValue / 100; @@ -157,7 +156,7 @@ class FlushValueSelectorWidget extends StatelessWidget { String get getDisplayText { final num? value = functionData.value; - double displayValue = value?.toDouble() ?? 0.0; + var displayValue = value?.toDouble() ?? 0.0; if (functionData.functionCode == FlushMountedPresenceSensorModel.codeNearDetection || diff --git a/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/time_wheel.dart b/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/time_wheel.dart index 56f74054..4e296e65 100644 --- a/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/time_wheel.dart +++ b/lib/pages/routines/widgets/routine_dialogs/flush_presence_sensor/time_wheel.dart @@ -49,8 +49,6 @@ class _TimeWheelPickerState extends State { } } - - @override void dispose() { _hoursController.dispose(); @@ -103,7 +101,7 @@ class _TimeWheelPickerState extends State { } void _handleTimeChange(int hours, int minutes, int seconds) { - int total = hours * 3600 + minutes * 60 + seconds; + var total = hours * 3600 + minutes * 60 + seconds; if (total > 10000) { hours = 2; minutes = 46; diff --git a/lib/pages/routines/widgets/routine_dialogs/gateway/gateway_dialog_value_selector.dart b/lib/pages/routines/widgets/routine_dialogs/gateway/gateway_dialog_value_selector.dart index 392c3012..1d22f1a1 100644 --- a/lib/pages/routines/widgets/routine_dialogs/gateway/gateway_dialog_value_selector.dart +++ b/lib/pages/routines/widgets/routine_dialogs/gateway/gateway_dialog_value_selector.dart @@ -45,7 +45,8 @@ class GatewayDialogValueSelector extends StatelessWidget { operationName: operationName, value: operation.value, condition: selectedFunctionData?.condition, - valueDescription: selectedFunctionData?.valueDescription, + valueDescription: + selectedFunctionData?.valueDescription, ), ), ); diff --git a/lib/pages/routines/widgets/routine_dialogs/one_gang_switch_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/one_gang_switch_dialog.dart index 641fd234..e2b103c5 100644 --- a/lib/pages/routines/widgets/routine_dialogs/one_gang_switch_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/one_gang_switch_dialog.dart @@ -25,8 +25,7 @@ class OneGangSwitchHelper { required String uniqueCustomId, required bool removeComparetors, }) async { - List oneGangFunctions = - functions.whereType().toList(); + final oneGangFunctions = functions.whereType().toList(); return showDialog?>( context: context, @@ -246,9 +245,9 @@ class OneGangSwitchHelper { withSpecialChar: false, currentCondition: selectedFunctionData?.condition, dialogType: dialogType, - sliderRange: (0, 43200), + sliderRange: (0, 43200), displayedValue: (initialValue ?? 0).toString(), - initialValue: (initialValue ?? 0).toString(), + initialValue: (initialValue ?? 0).toString(), onConditionChanged: (condition) { context.read().add( AddFunction( diff --git a/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/enargy_operational_values_list.dart b/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/enargy_operational_values_list.dart index 2b8ba68f..e6f832c8 100644 --- a/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/enargy_operational_values_list.dart +++ b/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/enargy_operational_values_list.dart @@ -81,6 +81,4 @@ class EnergyOperationalValuesList extends StatelessWidget { ), ); } - - } diff --git a/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/energy_value_selector_widget.dart b/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/energy_value_selector_widget.dart index 696251a1..3695d075 100644 --- a/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/energy_value_selector_widget.dart +++ b/lib/pages/routines/widgets/routine_dialogs/power_clamp_enargy/energy_value_selector_widget.dart @@ -27,13 +27,11 @@ class EnergyValueSelectorWidget extends StatelessWidget { @override Widget build(BuildContext context) { - final selectedFn = - functions.firstWhere((f) => f.code == selectedFunction); + final selectedFn = functions.firstWhere((f) => f.code == selectedFunction); final values = selectedFn.getOperationalValues(); - final step = selectedFn.step ?? 1.0; - final _unit = selectedFn.unit ?? ''; - final (double, double) sliderRange = - (selectedFn.min ?? 0.0, selectedFn.max ?? 100.0); + final step = selectedFn.step ?? 1.0; + final unit = selectedFn.unit ?? ''; + final sliderRange = (selectedFn.min ?? 0.0, selectedFn.max ?? 100.0); if (_isSliderFunction(selectedFunction)) { return CustomRoutinesTextbox( @@ -65,7 +63,7 @@ class EnergyValueSelectorWidget extends StatelessWidget { ), ), ), - unit: _unit, + unit: unit, dividendOfRange: 1, stepIncreaseAmount: step, ); diff --git a/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart index b8449838..2d02304a 100644 --- a/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/routines/bloc/effective_period/effect_period_bloc.dart'; @@ -13,7 +14,6 @@ import 'package:syncrow_web/pages/routines/view/effective_period_view.dart'; import 'package:syncrow_web/pages/routines/widgets/delete_scene.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'package:flutter/cupertino.dart'; class SettingHelper { static Future showSettingDialog({ @@ -30,14 +30,16 @@ class SettingHelper { providers: [ if (effectiveTime != null) BlocProvider( - create: (_) => EffectPeriodBloc()..add(InitialEffectPeriodEvent(effectiveTime)), + create: (_) => EffectPeriodBloc() + ..add(InitialEffectPeriodEvent(effectiveTime)), ), if (effectiveTime == null) BlocProvider( create: (_) => EffectPeriodBloc(), ), BlocProvider( - create: (_) => SettingBloc()..add(InitialEvent(selectedIcon: iconId ?? ''))), + create: (_) => SettingBloc() + ..add(InitialEvent(selectedIcon: iconId ?? ''))), ], child: AlertDialog( contentPadding: EdgeInsets.zero, @@ -45,15 +47,18 @@ class SettingHelper { builder: (context, effectPeriodState) { return BlocBuilder( builder: (context, settingState) { - String selectedIcon = ''; - List list = []; + var selectedIcon = ''; + var list = []; if (settingState is TabToRunSettingLoaded) { selectedIcon = settingState.selectedIcon; list = settingState.iconList; } return Container( width: context.read().isExpanded ? 800 : 400, - height: context.read().isExpanded && isAutomation ? 500 : 350, + height: + context.read().isExpanded && isAutomation + ? 500 + : 350, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), @@ -76,14 +81,18 @@ class SettingHelper { children: [ Container( padding: const EdgeInsets.only( - top: 10, left: 10, right: 10, bottom: 10), + top: 10, + left: 10, + right: 10, + bottom: 10), child: Column( children: [ InkWell( onTap: () {}, child: Row( mainAxisAlignment: - MainAxisAlignment.spaceBetween, + MainAxisAlignment + .spaceBetween, children: [ Text( 'Validity', @@ -91,14 +100,18 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: - ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), const Icon( - Icons.arrow_forward_ios_outlined, - color: ColorsManager.textGray, + Icons + .arrow_forward_ios_outlined, + color: ColorsManager + .textGray, size: 15, ) ], @@ -108,22 +121,27 @@ class SettingHelper { height: 5, ), const Divider( - color: ColorsManager.graysColor, + color: + ColorsManager.graysColor, ), const SizedBox( height: 5, ), InkWell( onTap: () { - BlocProvider.of(context).add( - FetchIcons( + BlocProvider.of< + SettingBloc>( + context) + .add(FetchIcons( expanded: !context - .read() + .read< + SettingBloc>() .isExpanded)); }, child: Row( mainAxisAlignment: - MainAxisAlignment.spaceBetween, + MainAxisAlignment + .spaceBetween, children: [ Text( 'Effective Period', @@ -131,14 +149,18 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: - ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), const Icon( - Icons.arrow_forward_ios_outlined, - color: ColorsManager.textGray, + Icons + .arrow_forward_ios_outlined, + color: ColorsManager + .textGray, size: 15, ) ], @@ -148,13 +170,16 @@ class SettingHelper { height: 5, ), const Divider( - color: ColorsManager.graysColor, + color: + ColorsManager.graysColor, ), const SizedBox( height: 5, ), Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, children: [ Text( 'Executed by', @@ -162,8 +187,11 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), Text('Cloud', @@ -171,12 +199,19 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager.textGray, - fontWeight: FontWeight.w400, + color: + ColorsManager + .textGray, + fontWeight: + FontWeight + .w400, fontSize: 14)), ], ), - if (context.read().state.isUpdate ?? + if (context + .read() + .state + .isUpdate ?? false) const DeleteSceneWidget() ], @@ -188,20 +223,27 @@ class SettingHelper { children: [ Container( padding: const EdgeInsets.only( - top: 10, left: 10, right: 10, bottom: 10), + top: 10, + left: 10, + right: 10, + bottom: 10), child: Column( children: [ InkWell( onTap: () { - BlocProvider.of(context).add( - FetchIcons( + BlocProvider.of< + SettingBloc>( + context) + .add(FetchIcons( expanded: !context - .read() + .read< + SettingBloc>() .isExpanded)); }, child: Row( mainAxisAlignment: - MainAxisAlignment.spaceBetween, + MainAxisAlignment + .spaceBetween, children: [ Text( 'Icons', @@ -209,14 +251,18 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: - ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), const Icon( - Icons.arrow_forward_ios_outlined, - color: ColorsManager.textGray, + Icons + .arrow_forward_ios_outlined, + color: ColorsManager + .textGray, size: 15, ) ], @@ -226,13 +272,16 @@ class SettingHelper { height: 5, ), const Divider( - color: ColorsManager.graysColor, + color: + ColorsManager.graysColor, ), const SizedBox( height: 5, ), Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, children: [ Text( 'Show on devices page', @@ -240,23 +289,30 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), Row( - mainAxisAlignment: MainAxisAlignment.end, + mainAxisAlignment: + MainAxisAlignment.end, children: [ Container( height: 30, width: 1, - color: ColorsManager.graysColor, + color: ColorsManager + .graysColor, ), Transform.scale( scale: .8, - child: CupertinoSwitch( + child: + CupertinoSwitch( value: true, - onChanged: (value) {}, + onChanged: + (value) {}, applyTheme: true, ), ), @@ -268,13 +324,16 @@ class SettingHelper { height: 5, ), const Divider( - color: ColorsManager.graysColor, + color: + ColorsManager.graysColor, ), const SizedBox( height: 5, ), Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, children: [ Text( 'Executed by', @@ -282,8 +341,11 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager.textPrimaryColor, - fontWeight: FontWeight.w400, + color: ColorsManager + .textPrimaryColor, + fontWeight: + FontWeight + .w400, fontSize: 14), ), Text('Cloud', @@ -291,12 +353,19 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager.textGray, - fontWeight: FontWeight.w400, + color: + ColorsManager + .textGray, + fontWeight: + FontWeight + .w400, fontSize: 14)), ], ), - if (context.read().state.isUpdate ?? + if (context + .read() + .state + .isUpdate ?? false) const DeleteSceneWidget() ], @@ -304,12 +373,14 @@ class SettingHelper { ], ), ), - if (context.read().isExpanded && !isAutomation) + if (context.read().isExpanded && + !isAutomation) SizedBox( width: 400, height: 150, child: settingState is LoadingState - ? const Center(child: CircularProgressIndicator()) + ? const Center( + child: CircularProgressIndicator()) : GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( @@ -326,7 +397,8 @@ class SettingHelper { height: 35, child: InkWell( onTap: () { - BlocProvider.of(context) + BlocProvider.of( + context) .add(SelectIcon( iconId: iconModel.uuid, )); @@ -335,13 +407,17 @@ class SettingHelper { child: SizedBox( child: ClipOval( child: Container( - padding: const EdgeInsets.all(1), + padding: + const EdgeInsets.all( + 1), decoration: BoxDecoration( border: Border.all( - color: selectedIcon == iconModel.uuid + color: selectedIcon == + iconModel.uuid ? ColorsManager .primaryColorWithOpacity - : Colors.transparent, + : Colors + .transparent, width: 2, ), shape: BoxShape.circle, @@ -356,8 +432,12 @@ class SettingHelper { ); }, )), - if (context.read().isExpanded && isAutomation) - const SizedBox(height: 350, width: 400, child: EffectivePeriodView()) + if (context.read().isExpanded && + isAutomation) + const SizedBox( + height: 350, + width: 400, + child: EffectivePeriodView()) ], ), Container( @@ -381,23 +461,33 @@ class SettingHelper { alignment: AlignmentDirectional.center, child: Text( 'Cancel', - style: Theme.of(context).textTheme.bodyMedium!.copyWith( + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith( color: ColorsManager.textGray, ), ), ), ), ), - Container(width: 1, height: 50, color: ColorsManager.greyColor), + Container( + width: 1, + height: 50, + color: ColorsManager.greyColor), Expanded( child: InkWell( onTap: () { if (isAutomation) { BlocProvider.of(context).add( - EffectiveTimePeriodEvent(EffectiveTime( - start: effectPeriodState.customStartTime!, - end: effectPeriodState.customEndTime!, - loops: effectPeriodState.selectedDaysBinary))); + EffectiveTimePeriodEvent( + EffectiveTime( + start: effectPeriodState + .customStartTime!, + end: effectPeriodState + .customEndTime!, + loops: effectPeriodState + .selectedDaysBinary))); Navigator.of(context).pop(); } else { Navigator.of(context).pop(selectedIcon); @@ -407,8 +497,12 @@ class SettingHelper { alignment: AlignmentDirectional.center, child: Text( 'Confirm', - style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: ColorsManager.primaryColorWithOpacity, + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith( + color: ColorsManager + .primaryColorWithOpacity, ), ), ), diff --git a/lib/pages/routines/widgets/routine_dialogs/three_gang_switch_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/three_gang_switch_dialog.dart index 5e50c11d..8416837a 100644 --- a/lib/pages/routines/widgets/routine_dialogs/three_gang_switch_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/three_gang_switch_dialog.dart @@ -24,8 +24,7 @@ class ThreeGangSwitchHelper { required String dialogType, required bool removeComparetors, }) async { - List switchFunctions = - functions.whereType().toList(); + final switchFunctions = functions.whereType().toList(); return showDialog?>( context: context, diff --git a/lib/pages/routines/widgets/routine_dialogs/two_gang_switch_dialog.dart b/lib/pages/routines/widgets/routine_dialogs/two_gang_switch_dialog.dart index 6b3dc813..1ed89cd4 100644 --- a/lib/pages/routines/widgets/routine_dialogs/two_gang_switch_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/two_gang_switch_dialog.dart @@ -25,8 +25,7 @@ class TwoGangSwitchHelper { required bool removeComparetors, required String dialogType, }) async { - List switchFunctions = - functions.whereType().toList(); + final switchFunctions = functions.whereType().toList(); return showDialog?>( context: context, @@ -237,7 +236,7 @@ class TwoGangSwitchHelper { DeviceFunctionData? selectedFunctionData, // Function(String) onConditionChanged, ) { - final conditions = ["<", "==", ">"]; + final conditions = ['<', '==', '>']; return ToggleButtons( onPressed: (int index) { @@ -264,8 +263,8 @@ class TwoGangSwitchHelper { minWidth: 40.0, ), isSelected: - conditions.map((c) => c == (currentCondition ?? "==")).toList(), - children: conditions.map((c) => Text(c)).toList(), + conditions.map((c) => c == (currentCondition ?? '==')).toList(), + children: conditions.map(Text.new).toList(), ); } @@ -280,7 +279,7 @@ class TwoGangSwitchHelper { return Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), decoration: BoxDecoration( - color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1), + color: ColorsManager.primaryColorWithOpacity.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(10), ), child: Text( diff --git a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/time_wheel.dart b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/time_wheel.dart index 56f74054..4e296e65 100644 --- a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/time_wheel.dart +++ b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/time_wheel.dart @@ -49,8 +49,6 @@ class _TimeWheelPickerState extends State { } } - - @override void dispose() { _hoursController.dispose(); @@ -103,7 +101,7 @@ class _TimeWheelPickerState extends State { } void _handleTimeChange(int hours, int minutes, int seconds) { - int total = hours * 3600 + minutes * 60 + seconds; + var total = hours * 3600 + minutes * 60 + seconds; if (total > 10000) { hours = 2; minutes = 46; diff --git a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wall_presence_sensor.dart b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wall_presence_sensor.dart index 4d04102d..497ee3db 100644 --- a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wall_presence_sensor.dart +++ b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wall_presence_sensor.dart @@ -63,7 +63,8 @@ class _WallPresenceSensorState extends State { @override void initState() { super.initState(); - _wpsFunctions = widget.functions.whereType().where((function) { + _wpsFunctions = + widget.functions.whereType().where((function) { if (widget.dialogType == 'THEN') { return function.type == 'THEN' || function.type == 'BOTH'; } diff --git a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wps_operational_values_list.dart b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wps_operational_values_list.dart index 6c149cd3..6dacb85e 100644 --- a/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wps_operational_values_list.dart +++ b/lib/pages/routines/widgets/routine_dialogs/wall_sensor/wps_operational_values_list.dart @@ -30,7 +30,8 @@ class WpsOperationalValuesList extends StatelessWidget { : ListView.builder( padding: const EdgeInsets.all(20), itemCount: values.length, - itemBuilder: (context, index) => _buildValueItem(context, values[index]), + itemBuilder: (context, index) => + _buildValueItem(context, values[index]), ); } @@ -61,7 +62,8 @@ class WpsOperationalValuesList extends StatelessWidget { Widget _buildValueIcon(context, WpsOperationalValue value) { return Column( children: [ - if (_shouldShowTextDescription) Text(value.description.replaceAll("cm", '')), + if (_shouldShowTextDescription) + Text(value.description.replaceAll('cm', '')), SvgPicture.asset(value.icon, width: 25, height: 25), ], ); diff --git a/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_operational_values_list.dart b/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_operational_values_list.dart index 4042df36..25839c68 100644 --- a/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_operational_values_list.dart +++ b/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_operational_values_list.dart @@ -61,5 +61,4 @@ class WaterHeaterOperationalValuesList extends StatelessWidget { groupValue: selectedValue, onChanged: (_) => onSelect(value)); } - } diff --git a/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_value_selector_widget.dart b/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_value_selector_widget.dart index a09bbba7..9647408c 100644 --- a/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_value_selector_widget.dart +++ b/lib/pages/routines/widgets/routine_dialogs/water_heater/water_heater_value_selector_widget.dart @@ -12,7 +12,7 @@ class WaterHeaterValueSelectorWidget extends StatelessWidget { final DeviceFunctionData functionData; final List whFunctions; final AllDevicesModel? device; - final String dialogType; + final String dialogType; const WaterHeaterValueSelectorWidget({ required this.selectedFunction, @@ -39,14 +39,13 @@ class WaterHeaterValueSelectorWidget extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ _buildCountDownSlider( - context, - functionData.value, - device, - selectedFn.operationName, - functionData, - selectedFunction, - dialogType - ), + context, + functionData.value, + device, + selectedFn.operationName, + functionData, + selectedFunction, + dialogType), const SizedBox(height: 10), ], ); diff --git a/lib/pages/routines/widgets/routine_search_and_buttons.dart b/lib/pages/routines/widgets/routine_search_and_buttons.dart index efeedf9d..e261b3b1 100644 --- a/lib/pages/routines/widgets/routine_search_and_buttons.dart +++ b/lib/pages/routines/widgets/routine_search_and_buttons.dart @@ -15,7 +15,8 @@ class RoutineSearchAndButtons extends StatefulWidget { }); @override - State createState() => _RoutineSearchAndButtonsState(); + State createState() => + _RoutineSearchAndButtonsState(); } class _RoutineSearchAndButtonsState extends State { @@ -61,8 +62,9 @@ class _RoutineSearchAndButtonsState extends State { children: [ ConstrainedBox( constraints: BoxConstraints( - maxWidth: - constraints.maxWidth > 700 ? 450 : constraints.maxWidth - 32), + maxWidth: constraints.maxWidth > 700 + ? 450 + : constraints.maxWidth - 32), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -71,10 +73,13 @@ class _RoutineSearchAndButtonsState extends State { children: [ Text('* ', style: context.textTheme.bodyMedium! - .copyWith(color: ColorsManager.red, fontSize: 13)), + .copyWith( + color: ColorsManager.red, + fontSize: 13)), Text( 'Routine Name', - style: context.textTheme.bodyMedium!.copyWith( + style: context.textTheme.bodyMedium! + .copyWith( fontSize: 13, fontWeight: FontWeight.w600, color: ColorsManager.blackColor, @@ -88,20 +93,23 @@ class _RoutineSearchAndButtonsState extends State { decoration: containerWhiteDecoration, child: TextFormField( style: context.textTheme.bodyMedium! - .copyWith(color: ColorsManager.blackColor), + .copyWith( + color: ColorsManager.blackColor), controller: _nameController, decoration: InputDecoration( hintText: 'Please enter the name', hintStyle: context.textTheme.bodyMedium! - .copyWith(fontSize: 12, color: ColorsManager.grayColor), + .copyWith( + fontSize: 12, + color: ColorsManager.grayColor), contentPadding: - const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + const EdgeInsets.symmetric( + horizontal: 12, vertical: 10), border: InputBorder.none, ), onTapOutside: (_) { - context - .read() - .add(SetRoutineName(_nameController.text)); + context.read().add( + SetRoutineName(_nameController.text)); }, validator: (value) { if (value == null || value.isEmpty) { @@ -114,41 +122,44 @@ class _RoutineSearchAndButtonsState extends State { ], ), ), - (constraints.maxWidth <= 1000) - ? const SizedBox() - : SizedBox( - height: 40, - width: 200, - child: Center( - child: DefaultButton( - onPressed: state.isAutomation || state.isTabToRun - ? () async { - final result = await SettingHelper.showSettingDialog( - context: context, - iconId: state.selectedIcon ?? '', - ); - if (result != null) { - context - .read() - .add(AddSelectedIcon(result)); - } - } - : null, - borderRadius: 15, - elevation: 0, - borderColor: ColorsManager.greyColor, - backgroundColor: ColorsManager.boxColor, - child: const Text( - 'Settings', - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 12, - color: ColorsManager.primaryColor, - ), - ), + if (constraints.maxWidth <= 1000) + const SizedBox() + else + SizedBox( + height: 40, + width: 200, + child: Center( + child: DefaultButton( + onPressed: state.isAutomation || + state.isTabToRun + ? () async { + final result = await SettingHelper + .showSettingDialog( + context: context, + iconId: state.selectedIcon ?? '', + ); + if (result != null) { + context + .read() + .add(AddSelectedIcon(result)); + } + } + : null, + borderRadius: 15, + elevation: 0, + borderColor: ColorsManager.greyColor, + backgroundColor: ColorsManager.boxColor, + child: const Text( + 'Settings', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 12, + color: ColorsManager.primaryColor, ), ), ), + ), + ), ], ), ), @@ -186,10 +197,12 @@ class _RoutineSearchAndButtonsState extends State { child: Center( child: DefaultButton( onPressed: () async { - if (state.routineName == null || state.routineName!.isEmpty) { + if (state.routineName == null || + state.routineName!.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: const Text('Please enter the routine name'), + content: const Text( + 'Please enter the routine name'), duration: const Duration(seconds: 2), backgroundColor: ColorsManager.red, action: SnackBarAction( @@ -203,10 +216,12 @@ class _RoutineSearchAndButtonsState extends State { return; } - if (state.ifItems.isEmpty || state.thenItems.isEmpty) { + if (state.ifItems.isEmpty || + state.thenItems.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: const Text('Please add if and then condition'), + content: const Text( + 'Please add if and then condition'), duration: const Duration(seconds: 2), backgroundColor: ColorsManager.red, action: SnackBarAction( @@ -221,8 +236,10 @@ class _RoutineSearchAndButtonsState extends State { } // final result = // await - BlocProvider.of(context).add(ResetErrorMessage()); - SaveRoutineHelper.showSaveRoutineDialog(context); + BlocProvider.of(context) + .add(ResetErrorMessage()); + SaveRoutineHelper.showSaveRoutineDialog( + context); // if (result != null && result) { // BlocProvider.of(context).add( // const CreateNewRoutineViewEvent(createRoutineView: false), @@ -261,10 +278,14 @@ class _RoutineSearchAndButtonsState extends State { child: DefaultButton( onPressed: state.isAutomation || state.isTabToRun ? () async { - final result = await SettingHelper.showSettingDialog( - context: context, iconId: state.selectedIcon ?? ''); + final result = + await SettingHelper.showSettingDialog( + context: context, + iconId: state.selectedIcon ?? ''); if (result != null) { - context.read().add(AddSelectedIcon(result)); + context + .read() + .add(AddSelectedIcon(result)); } } : null, @@ -314,10 +335,12 @@ class _RoutineSearchAndButtonsState extends State { child: Center( child: DefaultButton( onPressed: () async { - if (state.routineName == null || state.routineName!.isEmpty) { + if (state.routineName == null || + state.routineName!.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: const Text('Please enter the routine name'), + content: const Text( + 'Please enter the routine name'), duration: const Duration(seconds: 2), backgroundColor: ColorsManager.red, action: SnackBarAction( @@ -331,10 +354,12 @@ class _RoutineSearchAndButtonsState extends State { return; } - if (state.ifItems.isEmpty || state.thenItems.isEmpty) { + if (state.ifItems.isEmpty || + state.thenItems.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: const Text('Please add if and then condition'), + content: const Text( + 'Please add if and then condition'), duration: const Duration(seconds: 2), backgroundColor: ColorsManager.red, action: SnackBarAction( @@ -349,7 +374,8 @@ class _RoutineSearchAndButtonsState extends State { } // final result = // await - BlocProvider.of(context).add(ResetErrorMessage()); + BlocProvider.of(context) + .add(ResetErrorMessage()); SaveRoutineHelper.showSaveRoutineDialog(context); // if (result != null && result) { // BlocProvider.of(context).add( diff --git a/lib/pages/routines/widgets/scenes_and_automations.dart b/lib/pages/routines/widgets/scenes_and_automations.dart index 14cb8d61..785686b6 100644 --- a/lib/pages/routines/widgets/scenes_and_automations.dart +++ b/lib/pages/routines/widgets/scenes_and_automations.dart @@ -27,14 +27,16 @@ class _ScenesAndAutomationsState extends State { return BlocBuilder( builder: (context, state) { if (!state.isLoading) { - var scenes = [...state.scenes, ...state.automations]; + final scenes = [...state.scenes, ...state.automations]; return Wrap( spacing: 10, runSpacing: 10, children: scenes.asMap().entries.map((entry) { final scene = entry.value; if (state.searchText != null && state.searchText!.isNotEmpty) { - return scene.name.toLowerCase().contains(state.searchText!.toLowerCase()) + return scene.name + .toLowerCase() + .contains(state.searchText!.toLowerCase()) ? DraggableCard( imagePath: scene.icon ?? Assets.loginLogo, title: scene.name, diff --git a/lib/pages/routines/widgets/search_bar_condition_title.dart b/lib/pages/routines/widgets/search_bar_condition_title.dart index 9ffcbf63..9d2320bd 100644 --- a/lib/pages/routines/widgets/search_bar_condition_title.dart +++ b/lib/pages/routines/widgets/search_bar_condition_title.dart @@ -6,7 +6,8 @@ import 'package:syncrow_web/pages/routines/widgets/routines_title_widget.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; -class ConditionTitleAndSearchBar extends StatelessWidget with HelperResponsiveLayout { +class ConditionTitleAndSearchBar extends StatelessWidget + with HelperResponsiveLayout { const ConditionTitleAndSearchBar({ super.key, }); diff --git a/lib/pages/routines/widgets/then_container.dart b/lib/pages/routines/widgets/then_container.dart index d9eee4c4..e32a2e67 100644 --- a/lib/pages/routines/widgets/then_container.dart +++ b/lib/pages/routines/widgets/then_container.dart @@ -30,123 +30,118 @@ class ThenContainer extends StatelessWidget { style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(height: 16), - state.isLoading && state.isUpdate == true - ? const Center( - child: CircularProgressIndicator(), - ) - : Wrap( - spacing: 8, - runSpacing: 8, - children: List.generate( - state.thenItems.length, - (index) => GestureDetector( - onTap: () async { - if (state.thenItems[index] - ['deviceId'] == - 'delay') { - final result = await DelayHelper - .showDelayPickerDialog(context, - state.thenItems[index]); - - if (result != null) { - context - .read() - .add(AddToThenContainer({ - ...state.thenItems[index], - 'imagePath': Assets.delay, - 'title': 'Delay', - })); - } - return; - } - - if (state.thenItems[index]['type'] == - 'automation') { - final result = await showDialog( - context: context, - builder: (BuildContext context) => - AutomationDialog( - automationName: - state.thenItems[index] - ['name'] ?? - 'Automation', - automationId: - state.thenItems[index] - ['deviceId'] ?? - '', - uniqueCustomId: - state.thenItems[index] - ['uniqueCustomId'], - ), - ); - - if (result != null) { - context - .read() - .add(AddToThenContainer({ - ...state.thenItems[index], - 'imagePath': - Assets.automation, - 'title': - state.thenItems[index] - ['name'] ?? - state.thenItems[index] - ['title'], - })); - } - return; - } - - final result = await DeviceDialogHelper - .showDeviceDialog( - context: context, - data: state.thenItems[index], - removeComparetors: true, - dialogType: "THEN"); + if (state.isLoading && state.isUpdate == true) + const Center( + child: CircularProgressIndicator(), + ) + else + Wrap( + spacing: 8, + runSpacing: 8, + children: List.generate( + state.thenItems.length, + (index) => GestureDetector( + onTap: () async { + if (state.thenItems[index]['deviceId'] == + 'delay') { + final result = await DelayHelper + .showDelayPickerDialog(context, + state.thenItems[index]); if (result != null) { - context.read().add( - AddToThenContainer( - state.thenItems[index])); - } else if (![ - 'AC', - '1G', - '2G', - '3G', - 'WPS', - 'CPS', - "GW", - "NCPS", - 'WH', - ].contains(state.thenItems[index] - ['productType'])) { - context.read().add( - AddToThenContainer( - state.thenItems[index])); + context + .read() + .add(AddToThenContainer({ + ...state.thenItems[index], + 'imagePath': Assets.delay, + 'title': 'Delay', + })); } + return; + } + + if (state.thenItems[index]['type'] == + 'automation') { + final result = await showDialog( + context: context, + builder: (BuildContext context) => + AutomationDialog( + automationName: state + .thenItems[index]['name'] ?? + 'Automation', + automationId: state.thenItems[index] + ['deviceId'] ?? + '', + uniqueCustomId: + state.thenItems[index] + ['uniqueCustomId'], + ), + ); + + if (result != null) { + context + .read() + .add(AddToThenContainer({ + ...state.thenItems[index], + 'imagePath': Assets.automation, + 'title': state.thenItems[index] + ['name'] ?? + state.thenItems[index] + ['title'], + })); + } + return; + } + + final result = await DeviceDialogHelper + .showDeviceDialog( + context: context, + data: state.thenItems[index], + removeComparetors: true, + dialogType: 'THEN'); + + if (result != null) { + context.read().add( + AddToThenContainer( + state.thenItems[index])); + } else if (![ + 'AC', + '1G', + '2G', + '3G', + 'WPS', + 'CPS', + 'GW', + 'NCPS', + 'WH', + ].contains(state.thenItems[index] + ['productType'])) { + context.read().add( + AddToThenContainer( + state.thenItems[index])); + } + }, + child: DraggableCard( + imagePath: state.thenItems[index] + ['imagePath'] ?? + '', + title: + state.thenItems[index]['title'] ?? '', + deviceData: state.thenItems[index], + padding: const EdgeInsets.symmetric( + horizontal: 4, vertical: 8), + isFromThen: true, + isFromIf: false, + onRemove: () { + context.read().add( + RemoveDragCard( + index: index, + isFromThen: true, + key: state.thenItems[index] + ['uniqueCustomId'])); }, - child: DraggableCard( - imagePath: state.thenItems[index] - ['imagePath'] ?? - '', - title: state.thenItems[index] - ['title'] ?? - '', - deviceData: state.thenItems[index], - padding: const EdgeInsets.symmetric( - horizontal: 4, vertical: 8), - isFromThen: true, - isFromIf: false, - onRemove: () { - context.read().add( - RemoveDragCard( - index: index, - isFromThen: true, - key: state.thenItems[index] - ['uniqueCustomId'])); - }, - ), - ))), + ), + ))), ], ), ), @@ -168,7 +163,7 @@ class ThenContainer extends StatelessWidget { } if (mutableData['type'] == 'automation') { - int index = state.thenItems.indexWhere( + final index = state.thenItems.indexWhere( (item) => item['deviceId'] == mutableData['deviceId']); if (index != -1) { return; @@ -194,7 +189,7 @@ class ThenContainer extends StatelessWidget { } if (mutableData['type'] == 'tap_to_run' && state.isAutomation) { - int index = state.thenItems.indexWhere( + final index = state.thenItems.indexWhere( (item) => item['deviceId'] == mutableData['deviceId']); if (index != -1) { return; @@ -230,7 +225,7 @@ class ThenContainer extends StatelessWidget { context: context, data: mutableData, removeComparetors: true, - dialogType: "THEN"); + dialogType: 'THEN'); if (result != null) { context.read().add(AddToThenContainer(mutableData)); } else if (![ @@ -241,8 +236,8 @@ class ThenContainer extends StatelessWidget { 'WPS', 'GW', 'CPS', - "NCPS", - "WH", + 'NCPS', + 'WH', 'PC', ].contains(mutableData['productType'])) { context.read().add(AddToThenContainer(mutableData)); diff --git a/lib/pages/routines/widgets/value_display.dart b/lib/pages/routines/widgets/value_display.dart index 6a8bd949..b03720cf 100644 --- a/lib/pages/routines/widgets/value_display.dart +++ b/lib/pages/routines/widgets/value_display.dart @@ -19,7 +19,7 @@ class ValueDisplay extends StatelessWidget { return Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), decoration: BoxDecoration( - color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1), + color: ColorsManager.primaryColorWithOpacity.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(10), ), child: Text( diff --git a/lib/pages/space_tree/bloc/space_tree_bloc.dart b/lib/pages/space_tree/bloc/space_tree_bloc.dart index e8c2e015..cd374eb5 100644 --- a/lib/pages/space_tree/bloc/space_tree_bloc.dart +++ b/lib/pages/space_tree/bloc/space_tree_bloc.dart @@ -30,7 +30,7 @@ class SpaceTreeBloc extends Bloc { } Timer _timer = Timer(const Duration(microseconds: 0), () {}); - void _onCommunityUpdate( + Future _onCommunityUpdate( OnCommunityUpdated event, Emitter emit, ) async { @@ -54,12 +54,13 @@ class SpaceTreeBloc extends Bloc { } } - _fetchSpaces(InitialEvent event, Emitter emit) async { + Future _fetchSpaces( + InitialEvent event, Emitter emit) async { emit(SpaceTreeLoadingState()); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - PaginationModel paginationModel = await CommunitySpaceManagementApi() + final paginationModel = await CommunitySpaceManagementApi() .fetchCommunitiesAndSpaces(projectId: projectUuid, page: 1); // List updatedCommunities = await Future.wait( @@ -89,10 +90,11 @@ class SpaceTreeBloc extends Bloc { } } - _fetchPaginationSpaces(PaginationEvent event, Emitter emit) async { + Future _fetchPaginationSpaces( + PaginationEvent event, Emitter emit) async { emit(state.copyWith(paginationIsLoading: true)); - PaginationModel paginationModel = event.paginationModel; - List communities = List.from(event.communities); + var paginationModel = event.paginationModel; + final communities = List.from(event.communities); try { if (paginationModel.hasNext && state.searchQuery.isEmpty) { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -114,7 +116,7 @@ class SpaceTreeBloc extends Bloc { paginationIsLoading: false)); } - void _onCommunityAdded( + Future _onCommunityAdded( OnCommunityAdded event, Emitter emit) async { final updatedCommunities = List.from(state.communityList); updatedCommunities.add(event.newCommunity); @@ -122,11 +124,11 @@ class SpaceTreeBloc extends Bloc { emit(state.copyWith(communitiesList: updatedCommunities)); } - _onCommunityExpanded( + Future _onCommunityExpanded( OnCommunityExpanded event, Emitter emit) async { try { - List updatedExpandedCommunityList = - List.from(state.expandedCommunities); + final updatedExpandedCommunityList = + List.from(state.expandedCommunities); if (updatedExpandedCommunityList.contains(event.communityId)) { updatedExpandedCommunityList.remove(event.communityId); @@ -142,9 +144,10 @@ class SpaceTreeBloc extends Bloc { } } - _onSpaceExpanded(OnSpaceExpanded event, Emitter emit) async { + Future _onSpaceExpanded( + OnSpaceExpanded event, Emitter emit) async { try { - List updatedExpandedSpacesList = List.from(state.expandedSpaces); + final updatedExpandedSpacesList = List.from(state.expandedSpaces); if (updatedExpandedSpacesList.contains(event.spaceId)) { updatedExpandedSpacesList.remove(event.spaceId); @@ -158,20 +161,21 @@ class SpaceTreeBloc extends Bloc { } } - _onCommunitySelected( + Future _onCommunitySelected( OnCommunitySelected event, Emitter emit) async { try { - List updatedSelectedCommunities = - List.from(state.selectedCommunities.toSet().toList()); - List updatedSelectedSpaces = - List.from(state.selectedSpaces.toSet().toList()); - List updatedSoldChecks = List.from(state.soldCheck.toSet().toList()); - Map> communityAndSpaces = - Map.from(state.selectedCommunityAndSpaces); - List selectedSpacesInCommunity = + final updatedSelectedCommunities = + List.from(state.selectedCommunities.toSet().toList()); + final updatedSelectedSpaces = + List.from(state.selectedSpaces.toSet().toList()); + final updatedSoldChecks = + List.from(state.soldCheck.toSet().toList()); + final communityAndSpaces = + Map>.from(state.selectedCommunityAndSpaces); + final selectedSpacesInCommunity = communityAndSpaces[event.communityId] ?? []; - List childrenIds = _getAllChildIds(event.children); + final childrenIds = _getAllChildIds(event.children); if (!updatedSelectedCommunities.contains(event.communityId)) { // Select the community and all its children @@ -198,23 +202,25 @@ class SpaceTreeBloc extends Bloc { } } - _onSpaceSelected(OnSpaceSelected event, Emitter emit) async { + Future _onSpaceSelected( + OnSpaceSelected event, Emitter emit) async { try { - List updatedSelectedCommunities = - List.from(state.selectedCommunities.toSet().toList()); - List updatedSelectedSpaces = - List.from(state.selectedSpaces.toSet().toList()); - List updatedSoldChecks = List.from(state.soldCheck.toSet().toList()); - Map> communityAndSpaces = - Map.from(state.selectedCommunityAndSpaces); + final updatedSelectedCommunities = + List.from(state.selectedCommunities.toSet().toList()); + final updatedSelectedSpaces = + List.from(state.selectedSpaces.toSet().toList()); + final updatedSoldChecks = + List.from(state.soldCheck.toSet().toList()); + final communityAndSpaces = + Map>.from(state.selectedCommunityAndSpaces); - List selectedSpacesInCommunity = + final selectedSpacesInCommunity = communityAndSpaces[event.communityModel.uuid] ?? []; - List childrenIds = _getAllChildIds(event.children); - bool isChildSelected = false; + final childrenIds = _getAllChildIds(event.children); + var isChildSelected = false; - for (String id in childrenIds) { + for (final id in childrenIds) { if (updatedSelectedSpaces.contains(id)) { isChildSelected = true; } @@ -232,9 +238,9 @@ class SpaceTreeBloc extends Bloc { selectedSpacesInCommunity.addAll(childrenIds); } - List spaces = + final spaces = _getThePathToChild(event.communityModel.uuid, event.spaceId); - for (String space in spaces) { + for (final space in spaces) { if (!updatedSelectedSpaces.contains(space) && !updatedSoldChecks.contains(space)) { updatedSoldChecks.add(space); @@ -258,7 +264,7 @@ class SpaceTreeBloc extends Bloc { } updatedSoldChecks.remove(event.spaceId); - List parents = + final parents = _getThePathToChild(event.communityModel.uuid, event.spaceId) .toSet() .toList(); @@ -268,7 +274,7 @@ class SpaceTreeBloc extends Bloc { updatedSelectedCommunities.remove(event.communityModel.uuid); } else { // Check if any parent has selected children - for (String space in parents) { + for (final space in parents) { if (!_noChildrenSelected( event.communityModel, space, updatedSelectedSpaces, parents)) { updatedSoldChecks.remove(space); @@ -295,17 +301,17 @@ class SpaceTreeBloc extends Bloc { } } - _noChildrenSelected(CommunityModel community, String spaceId, + bool _noChildrenSelected(CommunityModel community, String spaceId, List selectedSpaces, List parents) { if (selectedSpaces.contains(spaceId)) { return true; } - List children = _getAllChildSpaces(community.spaces); - for (var child in children) { + final children = _getAllChildSpaces(community.spaces); + for (final child in children) { if (spaceId == child.uuid) { - List ids = _getAllChildIds(child.children); - for (var id in ids) { + final ids = _getAllChildIds(child.children); + for (final id in ids) { if (selectedSpaces.contains(id)) { return true; } @@ -316,14 +322,15 @@ class SpaceTreeBloc extends Bloc { return false; } - _onSearch(SearchQueryEvent event, Emitter emit) async { + Future _onSearch( + SearchQueryEvent event, Emitter emit) async { try { const duration = Duration(seconds: 1); if (_timer.isActive) { _timer.cancel(); // clear timer } - _timer = - Timer(duration, () async => add(DebouncedSearchEvent(event.searchQuery))); + _timer = Timer( + duration, () async => add(DebouncedSearchEvent(event.searchQuery))); // List communities = List.from(state.communityList); // List filteredCommunity = []; @@ -347,12 +354,12 @@ class SpaceTreeBloc extends Bloc { } } - _onDebouncedSearch( + Future _onDebouncedSearch( DebouncedSearchEvent event, Emitter emit) async { emit(state.copyWith( isSearching: true, )); - PaginationModel paginationModel = const PaginationModel.emptyConstructor(); + var paginationModel = const PaginationModel.emptyConstructor(); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -367,7 +374,8 @@ class SpaceTreeBloc extends Bloc { searchQuery: event.searchQuery)); } - _clearAllData(ClearAllData event, Emitter emit) async { + Future _clearAllData( + ClearAllData event, Emitter emit) async { try { emit(state.copyWith( communitiesList: [], @@ -385,7 +393,8 @@ class SpaceTreeBloc extends Bloc { } } - _clearCachedData(ClearCachedData event, Emitter emit) async { + Future _clearCachedData( + ClearCachedData event, Emitter emit) async { try { emit(state.copyWith( communitiesList: state.communityList, @@ -413,8 +422,8 @@ class SpaceTreeBloc extends Bloc { // } List _getAllChildIds(List spaces) { - List ids = []; - for (var child in spaces) { + final ids = []; + for (final child in spaces) { ids.add(child.uuid!); ids.addAll(_getAllChildIds(child.children)); } @@ -422,8 +431,8 @@ class SpaceTreeBloc extends Bloc { } List _getAllChildSpaces(List spaces) { - List children = []; - for (var child in spaces) { + final children = []; + for (final child in spaces) { children.add(child); children.addAll(_getAllChildSpaces(child.children)); } @@ -432,9 +441,9 @@ class SpaceTreeBloc extends Bloc { bool _anySpacesSelectedInCommunity(CommunityModel community, List selectedSpaces, List partialCheckedList) { - bool result = false; - List ids = _getAllChildIds(community.spaces); - for (var id in ids) { + var result = false; + final ids = _getAllChildIds(community.spaces); + for (final id in ids) { result = selectedSpaces.contains(id) || partialCheckedList.contains(id); if (result) { return result; @@ -444,11 +453,11 @@ class SpaceTreeBloc extends Bloc { } List _getThePathToChild(String communityId, String selectedSpaceId) { - List ids = []; - for (var community in state.communityList) { + var ids = []; + for (final community in state.communityList) { if (community.uuid == communityId) { - for (var space in community.spaces) { - List list = []; + for (final space in community.spaces) { + final list = []; list.add(space.uuid!); ids = _getAllParentsIds(space, selectedSpaceId, List.from(list)); if (ids.isNotEmpty) { @@ -462,7 +471,7 @@ class SpaceTreeBloc extends Bloc { List _getAllParentsIds( SpaceModel child, String spaceId, List listIds) { - List ids = listIds; + final ids = listIds; ids.add(child.uuid ?? ''); @@ -471,8 +480,8 @@ class SpaceTreeBloc extends Bloc { } if (child.children.isNotEmpty) { - for (var space in child.children) { - var result = _getAllParentsIds(space, spaceId, List.from(ids)); + for (final space in child.children) { + final result = _getAllParentsIds(space, spaceId, List.from(ids)); if (result.isNotEmpty) { return result; } @@ -483,7 +492,7 @@ class SpaceTreeBloc extends Bloc { return []; } - void _onSpaceTreeClearSelectionEvent( + Future _onSpaceTreeClearSelectionEvent( SpaceTreeClearSelectionEvent event, Emitter emit, ) async { @@ -496,7 +505,7 @@ class SpaceTreeBloc extends Bloc { ); } - void _onAnalyticsClearAllSpaceTreeSelectionsEvent( + Future _onAnalyticsClearAllSpaceTreeSelectionsEvent( AnalyticsClearAllSpaceTreeSelectionsEvent event, Emitter emit, ) async { diff --git a/lib/pages/space_tree/bloc/space_tree_state.dart b/lib/pages/space_tree/bloc/space_tree_state.dart index 595380fd..175a9da6 100644 --- a/lib/pages/space_tree/bloc/space_tree_state.dart +++ b/lib/pages/space_tree/bloc/space_tree_state.dart @@ -44,15 +44,16 @@ class SpaceTreeState extends Equatable { PaginationModel? paginationModel, bool? paginationIsLoading}) { return SpaceTreeState( - communityList: communitiesList ?? this.communityList, + communityList: communitiesList ?? communityList, filteredCommunity: filteredCommunity ?? this.filteredCommunity, expandedSpaces: expandedSpaces ?? this.expandedSpaces, - expandedCommunities: expandedCommunity ?? this.expandedCommunities, + expandedCommunities: expandedCommunity ?? expandedCommunities, selectedCommunities: selectedCommunities ?? this.selectedCommunities, selectedSpaces: selectedSpaces ?? this.selectedSpaces, soldCheck: soldCheck ?? this.soldCheck, isSearching: isSearching ?? this.isSearching, - selectedCommunityAndSpaces: selectedCommunityAndSpaces ?? this.selectedCommunityAndSpaces, + selectedCommunityAndSpaces: + selectedCommunityAndSpaces ?? this.selectedCommunityAndSpaces, searchQuery: searchQuery ?? this.searchQuery, paginationModel: paginationModel ?? this.paginationModel, paginationIsLoading: paginationIsLoading ?? this.paginationIsLoading); diff --git a/lib/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart b/lib/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart index e84851c5..624045e9 100644 --- a/lib/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart +++ b/lib/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart @@ -1,7 +1,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; class AddDeviceTypeBloc extends Bloc { AddDeviceTypeBloc() : super(AddDeviceInitial()) { diff --git a/lib/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart b/lib/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart index 254b78fd..51b1ea34 100644 --- a/lib/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart +++ b/lib/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart @@ -16,7 +16,7 @@ class UpdateProductCountEvent extends AddDeviceTypeEvent { final String productName; final ProductModel product; - UpdateProductCountEvent( + const UpdateProductCountEvent( {required this.productId, required this.count, required this.productName, @@ -26,7 +26,6 @@ class UpdateProductCountEvent extends AddDeviceTypeEvent { List get props => [productId, count]; } - class InitializeDevice extends AddDeviceTypeEvent { final List initialTags; final List addedProducts; diff --git a/lib/pages/spaces_management/add_device_type/views/add_device_type_widget.dart b/lib/pages/spaces_management/add_device_type/views/add_device_type_widget.dart index ede6afb9..e95bc74d 100644 --- a/lib/pages/spaces_management/add_device_type/views/add_device_type_widget.dart +++ b/lib/pages/spaces_management/add_device_type/views/add_device_type_widget.dart @@ -6,10 +6,10 @@ import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_dev import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart'; import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/add_device_type/widgets/scrollable_grid_view_widget.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -24,8 +24,7 @@ class AddDeviceTypeWidget extends StatelessWidget { final String spaceName; final bool isCreate; final Function(List, List?)? onSave; - final List projectTags; - + final List projectTags; const AddDeviceTypeWidget( {super.key, diff --git a/lib/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart b/lib/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart index a4d6628e..4bda7999 100644 --- a/lib/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart +++ b/lib/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart @@ -1,20 +1,19 @@ import 'dart:async'; + import 'package:flutter/widgets.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_state.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_state.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_body_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart'; import 'package:syncrow_web/services/product_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart'; @@ -57,10 +56,10 @@ class SpaceManagementBloc UpdateSpaceModelCache event, Emitter emit) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - List allSpaceModels = []; + final allSpaceModels = []; - bool hasNext = true; - int page = 1; + var hasNext = true; + var page = 1; while (hasNext) { final spaceModels = await _spaceModelApi.listSpaceModels( @@ -85,7 +84,7 @@ class SpaceManagementBloc allTags: _cachedTags ?? [])); } - void _deleteSpaceModelFromCache(DeleteSpaceModelFromCache event, + Future _deleteSpaceModelFromCache(DeleteSpaceModelFromCache event, Emitter emit) async { if (_cachedSpaceModels != null) { _cachedSpaceModels = _cachedSpaceModels! @@ -121,10 +120,10 @@ class SpaceManagementBloc final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - List allSpaceModels = []; + final allSpaceModels = []; - bool hasNext = true; - int page = 1; + var hasNext = true; + var page = 1; while (hasNext) { final spaceModels = await _spaceModelApi.listSpaceModels( @@ -159,7 +158,7 @@ class SpaceManagementBloc } } - void _onUpdateCommunity( + Future _onUpdateCommunity( UpdateCommunityEvent event, Emitter emit, ) async { @@ -175,7 +174,7 @@ class SpaceManagementBloc if (previousState is SpaceManagementLoaded) { final updatedCommunities = List.from(previousState.communities); - for (var community in updatedCommunities) { + for (final community in updatedCommunities) { if (community.uuid == event.communityUuid) { community.name = event.name; _spaceTreeBloc.add(OnCommunityAdded(community)); @@ -184,7 +183,7 @@ class SpaceManagementBloc } } - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); emit(SpaceManagementLoaded( communities: updatedCommunities, @@ -201,14 +200,14 @@ class SpaceManagementBloc } } - void _onloadProducts() async { + Future _onloadProducts() async { if (_cachedProducts == null) { final products = await _productApi.fetchProducts(); _cachedProducts = products; } } - void _onFetchProducts( + Future _onFetchProducts( FetchProductsEvent event, Emitter emit, ) async { @@ -223,7 +222,7 @@ class SpaceManagementBloc String communityUuid) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - return await _api.getSpaceHierarchy(communityUuid, projectUuid); + return _api.getSpaceHierarchy(communityUuid, projectUuid); } Future _onNewCommunity( @@ -238,7 +237,7 @@ class SpaceManagementBloc return; } - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); emit(BlankState( communities: event.communities, @@ -255,15 +254,15 @@ class SpaceManagementBloc try { final previousState = state; final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - var spaceBloc = event.context.read(); - var spaceTreeState = event.context.read().state; + final spaceBloc = event.context.read(); + final spaceTreeState = event.context.read().state; - List communities = + final communities = await _waitForCommunityList(spaceBloc, spaceTreeState); await fetchSpaceModels(); // await fetchTags(); - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); if (previousState is SpaceManagementLoaded || previousState is BlankState) { @@ -287,18 +286,17 @@ class SpaceManagementBloc } } - void _onLoadCommunityAndSpaces( + Future _onLoadCommunityAndSpaces( LoadCommunityAndSpacesEvent event, Emitter emit, ) async { - var spaceTreeState = event.context.read().state; - var spaceBloc = event.context.read(); + final spaceTreeState = event.context.read().state; + final spaceBloc = event.context.read(); _onloadProducts(); await fetchTags(); // Wait until `communityList` is loaded - List communities = - await _waitForCommunityList(spaceBloc, spaceTreeState); + final communities = await _waitForCommunityList(spaceBloc, spaceTreeState); // Fetch space models after communities are available final prevSpaceModels = await fetchSpaceModels(); @@ -344,7 +342,7 @@ class SpaceManagementBloc } } - void _onCommunityDelete( + Future _onCommunityDelete( DeleteCommunityEvent event, Emitter emit, ) async { @@ -365,7 +363,7 @@ class SpaceManagementBloc } } - void _onCreateCommunity( + Future _onCreateCommunity( CreateCommunityEvent event, Emitter emit, ) async { @@ -375,9 +373,9 @@ class SpaceManagementBloc try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; await fetchTags(); - CommunityModel? newCommunity = await _api.createCommunity( + final newCommunity = await _api.createCommunity( event.name, event.description, projectUuid); - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); if (newCommunity != null) { if (previousState is SpaceManagementLoaded || @@ -405,7 +403,7 @@ class SpaceManagementBloc } } - void _onSelectCommunity( + Future _onSelectCommunity( SelectCommunityEvent event, Emitter emit, ) async { @@ -431,7 +429,7 @@ class SpaceManagementBloc ); } - void _handleCommunitySpaceStateUpdate({ + Future _handleCommunitySpaceStateUpdate({ required Emitter emit, CommunityModel? selectedCommunity, SpaceModel? selectedSpace, @@ -464,7 +462,7 @@ class SpaceManagementBloc } } - void _onSaveSpaces( + Future _onSaveSpaces( SaveSpacesEvent event, Emitter emit, ) async { @@ -494,9 +492,9 @@ class SpaceManagementBloc event.spaces.removeWhere( (space) => space.status == SpaceStatus.deleted, ); - event.spaces.forEach( - (space) => space.status = SpaceStatus.unchanged, - ); + for (final space in event.spaces) { + space.status = SpaceStatus.unchanged; + } } } catch (e) { // emit(SpaceManagementError('Error saving spaces: $e')); @@ -515,7 +513,7 @@ class SpaceManagementBloc Emitter emit, ) async { try { - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); await fetchTags(); @@ -523,7 +521,7 @@ class SpaceManagementBloc ? spaceTreeState.filteredCommunity : spaceTreeState.communityList; - for (var community in communities) { + for (final community in communities) { if (community.uuid == communityUuid) { community.spaces = allSpaces; _spaceTreeBloc.add(InitialEvent()); @@ -540,7 +538,7 @@ class SpaceManagementBloc } } emit(previousState); - } catch (e, stackTrace) { + } catch (e) { emit(previousState); // rethrow; } @@ -577,36 +575,36 @@ class SpaceManagementBloc space.status == SpaceStatus.deleted && (space.parent == null || space.parent?.status != SpaceStatus.deleted)); - for (var parent in parentsToDelete) { + for (final parent in parentsToDelete) { try { if (parent.uuid != null) { await _api.deleteSpace(communityUuid, parent.uuid!, projectUuid); } } catch (e) {} } - orderedSpaces.removeWhere((space) => parentsToDelete.contains(space)); + orderedSpaces.removeWhere(parentsToDelete.contains); - for (var space in orderedSpaces) { + for (final space in orderedSpaces) { try { if (space.uuid != null && space.uuid!.isNotEmpty) { - List tagUpdates = []; + var tagUpdates = []; - List matchedSpaces = + final matchedSpaces = findMatchingSpaces(selectedCommunity.spaces, space.uuid!); if (matchedSpaces.isEmpty) continue; final prevSpace = matchedSpaces.elementAtOrNull(0); - final List subspaceUpdates = []; - final List? prevSubspaces = prevSpace?.subspaces; - final List? newSubspaces = space.subspaces; + final subspaceUpdates = []; + final prevSubspaces = prevSpace?.subspaces; + final newSubspaces = space.subspaces; tagUpdates = processTagUpdates(prevSpace?.tags, space.tags); if (prevSubspaces != null || newSubspaces != null) { if (prevSubspaces != null && newSubspaces != null) { - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { final existsInNew = newSubspaces .any((subspace) => subspace.uuid == prevSubspace.uuid); if (!existsInNew) { @@ -616,7 +614,7 @@ class SpaceManagementBloc } } } else if (prevSubspaces != null && newSubspaces == null) { - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { subspaceUpdates.add(UpdateSubspaceTemplateModel( action: custom_action.Action.delete, uuid: prevSubspace.uuid)); @@ -624,13 +622,13 @@ class SpaceManagementBloc } if (newSubspaces != null) { - for (var newSubspace in newSubspaces) { + for (final newSubspace in newSubspaces) { // Tag without UUID - if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) { - final List tagUpdates = []; + if (newSubspace.uuid == null || newSubspace.uuid!.isEmpty) { + final tagUpdates = []; if (newSubspace.tags != null) { - for (var tag in newSubspace.tags!) { + for (final tag in newSubspace.tags!) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.add, newTagUuid: tag.uuid == '' ? null : tag.uuid, @@ -648,14 +646,14 @@ class SpaceManagementBloc if (prevSubspaces != null && newSubspaces != null) { final newSubspaceMap = { - for (var subspace in newSubspaces) subspace.uuid: subspace + for (final subspace in newSubspaces) subspace.uuid: subspace }; - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { final newSubspace = newSubspaceMap[prevSubspace.uuid]; if (newSubspace != null) { - final List tagSubspaceUpdates = + final tagSubspaceUpdates = processTagUpdates(prevSubspace.tags, newSubspace.tags); subspaceUpdates.add(UpdateSubspaceTemplateModel( action: custom_action.Action.update, @@ -669,7 +667,7 @@ class SpaceManagementBloc final response = await _api.updateSpace( communityId: communityUuid, - spaceId: space.uuid!, + spaceId: space.uuid, name: space.name, parentId: space.parent?.uuid, isPrivate: space.isPrivate, @@ -683,7 +681,7 @@ class SpaceManagementBloc projectId: projectUuid); } else { // Call create if the space does not have a UUID - List tagBodyModels = space.tags != null + var tagBodyModels = space.tags != null ? space.tags!.map((tag) => tag.toCreateTagBodyModel()).toList() : []; @@ -731,17 +729,17 @@ class SpaceManagementBloc void visit(SpaceModel space) { if (!result.contains(space)) { result.add(space); - for (var child in spaces.where((s) => s.parent == space)) { + for (final child in spaces.where((s) => s.parent == space)) { visit(child); } } } - for (var space in topLevelSpaces) { + for (final space in topLevelSpaces) { visit(space); } - for (var space in spaces) { + for (final space in spaces) { if (!result.contains(space)) { result.add(space); } @@ -749,7 +747,7 @@ class SpaceManagementBloc return result.toList(); // Convert back to a list } - void _onLoadSpaceModel( + Future _onLoadSpaceModel( SpaceModelLoadEvent event, Emitter emit) async { emit(SpaceManagementLoading()); @@ -760,9 +758,9 @@ class SpaceManagementBloc ? spaceTreeState.filteredCommunity : spaceTreeState.communityList; - List communities = filteredCommunities; + final communities = filteredCommunities; - var prevSpaceModels = await fetchSpaceModels(); + final prevSpaceModels = await fetchSpaceModels(); emit(SpaceModelLoaded( communities: communities, @@ -778,11 +776,11 @@ class SpaceManagementBloc List? prevTags, List? newTags, ) { - final List tagUpdates = []; + final tagUpdates = []; final processedTags = {}; if (prevTags == null && newTags != null) { - for (var newTag in newTags) { + for (final newTag in newTags) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.add, tag: newTag.tag, @@ -796,7 +794,7 @@ class SpaceManagementBloc if (newTags != null || prevTags != null) { // Case 1: Tags deleted if (prevTags != null && newTags != null) { - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { final existsInNew = newTags.any((newTag) => newTag.uuid == prevTag.uuid); if (!existsInNew) { @@ -805,7 +803,7 @@ class SpaceManagementBloc } } } else if (prevTags != null && newTags == null) { - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.delete, uuid: prevTag.uuid)); } @@ -815,7 +813,7 @@ class SpaceManagementBloc if (newTags != null) { final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {}; - for (var newTag in newTags) { + for (final newTag in newTags) { // Tag without UUID if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) && !processedTags.contains(newTag.tag)) { @@ -831,9 +829,9 @@ class SpaceManagementBloc // Case 3: Tags updated if (prevTags != null && newTags != null) { - final newTagMap = {for (var tag in newTags) tag.uuid: tag}; + final newTagMap = {for (final tag in newTags) tag.uuid: tag}; - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { final newTag = newTagMap[prevTag.uuid]; if (newTag != null) { tagUpdates.add(TagModelUpdate( @@ -852,9 +850,9 @@ class SpaceManagementBloc List findMatchingSpaces( List spaces, String targetUuid) { - List matched = []; + final matched = []; - for (var space in spaces) { + for (final space in spaces) { if (space.uuid == targetUuid) { matched.add(space); } diff --git a/lib/pages/spaces_management/all_spaces/bloc/space_management_event.dart b/lib/pages/spaces_management/all_spaces/bloc/space_management_event.dart index 8a9db432..b6c90304 100644 --- a/lib/pages/spaces_management/all_spaces/bloc/space_management_event.dart +++ b/lib/pages/spaces_management/all_spaces/bloc/space_management_event.dart @@ -166,10 +166,10 @@ class SpaceModelLoadEvent extends SpaceManagementEvent { class UpdateSpaceModelCache extends SpaceManagementEvent { final SpaceTemplateModel updatedModel; - UpdateSpaceModelCache(this.updatedModel); + const UpdateSpaceModelCache(this.updatedModel); } class DeleteSpaceModelFromCache extends SpaceManagementEvent { final String deletedUuid; - DeleteSpaceModelFromCache(this.deletedUuid); + const DeleteSpaceModelFromCache(this.deletedUuid); } diff --git a/lib/pages/spaces_management/all_spaces/bloc/space_management_state.dart b/lib/pages/spaces_management/all_spaces/bloc/space_management_state.dart index 3efa7c00..361be6c9 100644 --- a/lib/pages/spaces_management/all_spaces/bloc/space_management_state.dart +++ b/lib/pages/spaces_management/all_spaces/bloc/space_management_state.dart @@ -40,7 +40,10 @@ class BlankState extends SpaceManagementState { final List allTags; BlankState( - {required this.communities, required this.products, this.spaceModels, required this.allTags}); + {required this.communities, + required this.products, + this.spaceModels, + required this.allTags}); } class SpaceCreationSuccess extends SpaceManagementState { diff --git a/lib/pages/spaces_management/all_spaces/model/base_tag.dart b/lib/pages/spaces_management/all_spaces/model/base_tag.dart index 57f223f4..44babc9e 100644 --- a/lib/pages/spaces_management/all_spaces/model/base_tag.dart +++ b/lib/pages/spaces_management/all_spaces/model/base_tag.dart @@ -16,7 +16,7 @@ abstract class BaseTag { this.location, }) : internalId = internalId ?? const Uuid().v4(); - Map toJson(); + Map toJson(); BaseTag copyWith({ String? tag, ProductModel? product, diff --git a/lib/pages/spaces_management/all_spaces/model/community_model.dart b/lib/pages/spaces_management/all_spaces/model/community_model.dart index d1e27095..23388375 100644 --- a/lib/pages/spaces_management/all_spaces/model/community_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/community_model.dart @@ -27,9 +27,12 @@ class CommunityModel { updatedAt: DateTime.parse(json['updatedAt'] ?? ''), name: json['name'] ?? '', description: json['description'] ?? '', - region: json['region'] != null ? RegionModel.fromJson(json['region']) : null, + region: + json['region'] != null ? RegionModel.fromJson(json['region']) : null, spaces: json['spaces'] != null - ? (json['spaces'] as List).map((space) => SpaceModel.fromJson(space)).toList() + ? (json['spaces'] as List) + .map((space) => SpaceModel.fromJson(space)) + .toList() : [], ); } @@ -42,7 +45,9 @@ class CommunityModel { 'name': name, 'description': description, 'region': region?.toJson(), - 'spaces': spaces.map((space) => space.toMap()).toList(), // Convert spaces to Map + 'spaces': spaces + .map((space) => space.toMap()) + .toList(), // Convert spaces to Map }; } } diff --git a/lib/pages/spaces_management/all_spaces/model/product_model.dart b/lib/pages/spaces_management/all_spaces/model/product_model.dart index 8f905032..9ed528ed 100644 --- a/lib/pages/spaces_management/all_spaces/model/product_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/product_model.dart @@ -1,7 +1,6 @@ +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; -import 'selected_product_model.dart'; - class ProductModel { final String uuid; final String catName; diff --git a/lib/pages/spaces_management/all_spaces/model/selected_product_model.dart b/lib/pages/spaces_management/all_spaces/model/selected_product_model.dart index 91314e42..17fd429c 100644 --- a/lib/pages/spaces_management/all_spaces/model/selected_product_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/selected_product_model.dart @@ -6,7 +6,11 @@ class SelectedProduct { final String productName; final ProductModel? product; - SelectedProduct({required this.productId, required this.count, required this.productName, this.product}); + SelectedProduct( + {required this.productId, + required this.count, + required this.productName, + this.product}); Map toJson() { return { @@ -16,7 +20,7 @@ class SelectedProduct { }; } - @override + @override String toString() { return 'SelectedProduct(productId: $productId, count: $count)'; } diff --git a/lib/pages/spaces_management/all_spaces/model/space_model.dart b/lib/pages/spaces_management/all_spaces/model/space_model.dart index f9c59d24..50cdb36c 100644 --- a/lib/pages/spaces_management/all_spaces/model/space_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/space_model.dart @@ -56,7 +56,7 @@ class SpaceModel { {String? parentInternalId}) { final String internalId = json['internalId'] ?? const Uuid().v4(); - final List children = json['children'] != null + final children = json['children'] != null ? (json['children'] as List).map((childJson) { return SpaceModel.fromJson( childJson, @@ -73,8 +73,8 @@ class SpaceModel { isPrivate: json['isPrivate'] ?? false, invitationCode: json['invitationCode'], subspaces: (json['subspaces'] as List?) - ?.where((e) => e is Map) // Validate type - .map((e) => SubspaceModel.fromJson(e as Map)) + ?.whereType>() // Validate type + .map(SubspaceModel.fromJson) .toList() ?? [], parent: parentInternalId != null @@ -102,8 +102,8 @@ class SpaceModel { ? SpaceTemplateModel.fromJson(json['spaceModel']) : null, tags: (json['productAllocations'] as List?) - ?.where((item) => item is Map) // Validate type - .map((item) => Tag.fromJson(item as Map)) + ?.whereType>() // Validate type + .map(Tag.fromJson) .toList() ?? [], ); @@ -150,7 +150,7 @@ class SpaceModel { extension SpaceExtensions on SpaceModel { List listAllTagValues() { - final List tagValues = []; + final tagValues = []; if (tags != null) { tagValues.addAll( @@ -174,10 +174,10 @@ extension SpaceExtensions on SpaceModel { bool isNoChangesSubmited(String name, icon, SpaceTemplateModel? spaceModel, List? subspaces, List? tags) { - return (name == this.name && + return name == this.name && icon == this.icon && spaceModel == this.spaceModel && subspaces == this.subspaces && - tags == this.tags); + tags == this.tags; } } diff --git a/lib/pages/spaces_management/all_spaces/model/space_response_model.dart b/lib/pages/spaces_management/all_spaces/model/space_response_model.dart index 34df3d30..d698b48b 100644 --- a/lib/pages/spaces_management/all_spaces/model/space_response_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/space_response_model.dart @@ -1,5 +1,4 @@ - -import 'space_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; class SpacesResponse { final List data; diff --git a/lib/pages/spaces_management/all_spaces/model/subspace_model.dart b/lib/pages/spaces_management/all_spaces/model/subspace_model.dart index fd3e780e..9c1defa8 100644 --- a/lib/pages/spaces_management/all_spaces/model/subspace_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/subspace_model.dart @@ -1,9 +1,8 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/utils/constants/action_enum.dart'; import 'package:uuid/uuid.dart'; -import 'tag.dart'; - class SubspaceModel { final String? uuid; String subspaceName; diff --git a/lib/pages/spaces_management/all_spaces/model/tag.dart b/lib/pages/spaces_management/all_spaces/model/tag.dart index a7ec1e15..f17c3d86 100644 --- a/lib/pages/spaces_management/all_spaces/model/tag.dart +++ b/lib/pages/spaces_management/all_spaces/model/tag.dart @@ -6,18 +6,12 @@ import 'package:uuid/uuid.dart'; class Tag extends BaseTag { Tag({ - String? uuid, - required String? tag, - ProductModel? product, - String? internalId, - String? location, - }) : super( - uuid: uuid, - tag: tag, - product: product, - internalId: internalId, - location: location, - ); + super.uuid, + required super.tag, + super.product, + super.internalId, + super.location, + }); factory Tag.fromJson(Map json) { final String internalId = json['internalId'] ?? const Uuid().v4(); @@ -50,6 +44,7 @@ class Tag extends BaseTag { ); } + @override Map toJson() { return { if (uuid != null) 'uuid': uuid, diff --git a/lib/pages/spaces_management/all_spaces/view/spaces_management_page.dart b/lib/pages/spaces_management/all_spaces/view/spaces_management_page.dart index 291e6235..9094ebc0 100644 --- a/lib/pages/spaces_management/all_spaces/view/spaces_management_page.dart +++ b/lib/pages/spaces_management/all_spaces/view/spaces_management_page.dart @@ -2,11 +2,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; -import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_state.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/loaded_space_widget.dart'; +import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/structure_selector/view/center_body_widget.dart'; import 'package:syncrow_web/services/product_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart'; @@ -47,7 +47,7 @@ class SpaceManagementPageState extends State { style: ResponsiveTextTheme.of(context).deviceManagementTitle, ), enableMenuSidebar: false, - centerBody: CenterBodyWidget(), + centerBody: const CenterBodyWidget(), rightBody: const NavigateHomeGridView(), scaffoldBody: BlocBuilder( builder: (context, state) { diff --git a/lib/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart index 0e9f4bd1..71bda2ca 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart @@ -32,8 +32,9 @@ class _AddDeviceWidgetState extends State { void initState() { super.initState(); _scrollController = ScrollController(); - productCounts = - widget.initialSelectedProducts != null ? List.from(widget.initialSelectedProducts!) : []; + productCounts = widget.initialSelectedProducts != null + ? List.from(widget.initialSelectedProducts!) + : []; } @override @@ -96,10 +97,12 @@ class _AddDeviceWidgetState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - _buildActionButton('Cancel', ColorsManager.boxColor, ColorsManager.blackColor, () { + _buildActionButton( + 'Cancel', ColorsManager.boxColor, ColorsManager.blackColor, () { Navigator.of(context).pop(); }), - _buildActionButton('Continue', ColorsManager.secondaryColor, ColorsManager.whiteColors, () { + _buildActionButton('Continue', ColorsManager.secondaryColor, + ColorsManager.whiteColors, () { Navigator.of(context).pop(); if (widget.onProductsSelected != null) { widget.onProductsSelected!(productCounts); @@ -114,7 +117,11 @@ class _AddDeviceWidgetState extends State { Widget _buildDeviceTypeTile(ProductModel product, Size size) { final selectedProduct = productCounts.firstWhere( (p) => p.productId == product.uuid, - orElse: () => SelectedProduct(productId: product.uuid, count: 0, productName: product.catName, product: product), + orElse: () => SelectedProduct( + productId: product.uuid, + count: 0, + productName: product.catName, + product: product), ); return SizedBox( @@ -143,13 +150,17 @@ class _AddDeviceWidgetState extends State { setState(() { if (newCount > 0) { if (!productCounts.contains(selectedProduct)) { - productCounts - .add(SelectedProduct(productId: product.uuid, count: newCount, productName: product.catName, product: product)); + productCounts.add(SelectedProduct( + productId: product.uuid, + count: newCount, + productName: product.catName, + product: product)); } else { selectedProduct.count = newCount; } } else { - productCounts.removeWhere((p) => p.productId == product.uuid); + productCounts + .removeWhere((p) => p.productId == product.uuid); } if (widget.onProductsSelected != null) { @@ -192,7 +203,8 @@ class _AddDeviceWidgetState extends State { height: size.width > 800 ? 35 : 25, child: Text( product.name ?? '', - style: context.textTheme.bodySmall?.copyWith(color: ColorsManager.blackColor), + style: context.textTheme.bodySmall + ?.copyWith(color: ColorsManager.blackColor), textAlign: TextAlign.center, maxLines: 2, overflow: TextOverflow.ellipsis, diff --git a/lib/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart index 66f1a026..18dec3a1 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart @@ -9,7 +9,7 @@ import 'package:syncrow_web/utils/color_manager.dart'; class BlankCommunityWidget extends StatefulWidget { final List communities; - BlankCommunityWidget({required this.communities}); + const BlankCommunityWidget({super.key, required this.communities}); @override _BlankCommunityWidgetState createState() => _BlankCommunityWidgetState(); @@ -19,7 +19,7 @@ class _BlankCommunityWidgetState extends State { @override Widget build(BuildContext context) { return Expanded( - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, // Parent container with white background child: GridView.builder( diff --git a/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_action_button.dart b/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_action_button.dart index f5188c1e..49a19681 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_action_button.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_action_button.dart @@ -36,7 +36,7 @@ class CommunityStructureHeaderActionButtons extends StatelessWidget { children: [ if (isSave) CommunityStructureHeaderButton( - label: "Save", + label: 'Save', icon: const Icon(Icons.save, size: 18, color: ColorsManager.spaceColor), onPressed: onSave, @@ -44,19 +44,19 @@ class CommunityStructureHeaderActionButtons extends StatelessWidget { ), if (canShowActions) ...[ CommunityStructureHeaderButton( - label: "Edit", + label: 'Edit', svgAsset: Assets.editSpace, onPressed: onEdit, theme: theme, ), CommunityStructureHeaderButton( - label: "Duplicate", + label: 'Duplicate', svgAsset: Assets.duplicate, onPressed: onDuplicate, theme: theme, ), CommunityStructureHeaderButton( - label: "Delete", + label: 'Delete', svgAsset: Assets.spaceDelete, onPressed: onDelete, theme: theme, diff --git a/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart index 6bc35cca..9a45d76a 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart @@ -14,7 +14,7 @@ class CommunityStructureHeader extends StatefulWidget { final TextEditingController nameController; final VoidCallback onSave; final VoidCallback onDelete; - final VoidCallback onEdit; + final VoidCallback onEdit; final VoidCallback onDuplicate; final VoidCallback onEditName; diff --git a/lib/pages/spaces_management/all_spaces/widgets/community_structure_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/community_structure_widget.dart index 4f68fb7e..1e882d8a 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/community_structure_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/community_structure_widget.dart @@ -3,24 +3,23 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; - // Syncrow project imports import 'package:syncrow_web/pages/common/buttons/add_space_button.dart'; import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/connection_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/connection_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/space_card_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/space_container_widget.dart'; @@ -41,7 +40,8 @@ class CommunityStructureArea extends StatefulWidget { final List projectTags; CommunityStructureArea( - {this.selectedCommunity, + {super.key, + this.selectedCommunity, this.selectedSpace, required this.communities, this.products, @@ -120,7 +120,7 @@ class _CommunityStructureAreaState extends State { ); } - Size screenSize = MediaQuery.of(context).size; + final screenSize = MediaQuery.of(context).size; return Expanded( child: GestureDetector( onTap: () { @@ -173,16 +173,16 @@ class _CommunityStructureAreaState extends State { children: [ InteractiveViewer( transformationController: _transformationController, - boundaryMargin: EdgeInsets.all(500), + boundaryMargin: const EdgeInsets.all(500), minScale: 0.5, maxScale: 3.0, constrained: false, - child: Container( + child: SizedBox( width: canvasWidth, height: canvasHeight, child: Stack( children: [ - for (var connection in connections) + for (final connection in connections) Opacity( opacity: ConnectionHelper.isHighlightedConnection( connection, widget.selectedSpace) @@ -191,7 +191,7 @@ class _CommunityStructureAreaState extends State { child: CustomPaint( painter: CurvedLinePainter([connection])), ), - for (var entry in spaces.asMap().entries) + for (final entry in spaces.asMap().entries) if (entry.value.status != SpaceStatus.deleted && entry.value.status != SpaceStatus.parentDeleted) Positioned( @@ -214,7 +214,7 @@ class _CommunityStructureAreaState extends State { _updateNodePosition(entry.value, newPosition); }, buildSpaceContainer: (int index) { - final bool isHighlighted = + final isHighlighted = SpaceHelper.isHighlightedSpace( spaces[index], widget.selectedSpace); @@ -267,9 +267,9 @@ class _CommunityStructureAreaState extends State { canvasHeight += 200; } if (node.position.dx <= 200) { - double shiftAmount = 200; + const double shiftAmount = 200; canvasWidth += shiftAmount; - for (var n in spaces) { + for (final n in spaces) { n.position = Offset(n.position.dx + shiftAmount, n.position.dy); } } @@ -280,7 +280,7 @@ class _CommunityStructureAreaState extends State { } void _adjustCanvasSizeForSpaces() { - for (var space in spaces) { + for (final space in spaces) { if (space.position.dx >= canvasWidth - 200) { canvasWidth = space.position.dx + 200; } @@ -324,7 +324,7 @@ class _CommunityStructureAreaState extends State { position ?? ConnectionHelper.getCenterPosition(screenSize); } - SpaceModel newSpace = SpaceModel( + final newSpace = SpaceModel( name: name, icon: icon, position: newPosition, @@ -336,7 +336,7 @@ class _CommunityStructureAreaState extends State { tags: tags); if (parentIndex != null) { - SpaceModel parentSpace = spaces[parentIndex]; + final parentSpace = spaces[parentIndex]; parentSpace.internalId = spaces[parentIndex].internalId; newSpace.parent = parentSpace; final newConnection = Connection( @@ -406,7 +406,7 @@ class _CommunityStructureAreaState extends State { SpaceStatus.modified; // Mark as modified } - for (var space in spaces) { + for (final space in spaces) { if (space.internalId == widget.selectedSpace?.internalId) { space.status = SpaceStatus.modified; space.subspaces = subspaces; @@ -430,8 +430,8 @@ class _CommunityStructureAreaState extends State { } List flattenSpaces(List spaces) { - List result = []; - Map idToSpace = {}; + final result = []; + final idToSpace = {}; void flatten(SpaceModel space) { if (space.status == SpaceStatus.deleted || @@ -441,16 +441,16 @@ class _CommunityStructureAreaState extends State { result.add(space); idToSpace[space.internalId] = space; - for (var child in space.children) { + for (final child in space.children) { flatten(child); } } - for (var space in spaces) { + for (final space in spaces) { flatten(space); } - for (var space in result) { + for (final space in result) { if (space.parent != null) { space.parent = idToSpace[space.parent!.internalId]; } @@ -460,12 +460,12 @@ class _CommunityStructureAreaState extends State { } List createConnections(List spaces) { - List connections = []; + final connections = []; void addConnections(SpaceModel parent, String direction) { if (parent.status == SpaceStatus.deleted) return; - for (var child in parent.children) { + for (final child in parent.children) { if (child.status == SpaceStatus.deleted) continue; connections.add( @@ -480,8 +480,8 @@ class _CommunityStructureAreaState extends State { } } - for (var space in spaces) { - addConnections(space, "down"); + for (final space in spaces) { + addConnections(space, 'down'); } return connections; @@ -492,7 +492,7 @@ class _CommunityStructureAreaState extends State { return; } - List spacesToSave = spaces.where((space) { + final spacesToSave = spaces.where((space) { return space.status == SpaceStatus.newSpace || space.status == SpaceStatus.modified || space.status == SpaceStatus.deleted; @@ -502,7 +502,7 @@ class _CommunityStructureAreaState extends State { return; } - String communityUuid = widget.selectedCommunity!.uuid; + final communityUuid = widget.selectedCommunity!.uuid; context.read().add(SaveSpacesEvent( context, spaces: spacesToSave, @@ -513,7 +513,7 @@ class _CommunityStructureAreaState extends State { void _onDelete() { if (widget.selectedSpace != null) { setState(() { - for (var space in spaces) { + for (final space in spaces) { if (space.internalId == widget.selectedSpace?.internalId) { space.status = SpaceStatus.deleted; _markChildrenAsDeleted(space); @@ -526,7 +526,7 @@ class _CommunityStructureAreaState extends State { } void _markChildrenAsDeleted(SpaceModel parent) { - for (var child in parent.children) { + for (final child in parent.children) { child.status = SpaceStatus.parentDeleted; _markChildrenAsDeleted(child); @@ -543,11 +543,11 @@ class _CommunityStructureAreaState extends State { } void _moveToSpace(SpaceModel space) { - final double viewportWidth = MediaQuery.of(context).size.width; - final double viewportHeight = MediaQuery.of(context).size.height; + final viewportWidth = MediaQuery.of(context).size.width; + final viewportHeight = MediaQuery.of(context).size.height; - final double dx = -space.position.dx + (viewportWidth / 2) - 400; - final double dy = -space.position.dy + (viewportHeight / 2) - 300; + final dx = -space.position.dx + (viewportWidth / 2) - 400; + final dy = -space.position.dy + (viewportHeight / 2) - 300; _transformationController.value = Matrix4.identity() ..translate(dx, dy) @@ -578,10 +578,10 @@ class _CommunityStructureAreaState extends State { return Offset(parent.position.dx, parent.position.dy + verticalGap); } else { // More children → arrange them spaced horizontally - double totalWidth = (parent.children.length) * (nodeWidth + 60); - double startX = parent.position.dx - (totalWidth / 2); + final totalWidth = (parent.children.length) * (nodeWidth + 60); + final startX = parent.position.dx - (totalWidth / 2); - double childX = startX + (parent.children.length * (nodeWidth + 60)); + final childX = startX + (parent.children.length * (nodeWidth + 60)); return Offset(childX, parent.position.dy + verticalGap); } } @@ -599,15 +599,15 @@ class _CommunityStructureAreaState extends State { double calculateSubtreeWidth(SpaceModel node) { if (node.children.isEmpty) return nodeWidth; double totalWidth = 0; - for (var child in node.children) { + for (final child in node.children) { totalWidth += calculateSubtreeWidth(child) + horizontalGap; } return totalWidth - horizontalGap; } void layoutSubtree(SpaceModel node, double startX, double y) { - double subtreeWidth = calculateSubtreeWidth(node); - double centerX = startX + subtreeWidth / 2 - nodeWidth / 2; + final subtreeWidth = calculateSubtreeWidth(node); + final centerX = startX + subtreeWidth / 2 - nodeWidth / 2; node.position = Offset(centerX, y); canvasRightEdge = max(canvasRightEdge, centerX + nodeWidth); @@ -617,9 +617,9 @@ class _CommunityStructureAreaState extends State { final child = node.children.first; layoutSubtree(child, centerX, y + verticalGap); } else { - double childX = startX; - for (var child in node.children) { - double childWidth = calculateSubtreeWidth(child); + var childX = startX; + for (final child in node.children) { + final childWidth = calculateSubtreeWidth(child); layoutSubtree(child, childX, y + verticalGap); childX += childWidth + horizontalGap; } @@ -627,7 +627,7 @@ class _CommunityStructureAreaState extends State { } // ⚡ New: layout each root separately - final List roots = spaces + final roots = spaces .where((s) => s.parent == null && s.status != SpaceStatus.deleted && @@ -635,11 +635,11 @@ class _CommunityStructureAreaState extends State { .toList(); double currentX = 100; // start some margin from left - double currentY = 100; // top margin + const double currentY = 100; // top margin - for (var root in roots) { + for (final root in roots) { layoutSubtree(root, currentX, currentY); - double rootWidth = calculateSubtreeWidth(root); + final rootWidth = calculateSubtreeWidth(root); currentX += rootWidth + rootGap; } @@ -659,7 +659,7 @@ class _CommunityStructureAreaState extends State { return AlertDialog( backgroundColor: ColorsManager.whiteColors, title: Text( - "Duplicate Space", + 'Duplicate Space', textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -671,11 +671,11 @@ class _CommunityStructureAreaState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text("Are you sure you want to duplicate?", + Text('Are you sure you want to duplicate?', textAlign: TextAlign.center, style: Theme.of(context).textTheme.headlineSmall), const SizedBox(height: 15), - Text("All the child spaces will be duplicated.", + Text('All the child spaces will be duplicated.', textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -693,7 +693,7 @@ class _CommunityStructureAreaState extends State { onPressed: () { Navigator.of(context).pop(); }, - label: "Cancel", + label: 'Cancel', ), ), const SizedBox(width: 10), @@ -731,16 +731,16 @@ class _CommunityStructureAreaState extends State { void _duplicateSpace(SpaceModel space) { setState(() { - SpaceModel? parent = space.parent; + final parent = space.parent; - SpaceModel duplicated = _deepCloneSpaceTree(space, parent: parent); + final duplicated = _deepCloneSpaceTree(space, parent: parent); duplicated.position = Offset(space.position.dx + 300, space.position.dy + 100); - List duplicatedSubtree = []; + final duplicatedSubtree = []; void collectSubtree(SpaceModel node) { duplicatedSubtree.add(node); - for (var child in node.children) { + for (final child in node.children) { collectSubtree(child); } } @@ -782,7 +782,7 @@ class _CommunityStructureAreaState extends State { parent: parent, ); - for (var child in original.children) { + for (final child in original.children) { final duplicatedChild = _deepCloneSpaceTree(child, parent: newSpace); newSpace.children.add(duplicatedChild); diff --git a/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart index 2289819b..bd8c0a98 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart @@ -7,11 +7,10 @@ class CounterWidget extends StatefulWidget { final bool isCreate; const CounterWidget( - {Key? key, + {super.key, this.initialCount = 0, required this.onCountChanged, - required this.isCreate}) - : super(key: key); + required this.isCreate}); @override State createState() => _CounterWidgetState(); @@ -55,7 +54,8 @@ class _CounterWidgetState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - _buildCounterButton(Icons.remove, _decrementCounter,!widget.isCreate ), + _buildCounterButton( + Icons.remove, _decrementCounter, !widget.isCreate), const SizedBox(width: 8), Text( '$_counter', @@ -69,12 +69,15 @@ class _CounterWidgetState extends State { ); } - Widget _buildCounterButton(IconData icon, VoidCallback onPressed, bool isDisabled) { + Widget _buildCounterButton( + IconData icon, VoidCallback onPressed, bool isDisabled) { return GestureDetector( - onTap: isDisabled? null: onPressed, + onTap: isDisabled ? null : onPressed, child: Icon( icon, - color: isDisabled? ColorsManager.spaceColor.withOpacity(0.3): ColorsManager.spaceColor, + color: isDisabled + ? ColorsManager.spaceColor.withValues(alpha: 0.3) + : ColorsManager.spaceColor, size: 18, ), ); diff --git a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/devices_part_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/devices_part_widget.dart index 94896554..caa71183 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/devices_part_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/devices_part_widget.dart @@ -1,12 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; - -import '../../../../../common/edit_chip.dart'; -import '../../../../../utils/color_manager.dart'; -import '../../../helper/tag_helper.dart'; -import '../../../space_model/widgets/button_content_widget.dart'; -import '../../model/subspace_model.dart'; -import '../../model/tag.dart'; +import 'package:syncrow_web/common/edit_chip.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; +import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; class DevicesPartWidget extends StatelessWidget { const DevicesPartWidget({ @@ -28,73 +27,73 @@ class DevicesPartWidget extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - (tags?.isNotEmpty == true || - subspaces?.any( - (subspace) => subspace.tags?.isNotEmpty == true) == - true) - ? SizedBox( - width: screenWidth * 0.25, - child: Container( - padding: const EdgeInsets.all(8.0), - decoration: BoxDecoration( - color: ColorsManager.textFieldGreyColor, - borderRadius: BorderRadius.circular(15), - border: Border.all( - color: ColorsManager.textFieldGreyColor, - width: 3.0, // Border width - ), - ), - child: Wrap( - spacing: 8.0, - runSpacing: 8.0, - children: [ - // Combine tags from spaceModel and subspaces - ...TagHelper.groupTags([ - ...?tags, - ...?subspaces?.expand((subspace) => subspace.tags ?? []) - ]).entries.map( - (entry) => Chip( - avatar: SizedBox( - width: 24, - height: 24, - child: SvgPicture.asset( - entry.key.icon ?? 'assets/icons/gateway.svg', - fit: BoxFit.contain, - ), - ), - label: Text( - 'x${entry.value}', // Show count - style: Theme.of(context) - .textTheme - .bodySmall - ?.copyWith(color: ColorsManager.spaceColor), - ), - backgroundColor: ColorsManager.whiteColors, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16), - side: const BorderSide( - color: ColorsManager.spaceColor, - ), - ), + if (tags?.isNotEmpty == true || + subspaces?.any((subspace) => subspace.tags?.isNotEmpty == true) == + true) + SizedBox( + width: screenWidth * 0.25, + child: Container( + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: ColorsManager.textFieldGreyColor, + borderRadius: BorderRadius.circular(15), + border: Border.all( + color: ColorsManager.textFieldGreyColor, + width: 3.0, // Border width + ), + ), + child: Wrap( + spacing: 8.0, + runSpacing: 8.0, + children: [ + // Combine tags from spaceModel and subspaces + ...TagHelper.groupTags([ + ...?tags, + ...?subspaces?.expand((subspace) => subspace.tags ?? []) + ]).entries.map( + (entry) => Chip( + avatar: SizedBox( + width: 24, + height: 24, + child: SvgPicture.asset( + entry.key.icon ?? 'assets/icons/gateway.svg', + fit: BoxFit.contain, ), ), + label: Text( + 'x${entry.value}', // Show count + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: ColorsManager.spaceColor), + ), + backgroundColor: ColorsManager.whiteColors, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: const BorderSide( + color: ColorsManager.spaceColor, + ), + ), + ), + ), - EditChip(onTap: onEditChip) - ], - ), - ), - ) - : TextButton( - onPressed: onTextButtonPressed, - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - ), - child: ButtonContentWidget( - icon: Icons.add, - label: 'Add Devices', - disabled: isTagsAndSubspaceModelDisabled, - ), - ) + EditChip(onTap: onEditChip) + ], + ), + ), + ) + else + TextButton( + onPressed: onTextButtonPressed, + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + ), + child: ButtonContentWidget( + icon: Icons.add, + label: 'Add Devices', + disabled: isTagsAndSubspaceModelDisabled, + ), + ) ], ); } diff --git a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart index 59a100a3..94467180 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; -import '../../../../../utils/color_manager.dart'; -import '../../../../../utils/constants/assets.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; +import 'package:syncrow_web/utils/constants/assets.dart'; class IconChoosePartWidget extends StatelessWidget { const IconChoosePartWidget({ diff --git a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart index cd9ae470..ceedad63 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart @@ -1,9 +1,8 @@ import 'package:flutter/material.dart'; - -import '../../../../../utils/color_manager.dart'; -import '../../../../../utils/constants/assets.dart'; -import '../../../space_model/models/space_template_model.dart'; -import '../../../space_model/widgets/button_content_widget.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; +import 'package:syncrow_web/utils/constants/assets.dart'; class SpaceModelLinkingWidget extends StatelessWidget { const SpaceModelLinkingWidget({ @@ -23,66 +22,67 @@ class SpaceModelLinkingWidget extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - selectedSpaceModel == null - ? TextButton( - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - ), - onPressed: onPressed, - child: ButtonContentWidget( - svgAssets: Assets.link, - label: 'Link a space model', - disabled: isSpaceModelDisabled, - ), - ) - : Container( - width: screenWidth * 0.25, - padding: const EdgeInsets.symmetric( - vertical: 10.0, horizontal: 16.0), - decoration: BoxDecoration( - color: ColorsManager.boxColor, - borderRadius: BorderRadius.circular(10), - ), - child: Wrap( - spacing: 8.0, - runSpacing: 8.0, - children: [ - Chip( - label: Text( - selectedSpaceModel?.modelName ?? '', - style: Theme.of(context) - .textTheme - .bodyMedium! - .copyWith(color: ColorsManager.spaceColor), + if (selectedSpaceModel == null) + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + ), + onPressed: onPressed, + child: ButtonContentWidget( + svgAssets: Assets.link, + label: 'Link a space model', + disabled: isSpaceModelDisabled, + ), + ) + else + Container( + width: screenWidth * 0.25, + padding: + const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0), + decoration: BoxDecoration( + color: ColorsManager.boxColor, + borderRadius: BorderRadius.circular(10), + ), + child: Wrap( + spacing: 8.0, + runSpacing: 8.0, + children: [ + Chip( + label: Text( + selectedSpaceModel?.modelName ?? '', + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(color: ColorsManager.spaceColor), + ), + backgroundColor: ColorsManager.whiteColors, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: const BorderSide( + color: ColorsManager.transparentColor, + width: 0, + ), + ), + deleteIcon: Container( + width: 24, + height: 24, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: ColorsManager.lightGrayColor, + width: 1.5, ), - backgroundColor: ColorsManager.whiteColors, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - side: const BorderSide( - color: ColorsManager.transparentColor, - width: 0, - ), - ), - deleteIcon: Container( - width: 24, - height: 24, - decoration: BoxDecoration( - shape: BoxShape.circle, - border: Border.all( - color: ColorsManager.lightGrayColor, - width: 1.5, - ), - ), - child: const Icon( - Icons.close, - size: 16, - color: ColorsManager.lightGrayColor, - ), - ), - onDeleted: onDeleted), - ], - ), - ), + ), + child: const Icon( + Icons.close, + size: 16, + color: ColorsManager.lightGrayColor, + ), + ), + onDeleted: onDeleted), + ], + ), + ), ], ); } diff --git a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart index 600cb8ad..5700b9c5 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; -import '../../../../../utils/color_manager.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; class SpaceNameTextfieldWidget extends StatelessWidget { SpaceNameTextfieldWidget({ diff --git a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.dart index e518877a..868eefe5 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.dart @@ -1,10 +1,9 @@ import 'package:flutter/material.dart'; - -import '../../../../../common/edit_chip.dart'; -import '../../../../../utils/color_manager.dart'; -import '../../../space_model/widgets/button_content_widget.dart'; -import '../../../space_model/widgets/subspace_name_label_widget.dart'; -import '../../model/subspace_model.dart'; +import 'package:syncrow_web/common/edit_chip.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; class SubSpacePartWidget extends StatefulWidget { SubSpacePartWidget({ @@ -30,71 +29,72 @@ class _SubSpacePartWidgetState extends State { Widget build(BuildContext context) { return Column( children: [ - widget.subspaces == null || widget.subspaces!.isEmpty - ? TextButton( - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - overlayColor: ColorsManager.transparentColor, + if (widget.subspaces == null || widget.subspaces!.isEmpty) + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + overlayColor: ColorsManager.transparentColor, + ), + onPressed: widget.onPressed, + child: ButtonContentWidget( + icon: Icons.add, + label: 'Create Sub Spaces', + disabled: widget.isTagsAndSubspaceModelDisabled, + ), + ) + else + SizedBox( + width: widget.screenWidth * 0.25, + child: Container( + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: ColorsManager.textFieldGreyColor, + borderRadius: BorderRadius.circular(15), + border: Border.all( + color: ColorsManager.textFieldGreyColor, + width: 3.0, // Border width ), - onPressed: widget.onPressed, - child: ButtonContentWidget( - icon: Icons.add, - label: 'Create Sub Spaces', - disabled: widget.isTagsAndSubspaceModelDisabled, - ), - ) - : SizedBox( - width: widget.screenWidth * 0.25, - child: Container( - padding: const EdgeInsets.all(8.0), - decoration: BoxDecoration( - color: ColorsManager.textFieldGreyColor, - borderRadius: BorderRadius.circular(15), - border: Border.all( - color: ColorsManager.textFieldGreyColor, - width: 3.0, // Border width - ), - ), - child: Wrap( - spacing: 8.0, - runSpacing: 8.0, - children: [ - if (widget.subspaces != null) - ...widget.subspaces!.map((subspace) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SubspaceNameDisplayWidget( - text: subspace.subspaceName, - validateName: (updatedName) { - bool nameExists = widget.subspaces!.any((s) { - bool isSameId = - s.internalId == subspace.internalId; - bool isSameName = - s.subspaceName.trim().toLowerCase() == - updatedName.trim().toLowerCase(); + ), + child: Wrap( + spacing: 8.0, + runSpacing: 8.0, + children: [ + if (widget.subspaces != null) + ...widget.subspaces!.map((subspace) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SubspaceNameDisplayWidget( + text: subspace.subspaceName, + validateName: (updatedName) { + final nameExists = widget.subspaces!.any((s) { + final isSameId = + s.internalId == subspace.internalId; + final isSameName = + s.subspaceName.trim().toLowerCase() == + updatedName.trim().toLowerCase(); - return !isSameId && isSameName; - }); + return !isSameId && isSameName; + }); - return !nameExists; - }, - onNameChanged: (updatedName) { - setState(() { - subspace.subspaceName = updatedName; - }); - }, - ), - ], - ); - }), - EditChip( - onTap: widget.editChipOnTap, - ) - ], - ), - ), - ) + return !nameExists; + }, + onNameChanged: (updatedName) { + setState(() { + subspace.subspaceName = updatedName; + }); + }, + ), + ], + ); + }), + EditChip( + onTap: widget.editChipOnTap, + ) + ], + ), + ), + ) ], ); } diff --git a/lib/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart b/lib/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart index d8291110..d0c3bd83 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart @@ -19,15 +19,11 @@ class CurvedLinePainter extends CustomPainter { return; // Nothing to paint if there are no connections } - for (var connection in connections) { + for (final connection in connections) { // Ensure positions are valid before drawing lines - if (connection.endSpace.position == null) { - continue; - } - - Offset start = connection.startSpace.position + + final start = connection.startSpace.position + const Offset(75, 60); // Center bottom of start space - Offset end = connection.endSpace.position + + final end = connection.endSpace.position + const Offset(75, 0); // Center top of end space // Curved line for down connections diff --git a/lib/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart b/lib/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart index 8cf30f7c..f6f7bded 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart @@ -9,7 +9,6 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_mo import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/devices_part_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart'; @@ -99,9 +98,9 @@ class CreateSpaceDialogState extends State { @override Widget build(BuildContext context) { - bool isSpaceModelDisabled = (tags != null && tags!.isNotEmpty || - subspaces != null && subspaces!.isNotEmpty); - bool isTagsAndSubspaceModelDisabled = (selectedSpaceModel != null); + final isSpaceModelDisabled = tags != null && tags!.isNotEmpty || + subspaces != null && subspaces!.isNotEmpty; + final isTagsAndSubspaceModelDisabled = (selectedSpaceModel != null); final screenWidth = MediaQuery.of(context).size.width; return AlertDialog( @@ -298,7 +297,7 @@ class CreateSpaceDialogState extends State { } else if (isNameFieldExist) { return; } else { - String newName = enteredName.isNotEmpty + final newName = enteredName.isNotEmpty ? enteredName : (widget.name ?? ''); if (newName.isNotEmpty) { @@ -381,7 +380,7 @@ class CreateSpaceDialogState extends State { products: products, existingSubSpaces: existingSubSpaces, onSave: (slectedSubspaces, updatedSubSpaces) { - final List tagsToAppendToSpace = []; + final tagsToAppendToSpace = []; if (slectedSubspaces != null && slectedSubspaces.isNotEmpty) { final updatedIds = @@ -390,11 +389,11 @@ class CreateSpaceDialogState extends State { final deletedSubspaces = existingSubSpaces .where((s) => !updatedIds.contains(s.internalId)) .toList(); - for (var s in deletedSubspaces) { + for (final s in deletedSubspaces) { if (s.tags != null) { - s.tags!.forEach( - (tag) => tag.location = null, - ); + for (final tag in s.tags!) { + tag.location = null; + } tagsToAppendToSpace.addAll(s.tags!); } } @@ -403,11 +402,11 @@ class CreateSpaceDialogState extends State { if (existingSubSpaces != null) { final deletedSubspaces = existingSubSpaces; - for (var s in deletedSubspaces) { + for (final s in deletedSubspaces) { if (s.tags != null) { - s.tags!.forEach( - (tag) => tag.location = null, - ); + for (final tag in s.tags!) { + tag.location = null; + } tagsToAppendToSpace.addAll(s.tags!); } } diff --git a/lib/pages/spaces_management/all_spaces/widgets/dialogs/delete_dialogue.dart b/lib/pages/spaces_management/all_spaces/widgets/dialogs/delete_dialogue.dart index 27275be1..dd04bec6 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/dialogs/delete_dialogue.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/dialogs/delete_dialogue.dart @@ -2,9 +2,10 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -void showDeleteConfirmationDialog(BuildContext context, VoidCallback onConfirm, bool isSpace) { - final String title = isSpace ? 'Delete Space' : 'Delete Community'; - final String subtitle = isSpace +void showDeleteConfirmationDialog( + BuildContext context, VoidCallback onConfirm, bool isSpace) { + final title = isSpace ? 'Delete Space' : 'Delete Community'; + final subtitle = isSpace ? 'All the data in the space will be lost' : 'All the data in the community will be lost'; @@ -13,7 +14,8 @@ void showDeleteConfirmationDialog(BuildContext context, VoidCallback onConfirm, barrierDismissible: false, builder: (BuildContext context) { return Dialog( - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)), + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)), child: SizedBox( width: 500, child: Container( @@ -41,7 +43,8 @@ void showDeleteConfirmationDialog(BuildContext context, VoidCallback onConfirm, showProcessingPopup(context, isSpace, onConfirm); }, style: _dialogButtonStyle(ColorsManager.spaceColor), - child: const Text('Continue', style: TextStyle(color: ColorsManager.whiteColors)), + child: const Text('Continue', + style: TextStyle(color: ColorsManager.whiteColors)), ), ], ), @@ -54,15 +57,17 @@ void showDeleteConfirmationDialog(BuildContext context, VoidCallback onConfirm, ); } -void showProcessingPopup(BuildContext context, bool isSpace, VoidCallback onDelete) { - final String title = isSpace ? 'Delete Space' : 'Delete Community'; +void showProcessingPopup( + BuildContext context, bool isSpace, VoidCallback onDelete) { + final title = isSpace ? 'Delete Space' : 'Delete Community'; showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return Dialog( - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)), + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)), child: SizedBox( width: 500, child: Container( @@ -75,7 +80,8 @@ void showProcessingPopup(BuildContext context, bool isSpace, VoidCallback onDele const SizedBox(height: 20), _buildDialogTitle(context, title), const SizedBox(height: 10), - _buildDialogSubtitle(context, 'Are you sure you want to delete?'), + _buildDialogSubtitle( + context, 'Are you sure you want to delete?'), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -83,7 +89,8 @@ void showProcessingPopup(BuildContext context, bool isSpace, VoidCallback onDele ElevatedButton( onPressed: onDelete, style: _dialogButtonStyle(ColorsManager.warningRed), - child: const Text('Delete', style: TextStyle(color: ColorsManager.whiteColors)), + child: const Text('Delete', + style: TextStyle(color: ColorsManager.whiteColors)), ), CancelButton( label: 'Cancel', @@ -104,7 +111,7 @@ Widget _buildWarningIcon() { return Container( width: 50, height: 50, - decoration: BoxDecoration( + decoration: const BoxDecoration( color: ColorsManager.warningRed, shape: BoxShape.circle, ), @@ -123,7 +130,10 @@ Widget _buildDialogSubtitle(BuildContext context, String subtitle) { return Text( subtitle, textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: ColorsManager.grayColor), + style: Theme.of(context) + .textTheme + .bodyMedium + ?.copyWith(color: ColorsManager.grayColor), ); } diff --git a/lib/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart b/lib/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart index 1f719b1a..f3c7dda6 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart @@ -4,8 +4,7 @@ import 'package:syncrow_web/utils/color_manager.dart'; class DuplicateProcessDialog extends StatefulWidget { final VoidCallback onDuplicate; - const DuplicateProcessDialog({required this.onDuplicate, Key? key}) - : super(key: key); + const DuplicateProcessDialog({required this.onDuplicate, super.key}); @override _DuplicateProcessDialogState createState() => _DuplicateProcessDialogState(); @@ -20,7 +19,7 @@ class _DuplicateProcessDialogState extends State { _startDuplication(); } - void _startDuplication() async { + Future _startDuplication() async { WidgetsBinding.instance.addPostFrameCallback((_) { widget.onDuplicate(); }); @@ -55,7 +54,7 @@ class _DuplicateProcessDialogState extends State { ), const SizedBox(height: 15), Text( - "Duplicating in progress", + 'Duplicating in progress', style: Theme.of(context) .textTheme .headlineSmall @@ -70,7 +69,7 @@ class _DuplicateProcessDialogState extends State { ), const SizedBox(height: 15), Text( - "Duplicating successful", + 'Duplicating successful', textAlign: TextAlign.center, style: Theme.of(context) .textTheme diff --git a/lib/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart b/lib/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart index b2a01988..71b9efef 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart @@ -7,10 +7,10 @@ class IconSelectionDialog extends StatelessWidget { final Function(String selectedIcon) onIconSelected; const IconSelectionDialog({ - Key? key, + super.key, required this.spaceIconList, required this.onIconSelected, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -21,21 +21,23 @@ class IconSelectionDialog extends StatelessWidget { elevation: 0, backgroundColor: ColorsManager.transparentColor, child: Container( - width: screenWidth * 0.44, + width: screenWidth * 0.44, height: screenHeight * 0.45, decoration: BoxDecoration( color: ColorsManager.whiteColors, borderRadius: BorderRadius.circular(12), boxShadow: [ BoxShadow( - color: ColorsManager.blackColor.withOpacity(0.2), // Shadow color + color: ColorsManager.blackColor + .withValues(alpha: 0.2), // Shadow color blurRadius: 20, // Spread of the blur offset: const Offset(0, 8), // Offset of the shadow ), ], ), child: AlertDialog( - title: Text('Space Icon',style: Theme.of(context).textTheme.headlineMedium), + title: Text('Space Icon', + style: Theme.of(context).textTheme.headlineMedium), backgroundColor: ColorsManager.whiteColors, content: Container( width: screenWidth * 0.4, diff --git a/lib/pages/spaces_management/all_spaces/widgets/gradient_canvas_border_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/gradient_canvas_border_widget.dart index e1d4e11b..e0ca8827 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/gradient_canvas_border_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/gradient_canvas_border_widget.dart @@ -28,7 +28,7 @@ class GradientCanvasBorderWidget extends StatelessWidget { begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ - ColorsManager.semiTransparentBlackColor.withOpacity(0.1), + ColorsManager.semiTransparentBlackColor.withValues(alpha: 0.1), ColorsManager.transparentColor, ], ), diff --git a/lib/pages/spaces_management/all_spaces/widgets/hoverable_button.dart b/lib/pages/spaces_management/all_spaces/widgets/hoverable_button.dart index 49a863b6..e545f26b 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/hoverable_button.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/hoverable_button.dart @@ -8,11 +8,11 @@ class HoverableButton extends StatefulWidget { final VoidCallback onTap; const HoverableButton({ - Key? key, + super.key, required this.iconPath, required this.text, required this.onTap, - }) : super(key: key); + }); @override State createState() => _HoverableButtonState(); @@ -34,14 +34,17 @@ class _HoverableButtonState extends State { child: SizedBox( width: screenWidth * .07, child: Container( - padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 8), + padding: + const EdgeInsets.symmetric(horizontal: 13, vertical: 8), decoration: BoxDecoration( - color: isHovered ? ColorsManager.warningRed : ColorsManager.whiteColors, + color: isHovered + ? ColorsManager.warningRed + : ColorsManager.whiteColors, borderRadius: BorderRadius.circular(16), boxShadow: [ if (isHovered) BoxShadow( - color: ColorsManager.warningRed.withOpacity(0.4), + color: ColorsManager.warningRed.withValues(alpha: 0.4), blurRadius: 8, offset: const Offset(0, 4), ), diff --git a/lib/pages/spaces_management/all_spaces/widgets/loaded_space_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/loaded_space_widget.dart index d2c72fa7..d2a7c3de 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/loaded_space_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/loaded_space_widget.dart @@ -81,49 +81,51 @@ class _LoadedSpaceViewState extends State { return Stack( clipBehavior: Clip.none, children: [ - widget.shouldNavigateToSpaceModelPage - ? Row( - children: [ - SizedBox(width: 300, child: SpaceTreeView(onSelect: () {})), - Expanded( - child: BlocProvider( - create: (context) => SpaceModelBloc( - BlocProvider.of(context), - api: SpaceModelManagementApi(), - initialSpaceModels: widget.spaceModels ?? [], - ), - child: SpaceModelPage( - products: widget.products, - onSpaceModelsUpdated: _onSpaceModelsUpdated, - projectTags: widget.projectTags, - ), - ), + if (widget.shouldNavigateToSpaceModelPage) + Row( + children: [ + SizedBox(width: 300, child: SpaceTreeView(onSelect: () {})), + Expanded( + child: BlocProvider( + create: (context) => SpaceModelBloc( + BlocProvider.of(context), + api: SpaceModelManagementApi(), + initialSpaceModels: widget.spaceModels ?? [], ), - ], - ) - : Row( - children: [ - SidebarWidget( - communities: widget.communities, - selectedSpaceUuid: - widget.selectedSpace?.uuid ?? widget.selectedCommunity?.uuid ?? '', - onCreateCommunity: (name, description) { - context.read().add( - CreateCommunityEvent(name, description, context), - ); - }, - ), - CommunityStructureArea( - selectedCommunity: widget.selectedCommunity, - selectedSpace: widget.selectedSpace, - spaces: widget.selectedCommunity?.spaces ?? [], + child: SpaceModelPage( products: widget.products, - communities: widget.communities, - spaceModels: _spaceModels, + onSpaceModelsUpdated: _onSpaceModelsUpdated, projectTags: widget.projectTags, ), - ], + ), ), + ], + ) + else + Row( + children: [ + SidebarWidget( + communities: widget.communities, + selectedSpaceUuid: widget.selectedSpace?.uuid ?? + widget.selectedCommunity?.uuid ?? + '', + onCreateCommunity: (name, description) { + context.read().add( + CreateCommunityEvent(name, description, context), + ); + }, + ), + CommunityStructureArea( + selectedCommunity: widget.selectedCommunity, + selectedSpace: widget.selectedSpace, + spaces: widget.selectedCommunity?.spaces ?? [], + products: widget.products, + communities: widget.communities, + spaceModels: _spaceModels, + projectTags: widget.projectTags, + ), + ], + ), const GradientCanvasBorderWidget(), ], ); diff --git a/lib/pages/spaces_management/all_spaces/widgets/selected_products_button_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/selected_products_button_widget.dart index 7076a580..283bffac 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/selected_products_button_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/selected_products_button_widget.dart @@ -13,12 +13,12 @@ class SelectedProductsButtons extends StatelessWidget { final BuildContext context; const SelectedProductsButtons({ - Key? key, + super.key, required this.products, required this.selectedProducts, required this.onProductsUpdated, required this.context, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -86,9 +86,7 @@ class SelectedProductsButtons extends StatelessWidget { builder: (context) => AddDeviceWidget( products: products, initialSelectedProducts: selectedProducts, - onProductsSelected: (selectedProductsMap) { - onProductsUpdated(selectedProductsMap); - }, + onProductsSelected: onProductsUpdated, ), ); } diff --git a/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart index 6149dbda..3e2ad4dd 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart @@ -5,6 +5,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/common/widgets/search_bar.dart'; import 'package:syncrow_web/common/widgets/sidebar_communities_list.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; +import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; @@ -18,8 +19,6 @@ import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/cent import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_event.dart'; import 'package:syncrow_web/utils/style.dart'; -import '../../../space_tree/bloc/space_tree_event.dart'; - class SidebarWidget extends StatefulWidget { final List communities; final String? selectedSpaceUuid; @@ -55,13 +54,15 @@ class _SidebarWidgetState extends State { } void _onScroll() { - if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) { + if (_scrollController.position.pixels >= + _scrollController.position.maxScrollExtent - 100) { // Trigger pagination event final bloc = context.read(); - if (!bloc.state.paginationIsLoading && bloc.state.paginationModel?.hasNext == true) { + if (!bloc.state.paginationIsLoading && + bloc.state.paginationModel.hasNext == true) { bloc.add( PaginationEvent( - bloc.state.paginationModel!, + bloc.state.paginationModel, bloc.state.communityList, ), ); @@ -134,24 +135,28 @@ class _SidebarWidgetState extends State { communities: filteredCommunities, itemBuilder: (context, index) { if (index == filteredCommunities.length) { - final spaceTreeState = context.read().state; + final spaceTreeState = + context.read().state; if (spaceTreeState.paginationIsLoading) { return const Padding( padding: EdgeInsets.all(8.0), - child: Center(child: CircularProgressIndicator()), + child: + Center(child: CircularProgressIndicator()), ); } else { return const SizedBox.shrink(); } } - return _buildCommunityTile(context, filteredCommunities[index]); + return _buildCommunityTile( + context, filteredCommunities[index]); }, ); }, ), ), - if (spaceTreeState.paginationIsLoading || spaceTreeState.isSearching) - Center( + if (spaceTreeState.paginationIsLoading || + spaceTreeState.isSearching) + const Center( child: CircularProgressIndicator(), ) ], @@ -214,7 +219,8 @@ class _SidebarWidgetState extends State { }); context.read().add( - SelectSpaceEvent(selectedCommunity: community, selectedSpace: space), + SelectSpaceEvent( + selectedCommunity: community, selectedSpace: space), ); }, children: space.children @@ -229,8 +235,9 @@ class _SidebarWidgetState extends State { ); } - void _onAddCommunity() => - _selectedId?.isNotEmpty ?? true ? _clearSelection() : _showCreateCommunityDialog(); + void _onAddCommunity() => _selectedId?.isNotEmpty ?? true + ? _clearSelection() + : _showCreateCommunityDialog(); void _clearSelection() { setState(() => _selectedId = ''); diff --git a/lib/pages/spaces_management/all_spaces/widgets/space_card_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/space_card_widget.dart index 7e6e132f..344eddd3 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/space_card_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/space_card_widget.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'plus_button_widget.dart'; // Make sure to import your PlusButtonWidget +import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/plus_button_widget.dart'; // Make sure to import your PlusButtonWidget class SpaceCardWidget extends StatelessWidget { final int index; diff --git a/lib/pages/spaces_management/all_spaces/widgets/space_container_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/space_container_widget.dart index 6f52eb50..e43bccd3 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/space_container_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/space_container_widget.dart @@ -78,7 +78,7 @@ class SpaceContainerWidget extends StatelessWidget { borderRadius: BorderRadius.circular(15), boxShadow: [ BoxShadow( - color: ColorsManager.lightGrayColor.withOpacity(0.5), + color: ColorsManager.lightGrayColor.withValues(alpha: 0.5), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), // Shadow position diff --git a/lib/pages/spaces_management/all_spaces/widgets/space_widget.dart b/lib/pages/spaces_management/all_spaces/widgets/space_widget.dart index 62d8197c..1e805cb3 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/space_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/space_widget.dart @@ -27,7 +27,7 @@ class SpaceWidget extends StatelessWidget { borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( - color: ColorsManager.lightGrayColor.withOpacity(0.5), + color: ColorsManager.lightGrayColor.withValues(alpha: 0.5), spreadRadius: 5, blurRadius: 7, offset: const Offset(0, 3), diff --git a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart index afc0c852..7496eb16 100644 --- a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart +++ b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart @@ -11,7 +11,7 @@ class AssignTagBloc extends Bloc { final initialTags = event.initialTags ?? []; final existingTagCounts = {}; - for (var tag in initialTags) { + for (final tag in initialTags) { if (tag.product != null) { existingTagCounts[tag.product!.uuid] = (existingTagCounts[tag.product!.uuid] ?? 0) + 1; @@ -20,7 +20,7 @@ class AssignTagBloc extends Bloc { final tags = []; - for (var selectedProduct in event.addedProducts) { + for (final selectedProduct in event.addedProducts) { final existingCount = existingTagCounts[selectedProduct.productId] ?? 0; if (selectedProduct.count == 0 || @@ -171,7 +171,7 @@ class AssignTagBloc extends Bloc { List _calculateAvailableTags(List allTags, List selectedTags) { final selectedTagSet = selectedTags - .where((tag) => (tag.tag?.trim().isNotEmpty ?? false)) + .where((tag) => tag.tag?.trim().isNotEmpty ?? false) .map((tag) => tag.tag!.trim()) .toSet(); diff --git a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart index 7d81ffdb..b79fb699 100644 --- a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart +++ b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart @@ -1,6 +1,6 @@ import 'package:equatable/equatable.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; abstract class AssignTagEvent extends Equatable { const AssignTagEvent(); diff --git a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart index 53700a33..3fda79bf 100644 --- a/lib/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart +++ b/lib/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart @@ -27,7 +27,8 @@ class AssignTagLoaded extends AssignTagState { }); @override - List get props => [tags, updatedTags, isSaveEnabled, errorMessage ?? '']; + List get props => + [tags, updatedTags, isSaveEnabled, errorMessage ?? '']; } class AssignTagError extends AssignTagState { diff --git a/lib/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart b/lib/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart index 21ba141c..809dff64 100644 --- a/lib/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart +++ b/lib/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart @@ -7,11 +7,10 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag/views/widgets/save_add_device_row_widget.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'widgets/save_add_device_row_widget.dart'; - class AssignTagDialog extends StatelessWidget { final List? products; final List? subspaces; @@ -39,7 +38,7 @@ class AssignTagDialog extends StatelessWidget { @override Widget build(BuildContext context) { - final List locations = (subspaces ?? []) + final locations = (subspaces ?? []) .map((subspace) => subspace.subspaceName) .toList() ..add('Main Space'); diff --git a/lib/pages/spaces_management/assign_tag/views/widgets/save_add_device_row_widget.dart b/lib/pages/spaces_management/assign_tag/views/widgets/save_add_device_row_widget.dart index a81b7ad0..c5b164cf 100644 --- a/lib/pages/spaces_management/assign_tag/views/widgets/save_add_device_row_widget.dart +++ b/lib/pages/spaces_management/assign_tag/views/widgets/save_add_device_row_widget.dart @@ -1,14 +1,13 @@ import 'package:flutter/material.dart'; +import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; +import 'package:syncrow_web/pages/common/buttons/default_button.dart'; +import 'package:syncrow_web/pages/spaces_management/add_device_type/views/add_device_type_widget.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; -import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; -import 'package:syncrow_web/pages/common/buttons/default_button.dart'; +import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import '../../../add_device_type/views/add_device_type_widget.dart'; -import '../../../helper/tag_helper.dart'; - class SaveAddDeviceRowWidget extends StatelessWidget { const SaveAddDeviceRowWidget({ super.key, diff --git a/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart b/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart index 7df82b5e..4a6548f8 100644 --- a/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart +++ b/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart @@ -3,7 +3,8 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_state.dart'; -class AssignTagModelBloc extends Bloc { +class AssignTagModelBloc + extends Bloc { final List projectTags; AssignTagModelBloc(this.projectTags) : super(AssignTagModelInitial()) { @@ -11,25 +12,29 @@ class AssignTagModelBloc extends Bloc final initialTags = event.initialTags; final existingTagCounts = {}; - for (var tag in initialTags) { + for (final tag in initialTags) { if (tag.product != null) { - existingTagCounts[tag.product!.uuid] = (existingTagCounts[tag.product!.uuid] ?? 0) + 1; + existingTagCounts[tag.product!.uuid] = + (existingTagCounts[tag.product!.uuid] ?? 0) + 1; } } final tags = []; - for (var selectedProduct in event.addedProducts) { + for (final selectedProduct in event.addedProducts) { final existingCount = existingTagCounts[selectedProduct.productId] ?? 0; - if (selectedProduct.count == 0 || selectedProduct.count <= existingCount) { - tags.addAll(initialTags.where((tag) => tag.product?.uuid == selectedProduct.productId)); + if (selectedProduct.count == 0 || + selectedProduct.count <= existingCount) { + tags.addAll(initialTags + .where((tag) => tag.product?.uuid == selectedProduct.productId)); continue; } final missingCount = selectedProduct.count - existingCount; - tags.addAll(initialTags.where((tag) => tag.product?.uuid == selectedProduct.productId)); + tags.addAll(initialTags + .where((tag) => tag.product?.uuid == selectedProduct.productId)); if (missingCount > 0) { tags.addAll(List.generate( @@ -54,7 +59,8 @@ class AssignTagModelBloc extends Bloc on((event, emit) { final currentState = state; - if (currentState is AssignTagModelLoaded && currentState.tags.isNotEmpty) { + if (currentState is AssignTagModelLoaded && + currentState.tags.isNotEmpty) { final tags = List.from(currentState.tags); if (event.index < 0 || event.index >= tags.length) return; @@ -81,10 +87,12 @@ class AssignTagModelBloc extends Bloc on((event, emit) { final currentState = state; - if (currentState is AssignTagModelLoaded && currentState.tags.isNotEmpty) { + if (currentState is AssignTagModelLoaded && + currentState.tags.isNotEmpty) { final tags = List.from(currentState.tags); // Use copyWith for immutability - tags[event.index] = tags[event.index].copyWith(location: event.location); + tags[event.index] = + tags[event.index].copyWith(location: event.location); final updatedTags = _calculateAvailableTags(projectTags, tags); @@ -100,7 +108,8 @@ class AssignTagModelBloc extends Bloc on((event, emit) { final currentState = state; - if (currentState is AssignTagModelLoaded && currentState.tags.isNotEmpty) { + if (currentState is AssignTagModelLoaded && + currentState.tags.isNotEmpty) { final tags = List.from(currentState.tags); emit(AssignTagModelLoaded( @@ -115,8 +124,10 @@ class AssignTagModelBloc extends Bloc on((event, emit) { final currentState = state; - if (currentState is AssignTagModelLoaded && currentState.tags.isNotEmpty) { - final tags = List.from(currentState.tags)..remove(event.tagToDelete); + if (currentState is AssignTagModelLoaded && + currentState.tags.isNotEmpty) { + final tags = List.from(currentState.tags) + ..remove(event.tagToDelete); final updatedTags = _calculateAvailableTags(projectTags, tags); @@ -140,8 +151,10 @@ class AssignTagModelBloc extends Bloc String? _getValidationError(List tags) { // Check for duplicate tags - final nonEmptyTags = - tags.map((tag) => tag.tag?.trim() ?? '').where((tag) => tag.isNotEmpty).toList(); + final nonEmptyTags = tags + .map((tag) => tag.tag?.trim() ?? '') + .where((tag) => tag.isNotEmpty) + .toList(); final duplicateTags = nonEmptyTags .fold>({}, (map, tag) { @@ -162,12 +175,13 @@ class AssignTagModelBloc extends Bloc List _calculateAvailableTags(List allTags, List selectedTags) { final selectedTagSet = selectedTags - .where((tag) => (tag.tag?.trim().isNotEmpty ?? false)) + .where((tag) => tag.tag?.trim().isNotEmpty ?? false) .map((tag) => tag.tag!.trim()) .toSet(); final availableTags = allTags - .where((tag) => tag.tag != null && !selectedTagSet.contains(tag.tag!.trim())) + .where((tag) => + tag.tag != null && !selectedTagSet.contains(tag.tag!.trim())) .toList(); return availableTags; diff --git a/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart b/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart index cb878bde..d62e1523 100644 --- a/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart +++ b/lib/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart @@ -1,6 +1,6 @@ import 'package:equatable/equatable.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; abstract class AssignTagModelEvent extends Equatable { const AssignTagModelEvent(); diff --git a/lib/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart b/lib/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart index 57ed93df..4f0fcee5 100644 --- a/lib/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart +++ b/lib/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart @@ -6,13 +6,12 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_state.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/widgets/RowOfCancelSaveWidget.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'widgets/RowOfCancelSaveWidget.dart'; -import 'widgets/assign_tags_tables_widget.dart'; - class AssignTagModelsDialog extends StatelessWidget { final List? products; final List? subspaces; @@ -30,7 +29,7 @@ class AssignTagModelsDialog extends StatelessWidget { final List projectTags; const AssignTagModelsDialog( - {Key? key, + {super.key, required this.products, required this.subspaces, required this.addedProducts, @@ -43,12 +42,11 @@ class AssignTagModelsDialog extends StatelessWidget { this.otherSpaceModels, this.spaceModel, this.allSpaceModels, - required this.projectTags}) - : super(key: key); + required this.projectTags}); @override Widget build(BuildContext context) { - final List locations = (subspaces ?? []) + final locations = (subspaces ?? []) .map((subspace) => subspace.subspaceName) .toList() ..add('Main Space'); diff --git a/lib/pages/spaces_management/assign_tag_models/views/widgets/RowOfCancelSaveWidget.dart b/lib/pages/spaces_management/assign_tag_models/views/widgets/RowOfCancelSaveWidget.dart index 9b2a1367..72f8be87 100644 --- a/lib/pages/spaces_management/assign_tag_models/views/widgets/RowOfCancelSaveWidget.dart +++ b/lib/pages/spaces_management/assign_tag_models/views/widgets/RowOfCancelSaveWidget.dart @@ -1,18 +1,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; - -import '../../../../../utils/color_manager.dart'; -import '../../../../common/buttons/cancel_button.dart'; -import '../../../../common/buttons/default_button.dart'; -import '../../../all_spaces/model/product_model.dart'; -import '../../../all_spaces/model/tag.dart'; -import '../../../helper/tag_helper.dart'; -import '../../../space_model/models/space_template_model.dart'; -import '../../../space_model/models/subspace_template_model.dart'; -import '../../../space_model/widgets/dialog/create_space_model_dialog.dart'; -import '../../../tag_model/views/add_device_type_model_widget.dart'; -import '../../bloc/assign_tag_model_bloc.dart'; -import '../../bloc/assign_tag_model_state.dart'; +import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; +import 'package:syncrow_web/pages/common/buttons/default_button.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_state.dart'; +import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart'; +import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; class RowOfSaveCancelWidget extends StatelessWidget { const RowOfSaveCancelWidget({ diff --git a/lib/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart b/lib/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart index 0e17a0d7..ee335637 100644 --- a/lib/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart +++ b/lib/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart @@ -1,11 +1,10 @@ import 'package:flutter/material.dart'; +import 'package:syncrow_web/common/dialog_dropdown.dart'; +import 'package:syncrow_web/common/tag_dialog_textfield_dropdown.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; import 'package:uuid/uuid.dart'; -import '../../../../../common/dialog_dropdown.dart'; -import '../../../../../common/tag_dialog_textfield_dropdown.dart'; -import '../../../../../utils/color_manager.dart'; - class AssignTagsTable extends StatelessWidget { const AssignTagsTable({ super.key, diff --git a/lib/pages/spaces_management/create_community/bloc/community_dialog_bloc.dart b/lib/pages/spaces_management/create_community/bloc/community_dialog_bloc.dart index 724ed51a..e52f09bf 100644 --- a/lib/pages/spaces_management/create_community/bloc/community_dialog_bloc.dart +++ b/lib/pages/spaces_management/create_community/bloc/community_dialog_bloc.dart @@ -1,8 +1,9 @@ import 'package:flutter_bloc/flutter_bloc.dart'; -import 'community_dialog_event.dart'; -import 'community_dialog_state.dart'; +import 'package:syncrow_web/pages/spaces_management/create_community/bloc/community_dialog_event.dart'; +import 'package:syncrow_web/pages/spaces_management/create_community/bloc/community_dialog_state.dart'; -class CommunityDialogBloc extends Bloc { +class CommunityDialogBloc + extends Bloc { final List existingCommunityNames; CommunityDialogBloc(this.existingCommunityNames) diff --git a/lib/pages/spaces_management/create_community/view/create_community_dialog.dart b/lib/pages/spaces_management/create_community/view/create_community_dialog.dart index 13e676b5..9321cc1e 100644 --- a/lib/pages/spaces_management/create_community/view/create_community_dialog.dart +++ b/lib/pages/spaces_management/create_community/view/create_community_dialog.dart @@ -1,11 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; +import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/spaces_management/create_community/bloc/community_dialog_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/create_community/bloc/community_dialog_event.dart'; import 'package:syncrow_web/pages/spaces_management/create_community/bloc/community_dialog_state.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; -import 'package:syncrow_web/pages/common/buttons/default_button.dart'; class CreateCommunityDialog extends StatelessWidget { final Function(String name, String description) onCreateCommunity; @@ -43,7 +43,7 @@ class CreateCommunityDialog extends StatelessWidget { borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( - color: ColorsManager.blackColor.withOpacity(0.25), + color: ColorsManager.blackColor.withValues(alpha: 0.25), blurRadius: 20, spreadRadius: 5, offset: const Offset(0, 5), @@ -53,8 +53,8 @@ class CreateCommunityDialog extends StatelessWidget { child: SingleChildScrollView( child: BlocBuilder( builder: (context, state) { - bool isNameValid = true; - bool isNameEmpty = false; + var isNameValid = true; + var isNameEmpty = false; if (state is CommunityNameValidationState) { isNameValid = state.isNameValid; @@ -139,7 +139,7 @@ class CreateCommunityDialog extends StatelessWidget { if (isNameValid && !isNameEmpty) { onCreateCommunity( nameController.text.trim(), - "", + '', ); Navigator.of(context).pop(); } diff --git a/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart b/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart index a2d44553..bd14ff61 100644 --- a/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart +++ b/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart @@ -1,10 +1,9 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_state.dart'; import 'package:syncrow_web/utils/constants/action_enum.dart'; -import 'subspace_event.dart'; -import 'subspace_state.dart'; - class SubSpaceBloc extends Bloc { SubSpaceBloc() : super(SubSpaceState([], [], '', {})) { on((event, emit) { @@ -77,7 +76,7 @@ class SubSpaceBloc extends Bloc { emit(SubSpaceState( updatedSubSpaces, updatedSubspaceModels, - errorMessage , + errorMessage, updatedDuplicates, )); }); diff --git a/lib/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart b/lib/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart index 82df866a..3e54288d 100644 --- a/lib/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart +++ b/lib/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart @@ -5,12 +5,11 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_mo import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart'; import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_state.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/views/widgets/ok_cancel_sub_space_widget.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/views/widgets/textfield_sub_space_dialog_widget.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; -import 'widgets/ok_cancel_sub_space_widget.dart'; -import 'widgets/textfield_sub_space_dialog_widget.dart'; - class CreateSubSpaceDialog extends StatefulWidget { final String dialogTitle; final List? existingSubSpaces; diff --git a/lib/pages/spaces_management/create_subspace/views/widgets/ok_cancel_sub_space_widget.dart b/lib/pages/spaces_management/create_subspace/views/widgets/ok_cancel_sub_space_widget.dart index 3952e105..65bd0193 100644 --- a/lib/pages/spaces_management/create_subspace/views/widgets/ok_cancel_sub_space_widget.dart +++ b/lib/pages/spaces_management/create_subspace/views/widgets/ok_cancel_sub_space_widget.dart @@ -1,12 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; -import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; - -import '../../bloc/subspace_bloc.dart'; -import '../../bloc/subspace_event.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; class OkCancelSubSpaceWidget extends StatelessWidget { const OkCancelSubSpaceWidget({ diff --git a/lib/pages/spaces_management/create_subspace/views/widgets/textfield_sub_space_dialog_widget.dart b/lib/pages/spaces_management/create_subspace/views/widgets/textfield_sub_space_dialog_widget.dart index f655e178..7375a228 100644 --- a/lib/pages/spaces_management/create_subspace/views/widgets/textfield_sub_space_dialog_widget.dart +++ b/lib/pages/spaces_management/create_subspace/views/widgets/textfield_sub_space_dialog_widget.dart @@ -1,14 +1,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart'; -import '../../../../../utils/color_manager.dart'; -import '../../../all_spaces/model/subspace_model.dart'; -import '../../../create_subspace_model/widgets/subspace_chip.dart'; -import '../../../space_model/models/subspace_template_model.dart'; -import '../../bloc/subspace_bloc.dart'; -import '../../bloc/subspace_event.dart'; - class TextFieldSubSpaceDialogWidget extends StatelessWidget { const TextFieldSubSpaceDialogWidget({ super.key, diff --git a/lib/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart b/lib/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart index a331aed2..3337ce04 100644 --- a/lib/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart +++ b/lib/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart @@ -60,7 +60,7 @@ class SubSpaceModelBloc extends Bloc { if (event.subSpace.uuid?.isNotEmpty ?? false) { updatedSubspaceModels.add(UpdateSubspaceTemplateModel( action: Action.delete, - uuid: event.subSpace.uuid!, + uuid: event.subSpace.uuid, )); } @@ -104,7 +104,7 @@ class SubSpaceModelBloc extends Bloc { updatedSubspaceModels.add(UpdateSubspaceTemplateModel( action: Action.update, - uuid: event.updatedSubSpace.uuid!, + uuid: event.updatedSubSpace.uuid, )); emit(SubSpaceModelState( diff --git a/lib/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart b/lib/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart index 098b4804..0a9c9610 100644 --- a/lib/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart +++ b/lib/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart @@ -28,7 +28,8 @@ class SubspaceChip extends StatelessWidget { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), side: BorderSide( - color: isDuplicate ? ColorsManager.red : ColorsManager.transparentColor, + color: + isDuplicate ? ColorsManager.red : ColorsManager.transparentColor, width: 0, ), ), diff --git a/lib/pages/spaces_management/helper/space_helper.dart b/lib/pages/spaces_management/helper/space_helper.dart index 4049eb7e..45ee9777 100644 --- a/lib/pages/spaces_management/helper/space_helper.dart +++ b/lib/pages/spaces_management/helper/space_helper.dart @@ -2,18 +2,20 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_m import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; class SpaceHelper { - static SpaceModel? findSpaceByUuid(String? uuid, List communities) { - for (var community in communities) { - for (var space in community.spaces) { + static SpaceModel? findSpaceByUuid( + String? uuid, List communities) { + for (final community in communities) { + for (final space in community.spaces) { if (space.uuid == uuid) return space; } } return null; } - static SpaceModel? findSpaceByInternalId(String? internalId, List spaces) { + static SpaceModel? findSpaceByInternalId( + String? internalId, List spaces) { if (internalId != null) { - for (var space in spaces) { + for (final space in spaces) { if (space.internalId == internalId) return space; } } @@ -21,21 +23,22 @@ class SpaceHelper { return null; } - static String generateUniqueSpaceName(String originalName, List spaces) { + static String generateUniqueSpaceName( + String originalName, List spaces) { final baseName = originalName.replaceAll(RegExp(r'\(\d+\)$'), '').trim(); - int maxNumber = 0; + var maxNumber = 0; - for (var space in spaces) { + for (final space in spaces) { final match = RegExp(r'^(.*?)\((\d+)\)$').firstMatch(space.name); if (match != null && match.group(1)?.trim() == baseName) { - int existingNumber = int.parse(match.group(2)!); + final existingNumber = int.parse(match.group(2)!); if (existingNumber > maxNumber) { maxNumber = existingNumber; } } } - return "$baseName(${maxNumber + 1})"; + return '$baseName(${maxNumber + 1})'; } static bool isSave(List spaces) { @@ -51,10 +54,13 @@ class SpaceHelper { return space == selectedSpace || selectedSpace.parent?.internalId == space.internalId || - selectedSpace.children?.any((child) => child.internalId == space.internalId) == true; + selectedSpace.children + .any((child) => child.internalId == space.internalId) == + true; } - static bool isNameConflict(String value, SpaceModel? parentSpace, SpaceModel? editSpace) { + static bool isNameConflict( + String value, SpaceModel? parentSpace, SpaceModel? editSpace) { final siblings = parentSpace?.children .where((child) => child.internalId != editSpace?.internalId) .toList() ?? @@ -65,17 +71,19 @@ class SpaceHelper { .toList() ?? []; - final editSiblingConflict = editSiblings.any((child) => child.name == value); + final editSiblingConflict = + editSiblings.any((child) => child.name == value); final siblingConflict = siblings.any((child) => child.name == value); - final parentConflict = - parentSpace?.name == value && parentSpace?.internalId != editSpace?.internalId; + final parentConflict = parentSpace?.name == value && + parentSpace?.internalId != editSpace?.internalId; - final parentOfEditSpaceConflict = - editSpace?.parent?.name == value && editSpace?.parent?.internalId != editSpace?.internalId; + final parentOfEditSpaceConflict = editSpace?.parent?.name == value && + editSpace?.parent?.internalId != editSpace?.internalId; - final childConflict = editSpace?.children.any((child) => child.name == value) ?? false; + final childConflict = + editSpace?.children.any((child) => child.name == value) ?? false; return siblingConflict || parentConflict || diff --git a/lib/pages/spaces_management/helper/tag_helper.dart b/lib/pages/spaces_management/helper/tag_helper.dart index e1dc3cc3..f810b8ba 100644 --- a/lib/pages/spaces_management/helper/tag_helper.dart +++ b/lib/pages/spaces_management/helper/tag_helper.dart @@ -24,7 +24,7 @@ class TagHelper { final modifiedSubspaces = List.from(subspaces ?? []); if (subspaces != null) { - for (var subspace in subspaces) { + for (final subspace in subspaces) { getSubspaceTags(subspace)?.removeWhere( (tag) => !modifiedTags.any( (updatedTag) => getInternalId(updatedTag) == getInternalId(tag)), @@ -32,7 +32,7 @@ class TagHelper { } } - for (var tag in modifiedTags.toList()) { + for (final tag in modifiedTags.toList()) { if (modifiedSubspaces.isEmpty) continue; final prevIndice = checkTagExistInSubspace(tag, modifiedSubspaces); @@ -131,8 +131,7 @@ class TagHelper { static List getAvailableTagModels( List allTags, List currentTags, Tag currentTag) { - List availableTagsForTagModel = - TagHelper.getAvailableTags( + final availableTagsForTagModel = TagHelper.getAvailableTags( allTags: allTags, currentTags: currentTags, currentTag: currentTag, @@ -145,14 +144,14 @@ class TagHelper { List? spaceTagModels, List? subspaces, }) { - final List initialTags = []; + final initialTags = []; if (spaceTagModels != null) { initialTags.addAll(spaceTagModels); } if (subspaces != null) { - for (var subspace in subspaces) { + for (final subspace in subspaces) { if (subspace.tags != null) { initialTags.addAll( subspace.tags!.map( @@ -174,14 +173,14 @@ class TagHelper { List? spaceTags, List? subspaces, }) { - final List initialTags = []; + final initialTags = []; if (spaceTags != null) { initialTags.addAll(spaceTags); } if (subspaces != null) { - for (var subspace in subspaces) { + for (final subspace in subspaces) { if (subspace.tags != null) { initialTags.addAll( subspace.tags!.map( @@ -200,8 +199,8 @@ class TagHelper { } static Map groupTags(List tags) { - final Map groupedTags = {}; - for (var tag in tags) { + final groupedTags = {}; + for (final tag in tags) { if (tag.product != null) { final product = tag.product!; groupedTags[product] = (groupedTags[product] ?? 0) + 1; @@ -212,10 +211,10 @@ class TagHelper { static List createInitialSelectedProducts( List? tags, List? subspaces) { - final Map productCounts = {}; + final productCounts = {}; if (tags != null) { - for (var tag in tags) { + for (final tag in tags) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; } @@ -223,9 +222,9 @@ class TagHelper { } if (subspaces != null) { - for (var subspace in subspaces) { + for (final subspace in subspaces) { if (subspace.tags != null) { - for (var tag in subspace.tags!) { + for (final tag in subspace.tags!) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; @@ -247,10 +246,10 @@ class TagHelper { static List createInitialSelectedProductsForTags( List? tags, List? subspaces) { - final Map productCounts = {}; + final productCounts = {}; if (tags != null) { - for (var tag in tags) { + for (final tag in tags) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; } @@ -258,9 +257,9 @@ class TagHelper { } if (subspaces != null) { - for (var subspace in subspaces) { + for (final subspace in subspaces) { if (subspace.tags != null) { - for (var tag in subspace.tags!) { + for (final tag in subspace.tags!) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; @@ -280,14 +279,13 @@ class TagHelper { .toList(); } - static int? checkTagExistInSubspaceModels( - Tag tag, List? subspaces) { + static int? checkTagExistInSubspaceModels(Tag tag, List? subspaces) { if (subspaces == null) return null; - for (int i = 0; i < subspaces.length; i++) { + for (var i = 0; i < subspaces.length; i++) { final subspace = subspaces[i] as SubspaceTemplateModel; // Explicit cast if (subspace.tags == null) continue; - for (var t in subspace.tags!) { + for (final t in subspace.tags!) { if (tag.internalId == t.internalId) { return i; } @@ -314,11 +312,11 @@ class TagHelper { final processedSubspaces = List.from(result['subspaces'] as List); - for (var subspace in processedSubspaces) { + for (final subspace in processedSubspaces) { final subspaceTags = subspace.tags; if (subspaceTags != null) { - for (int i = 0; i < subspaceTags.length; i++) { + for (var i = 0; i < subspaceTags.length; i++) { final tag = subspaceTags[i]; // Find the updated tag inside processedTags @@ -341,10 +339,10 @@ class TagHelper { static int? checkTagExistInSubspace(Tag tag, List? subspaces) { if (subspaces == null) return null; - for (int i = 0; i < subspaces.length; i++) { + for (var i = 0; i < subspaces.length; i++) { final subspace = subspaces[i]; if (subspace.tags == null) continue; - for (var t in subspace.tags!) { + for (final t in subspace.tags!) { if (tag.internalId == t.internalId) { return i; } @@ -371,11 +369,11 @@ class TagHelper { final processedSubspaces = List.from(result['subspaces'] as List); - for (var subspace in processedSubspaces) { + for (final subspace in processedSubspaces) { final subspaceTags = subspace.tags; if (subspaceTags != null) { - for (int i = 0; i < subspaceTags.length; i++) { + for (var i = 0; i < subspaceTags.length; i++) { final tag = subspaceTags[i]; final changedTag = updatedTags.firstWhere( @@ -397,10 +395,10 @@ class TagHelper { static List getAllTagValues( List communities, List? spaceModels) { - final Set allTags = {}; + final allTags = {}; if (spaceModels != null) { - for (var model in spaceModels) { + for (final model in spaceModels) { allTags.addAll(model.listAllTagValues()); } } diff --git a/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart b/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart index 5b85e17e..aab51b59 100644 --- a/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart +++ b/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart @@ -26,27 +26,27 @@ class LinkSpaceToModelBloc Future _getSpaceIds(LinkSpaceModelSelectedIdsEvent event, Emitter emit) async { try { - BuildContext context = NavigationService.navigatorKey.currentContext!; - var spaceBloc = context.read(); - spacesListIds.clear(); - for (var communityId in spaceBloc.state.selectedCommunities) { - List spacesList = + final context = NavigationService.navigatorKey.currentContext!; + final spaceBloc = context.read(); + spacesListIds.clear(); + for (final communityId in spaceBloc.state.selectedCommunities) { + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - spacesListIds.addAll(spacesList); + spacesListIds.addAll(spacesList); } hasSelectedSpaces = spaceBloc.state.selectedCommunities.any((communityId) { - List spacesList = + final spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; return spacesList.isNotEmpty; }); if (hasSelectedSpaces) { - debugPrint("At least one space is selected."); + debugPrint('At least one space is selected.'); } else { - debugPrint("No spaces selected."); + debugPrint('No spaces selected.'); } } catch (e) { - debugPrint("Error in _getSpaceIds: $e"); + debugPrint('Error in _getSpaceIds: $e'); } } diff --git a/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart b/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart index ad18b3c7..ec358985 100644 --- a/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart +++ b/lib/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart @@ -5,8 +5,8 @@ abstract class LinkSpaceToModelState { class SpaceModelInitial extends LinkSpaceToModelState {} class SpaceModelLoading extends LinkSpaceToModelState {} -class LinkSpaceModelLoading extends LinkSpaceToModelState {} +class LinkSpaceModelLoading extends LinkSpaceToModelState {} class SpaceModelSelectedState extends LinkSpaceToModelState { final int selectedIndex; diff --git a/lib/pages/spaces_management/link_space_model/view/link_space_model_dialog.dart b/lib/pages/spaces_management/link_space_model/view/link_space_model_dialog.dart index bbd0de36..9e50b881 100644 --- a/lib/pages/spaces_management/link_space_model/view/link_space_model_dialog.dart +++ b/lib/pages/spaces_management/link_space_model/view/link_space_model_dialog.dart @@ -15,11 +15,11 @@ class LinkSpaceModelDialog extends StatelessWidget { final List spaceModels; const LinkSpaceModelDialog({ - Key? key, + super.key, this.onSave, this.initialSelectedIndex, required this.spaceModels, - }) : super(key: key); + }); @override Widget build(BuildContext context) { @@ -39,9 +39,10 @@ class LinkSpaceModelDialog extends StatelessWidget { color: ColorsManager.textFieldGreyColor, width: MediaQuery.of(context).size.width * 0.7, height: MediaQuery.of(context).size.height * 0.6, - child: BlocBuilder( + child: BlocBuilder( builder: (context, state) { - int selectedIndex = -1; + var selectedIndex = -1; if (state is SpaceModelSelectedState) { selectedIndex = state.selectedIndex; } @@ -72,7 +73,9 @@ class LinkSpaceModelDialog extends StatelessWidget { ), borderRadius: BorderRadius.circular(8.0), ), - child: SpaceModelCardWidget(model: model,), + child: SpaceModelCardWidget( + model: model, + ), ), ); }, diff --git a/lib/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart b/lib/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart index 5428c343..e386b186 100644 --- a/lib/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart +++ b/lib/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart @@ -5,7 +5,6 @@ import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_spac import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/utils/constants/action_enum.dart'; @@ -21,7 +20,7 @@ class CreateSpaceModelBloc try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - late SpaceTemplateModel spaceTemplate = event.spaceTemplate; + late final spaceTemplate = event.spaceTemplate; final tagBodyModels = spaceTemplate.tags?.map((tag) => tag.toTagBodyModel()).toList() ?? @@ -55,7 +54,7 @@ class CreateSpaceModelBloc } } } catch (e) { - emit(CreateSpaceModelError('Error creating space model')); + emit(const CreateSpaceModelError('Error creating space model')); } }); @@ -65,14 +64,14 @@ class CreateSpaceModelBloc if (_space != null) { emit(CreateSpaceModelLoaded(_space!)); } else { - emit(CreateSpaceModelError("No space template found")); + emit(const CreateSpaceModelError('No space template found')); } }); }); on((event, emit) { _space = event.spaceTemplate; - final String? errorMessage = _checkDuplicateModelName( + final errorMessage = _checkDuplicateModelName( event.allModels ?? [], event.spaceTemplate.modelName); emit(CreateSpaceModelLoaded(_space!, errorMessage: errorMessage)); }); @@ -94,9 +93,8 @@ class CreateSpaceModelBloc orElse: () => subspace, ); - final updatedTags = [ - ...?subspace.tags?.map((tag) { + ...subspace.tags?.map((tag) { final matchingTag = matchingEventSubspace.tags?.firstWhere( (e) => e.internalId == tag.internalId, @@ -108,7 +106,7 @@ class CreateSpaceModelBloc : tag; }) ?? [], - ...?matchingEventSubspace.tags?.where( + ...matchingEventSubspace.tags?.where( (e) => subspace.tags ?.every((t) => t.internalId != e.internalId) ?? @@ -127,9 +125,7 @@ class CreateSpaceModelBloc event.subspaces .where((e) => updatedSubspaces.every((s) => s.internalId != e.internalId)) - .forEach((newSubspace) { - updatedSubspaces.add(newSubspace); - }); + .forEach(updatedSubspaces.add); final updatedSpace = currentState.space.copyWith(subspaceModels: updatedSubspaces); @@ -137,7 +133,7 @@ class CreateSpaceModelBloc emit(CreateSpaceModelLoaded(updatedSpace, errorMessage: currentState.errorMessage)); } else { - emit(CreateSpaceModelError("Space template not initialized")); + emit(const CreateSpaceModelError('Space template not initialized')); } }); @@ -163,14 +159,12 @@ class CreateSpaceModelBloc event.tags .where( (e) => updatedTags.every((t) => t.internalId != e.internalId)) - .forEach((e) { - updatedTags.add(e); - }); + .forEach(updatedTags.add); emit(CreateSpaceModelLoaded( currentState.space.copyWith(tags: updatedTags))); } else { - emit(CreateSpaceModelError("Space template not initialized")); + emit(const CreateSpaceModelError('Space template not initialized')); } }); @@ -180,12 +174,12 @@ class CreateSpaceModelBloc if (event.allModels.contains(event.name) == true) { emit(CreateSpaceModelLoaded( currentState.space, - errorMessage: "Duplicate Model name", + errorMessage: 'Duplicate Model name', )); } else if (event.name.trim().isEmpty) { emit(CreateSpaceModelLoaded( currentState.space, - errorMessage: "Model name cannot be empty", + errorMessage: 'Model name cannot be empty', )); } else { final updatedSpaceModel = @@ -194,7 +188,7 @@ class CreateSpaceModelBloc emit(CreateSpaceModelLoaded(updatedSpaceModel)); } } else { - emit(CreateSpaceModelError("Space template not initialized")); + emit(const CreateSpaceModelError('Space template not initialized')); } }); @@ -211,19 +205,17 @@ class CreateSpaceModelBloc if (prevSpaceModel?.modelName != newSpaceModel.modelName) { spaceModelName = newSpaceModel.modelName; } - List tagUpdates = []; - final List subspaceUpdates = []; - final List? prevSubspaces = - prevSpaceModel?.subspaceModels; - final List? newSubspaces = - newSpaceModel.subspaceModels; + var tagUpdates = []; + final subspaceUpdates = []; + final prevSubspaces = prevSpaceModel?.subspaceModels; + final newSubspaces = newSpaceModel.subspaceModels; tagUpdates = processTagUpdates(prevSpaceModel?.tags, newSpaceModel.tags); if (prevSubspaces != null || newSubspaces != null) { if (prevSubspaces != null && newSubspaces != null) { - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { final existsInNew = newSubspaces .any((subspace) => subspace.uuid == prevSubspace.uuid); if (!existsInNew) { @@ -232,20 +224,20 @@ class CreateSpaceModelBloc } } } else if (prevSubspaces != null && newSubspaces == null) { - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { subspaceUpdates.add(UpdateSubspaceTemplateModel( action: Action.delete, uuid: prevSubspace.uuid)); } } if (newSubspaces != null) { - for (var newSubspace in newSubspaces) { + for (final newSubspace in newSubspaces) { // Tag without UUID - if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) { - final List tagUpdates = []; + if (newSubspace.uuid == null || newSubspace.uuid!.isEmpty) { + final tagUpdates = []; if (newSubspace.tags != null) { - for (var tag in newSubspace.tags!) { + for (final tag in newSubspace.tags!) { tagUpdates.add(TagModelUpdate( action: Action.add, newTagUuid: tag.uuid == '' ? null : tag.uuid, @@ -263,14 +255,14 @@ class CreateSpaceModelBloc if (prevSubspaces != null && newSubspaces != null) { final newSubspaceMap = { - for (var subspace in newSubspaces) subspace.uuid: subspace + for (final subspace in newSubspaces) subspace.uuid: subspace }; - for (var prevSubspace in prevSubspaces) { + for (final prevSubspace in prevSubspaces) { final newSubspace = newSubspaceMap[prevSubspace.uuid]; if (newSubspace != null) { - final List tagSubspaceUpdates = + final tagSubspaceUpdates = processTagUpdates(prevSubspace.tags, newSubspace.tags); subspaceUpdates.add(UpdateSubspaceTemplateModel( action: Action.update, @@ -298,7 +290,7 @@ class CreateSpaceModelBloc } } } catch (e) { - emit(CreateSpaceModelError('Error creating space model')); + emit(const CreateSpaceModelError('Error creating space model')); } }); } @@ -307,11 +299,11 @@ class CreateSpaceModelBloc List? prevTags, List? newTags, ) { - final List tagUpdates = []; + final tagUpdates = []; final processedTags = {}; if (prevTags == null && newTags != null) { - for (var newTag in newTags) { + for (final newTag in newTags) { tagUpdates.add(TagModelUpdate( action: Action.add, tag: newTag.tag, @@ -325,7 +317,7 @@ class CreateSpaceModelBloc if (newTags != null || prevTags != null) { // Case 1: Tags deleted if (prevTags != null && newTags != null) { - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { final existsInNew = newTags.any((newTag) => newTag.uuid == prevTag.uuid); if (!existsInNew) { @@ -334,7 +326,7 @@ class CreateSpaceModelBloc } } } else if (prevTags != null && newTags == null) { - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { tagUpdates .add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid)); } @@ -344,7 +336,7 @@ class CreateSpaceModelBloc if (newTags != null) { final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {}; - for (var newTag in newTags) { + for (final newTag in newTags) { // Tag without UUID if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) && !processedTags.contains(newTag.tag)) { @@ -360,9 +352,9 @@ class CreateSpaceModelBloc // Case 3: Tags updated if (prevTags != null && newTags != null) { - final newTagMap = {for (var tag in newTags) tag.uuid: tag}; + final newTagMap = {for (final tag in newTags) tag.uuid: tag}; - for (var prevTag in prevTags) { + for (final prevTag in prevTags) { final newTag = newTagMap[prevTag.uuid]; if (newTag != null) { tagUpdates.add(TagModelUpdate( @@ -381,7 +373,7 @@ class CreateSpaceModelBloc String? _checkDuplicateModelName(List allModels, String name) { if (allModels.contains(name)) { - return "Duplicate Model name"; + return 'Duplicate Model name'; } return null; } diff --git a/lib/pages/spaces_management/space_model/bloc/create_space_model_event.dart b/lib/pages/spaces_management/space_model/bloc/create_space_model_event.dart index 0d2a3a4f..897bc59c 100644 --- a/lib/pages/spaces_management/space_model/bloc/create_space_model_event.dart +++ b/lib/pages/spaces_management/space_model/bloc/create_space_model_event.dart @@ -16,7 +16,7 @@ class UpdateSpaceTemplate extends CreateSpaceModelEvent { final SpaceTemplateModel spaceTemplate; List? allModels; - UpdateSpaceTemplate(this.spaceTemplate,this.allModels); + UpdateSpaceTemplate(this.spaceTemplate, this.allModels); } class CreateSpaceTemplate extends CreateSpaceModelEvent { @@ -36,7 +36,7 @@ class UpdateSpaceTemplateName extends CreateSpaceModelEvent { final String name; final List allModels; - UpdateSpaceTemplateName({required this.name, required this.allModels}); + const UpdateSpaceTemplateName({required this.name, required this.allModels}); @override List get props => [name, allModels]; @@ -45,19 +45,19 @@ class UpdateSpaceTemplateName extends CreateSpaceModelEvent { class AddSubspacesToSpaceTemplate extends CreateSpaceModelEvent { final List subspaces; - AddSubspacesToSpaceTemplate(this.subspaces); + const AddSubspacesToSpaceTemplate(this.subspaces); } class AddTagsToSpaceTemplate extends CreateSpaceModelEvent { final List tags; - AddTagsToSpaceTemplate(this.tags); + const AddTagsToSpaceTemplate(this.tags); } class ValidateSpaceTemplateName extends CreateSpaceModelEvent { final String name; - ValidateSpaceTemplateName({required this.name}); + const ValidateSpaceTemplateName({required this.name}); } class ModifySpaceTemplate extends CreateSpaceModelEvent { @@ -65,7 +65,7 @@ class ModifySpaceTemplate extends CreateSpaceModelEvent { final SpaceTemplateModel updatedSpaceTemplate; final Function(SpaceTemplateModel)? onUpdate; - ModifySpaceTemplate( + const ModifySpaceTemplate( {required this.spaceTemplate, required this.updatedSpaceTemplate, this.onUpdate}); diff --git a/lib/pages/spaces_management/space_model/bloc/create_space_model_state.dart b/lib/pages/spaces_management/space_model/bloc/create_space_model_state.dart index 0fc5c48d..d28913b5 100644 --- a/lib/pages/spaces_management/space_model/bloc/create_space_model_state.dart +++ b/lib/pages/spaces_management/space_model/bloc/create_space_model_state.dart @@ -16,7 +16,7 @@ class CreateSpaceModelLoaded extends CreateSpaceModelState { final SpaceTemplateModel space; final String? errorMessage; - CreateSpaceModelLoaded(this.space, {this.errorMessage}); + const CreateSpaceModelLoaded(this.space, {this.errorMessage}); @override List get props => [space, errorMessage]; @@ -25,5 +25,5 @@ class CreateSpaceModelLoaded extends CreateSpaceModelState { class CreateSpaceModelError extends CreateSpaceModelState { final String message; - CreateSpaceModelError(this.message); + const CreateSpaceModelError(this.message); } diff --git a/lib/pages/spaces_management/space_model/bloc/space_model_bloc.dart b/lib/pages/spaces_management/space_model/bloc/space_model_bloc.dart index 37a8c0a9..0450d4ec 100644 --- a/lib/pages/spaces_management/space_model/bloc/space_model_bloc.dart +++ b/lib/pages/spaces_management/space_model/bloc/space_model_bloc.dart @@ -21,18 +21,21 @@ class SpaceModelBloc extends Bloc { on(_onDeleteSpaceModel); } - Future _onCreateSpaceModel(CreateSpaceModel event, Emitter emit) async { + Future _onCreateSpaceModel( + CreateSpaceModel event, Emitter emit) async { final currentState = state; if (currentState is SpaceModelLoaded) { try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final newSpaceModel = await api.getSpaceModel(event.newSpaceModel.uuid ?? '', projectUuid); + final newSpaceModel = await api.getSpaceModel( + event.newSpaceModel.uuid ?? '', projectUuid); if (newSpaceModel != null) { - final updatedSpaceModels = List.from(currentState.spaceModels) - ..add(newSpaceModel); + final updatedSpaceModels = + List.from(currentState.spaceModels) + ..add(newSpaceModel); emit(SpaceModelLoaded(spaceModels: updatedSpaceModels)); } } catch (e) { @@ -41,13 +44,15 @@ class SpaceModelBloc extends Bloc { } } - Future _onUpdateSpaceModel(UpdateSpaceModel event, Emitter emit) async { + Future _onUpdateSpaceModel( + UpdateSpaceModel event, Emitter emit) async { final currentState = state; if (currentState is SpaceModelLoaded) { try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final newSpaceModel = await api.getSpaceModel(event.spaceModelUuid, projectUuid); + final newSpaceModel = + await api.getSpaceModel(event.spaceModelUuid, projectUuid); if (newSpaceModel != null) { final updatedSpaceModels = currentState.spaceModels.map((model) { return model.uuid == event.spaceModelUuid ? newSpaceModel : model; @@ -61,14 +66,16 @@ class SpaceModelBloc extends Bloc { } } - Future _onDeleteSpaceModel(DeleteSpaceModel event, Emitter emit) async { + Future _onDeleteSpaceModel( + DeleteSpaceModel event, Emitter emit) async { final currentState = state; if (currentState is SpaceModelLoaded) { try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final deletedSuccessfully = await api.deleteSpaceModel(event.spaceModelUuid, projectUuid); + final deletedSuccessfully = + await api.deleteSpaceModel(event.spaceModelUuid, projectUuid); if (deletedSuccessfully) { final updatedSpaceModels = currentState.spaceModels diff --git a/lib/pages/spaces_management/space_model/models/space_template_model.dart b/lib/pages/spaces_management/space_model/models/space_template_model.dart index f8926051..1481dec4 100644 --- a/lib/pages/spaces_management/space_model/models/space_template_model.dart +++ b/lib/pages/spaces_management/space_model/models/space_template_model.dart @@ -30,19 +30,18 @@ class SpaceTemplateModel extends Equatable { return SpaceTemplateModel( uuid: json['uuid'] ?? '', createdAt: json['createdAt'] != null - ? DateTime.tryParse(json['createdAt']) + ? DateTime.tryParse(json['createdAt']) : null, internalId: internalId, modelName: json['modelName'] ?? '', subspaceModels: (json['subspaceModels'] as List?) - ?.where((e) => e is Map) - .map((e) => - SubspaceTemplateModel.fromJson(e as Map)) + ?.whereType>() + .map(SubspaceTemplateModel.fromJson) .toList() ?? [], tags: (json['tags'] as List?) - ?.where((item) => item is Map) // Validate type - .map((item) => Tag.fromJson(item as Map)) + ?.whereType>() // Validate type + .map(Tag.fromJson) .toList() ?? [], ); @@ -109,7 +108,7 @@ class UpdateSubspaceTemplateModel { extension SpaceTemplateExtensions on SpaceTemplateModel { List listAllTagValues() { - final List tagValues = []; + final tagValues = []; if (tags != null) { tagValues.addAll( diff --git a/lib/pages/spaces_management/space_model/view/space_model_page.dart b/lib/pages/spaces_management/space_model/view/space_model_page.dart index eef196be..69829f4a 100644 --- a/lib/pages/spaces_management/space_model/view/space_model_page.dart +++ b/lib/pages/spaces_management/space_model/view/space_model_page.dart @@ -18,8 +18,10 @@ class SpaceModelPage extends StatelessWidget { final List projectTags; const SpaceModelPage( - {Key? key, this.products, this.onSpaceModelsUpdated, required this.projectTags}) - : super(key: key); + {super.key, + this.products, + this.onSpaceModelsUpdated, + required this.projectTags}); @override Widget build(BuildContext context) { @@ -77,7 +79,8 @@ class SpaceModelPage extends StatelessWidget { } // Render existing space model final model = spaceModels[index]; - final otherModel = List.from(allSpaceModelNames); + final otherModel = + List.from(allSpaceModelNames); otherModel.remove(model.modelName); return GestureDetector( onTap: () { @@ -115,8 +118,10 @@ class SpaceModelPage extends StatelessWidget { return Center( child: Text( 'Error: ${state.message}', - style: - Theme.of(context).textTheme.bodySmall?.copyWith(color: ColorsManager.warningRed), + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: ColorsManager.warningRed), ), ); } @@ -126,7 +131,7 @@ class SpaceModelPage extends StatelessWidget { } double _calculateChildAspectRatio(BuildContext context) { - double screenWidth = MediaQuery.of(context).size.width; + final screenWidth = MediaQuery.of(context).size.width; if (screenWidth > 1600) { return 1.5; // Decrease to make cards taller } @@ -140,7 +145,7 @@ class SpaceModelPage extends StatelessWidget { } List _getAllTagValues(List spaceModels) { - final List allTags = []; + final allTags = []; for (final spaceModel in spaceModels) { if (spaceModel.tags != null) { allTags.addAll(spaceModel.listAllTagValues()); @@ -150,7 +155,7 @@ class SpaceModelPage extends StatelessWidget { } List _getAllSpaceModelName(List spaceModels) { - final List names = []; + final names = []; for (final spaceModel in spaceModels) { names.add(spaceModel.modelName); } diff --git a/lib/pages/spaces_management/space_model/widgets/add_space_model_widget.dart b/lib/pages/spaces_management/space_model/widgets/add_space_model_widget.dart index 20876a39..23377f7d 100644 --- a/lib/pages/spaces_management/space_model/widgets/add_space_model_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/add_space_model_widget.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/utils/color_manager.dart'; class AddSpaceModelWidget extends StatelessWidget { - const AddSpaceModelWidget({Key? key}) : super(key: key); + const AddSpaceModelWidget({super.key}); @override Widget build(BuildContext context) { diff --git a/lib/pages/spaces_management/space_model/widgets/button_content_widget.dart b/lib/pages/spaces_management/space_model/widgets/button_content_widget.dart index 2cd338e4..303ef187 100644 --- a/lib/pages/spaces_management/space_model/widgets/button_content_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/button_content_widget.dart @@ -9,12 +9,12 @@ class ButtonContentWidget extends StatelessWidget { final bool disabled; const ButtonContentWidget({ - Key? key, + super.key, this.icon, required this.label, this.svgAssets, this.disabled = false, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/confirm_merge_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/confirm_merge_dialog.dart index 2a39d67b..8079ad4a 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/confirm_merge_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/confirm_merge_dialog.dart @@ -45,7 +45,7 @@ class ConfirmMergeDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Cancel", + 'Cancel', style: Theme.of(context) .textTheme .bodyMedium @@ -66,7 +66,7 @@ class ConfirmMergeDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Ok", + 'Ok', style: Theme.of(context).textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, fontSize: 16, diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/confirm_overwrite_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/confirm_overwrite_dialog.dart index 0497b570..51a555a3 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/confirm_overwrite_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/confirm_overwrite_dialog.dart @@ -56,7 +56,7 @@ class ConfirmOverwriteDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Cancel", + 'Cancel', style: Theme.of(context) .textTheme .bodyMedium @@ -86,7 +86,7 @@ class ConfirmOverwriteDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Ok", + 'Ok', style: Theme.of(context).textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w400, fontSize: 16, diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart index 70dde231..1a429d4c 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart @@ -9,13 +9,12 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart'; - +import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -29,22 +28,21 @@ class CreateSpaceModelDialog extends StatelessWidget { final List projectTags; const CreateSpaceModelDialog( - {Key? key, + {super.key, this.products, this.allTags, this.spaceModel, this.pageContext, this.otherSpaceModels, this.allSpaceModels, - required this.projectTags}) - : super(key: key); + required this.projectTags}); @override Widget build(BuildContext context) { - final SpaceModelManagementApi _spaceModelApi = SpaceModelManagementApi(); + final spaceModelApi = SpaceModelManagementApi(); final screenWidth = MediaQuery.of(context).size.width; - final TextEditingController spaceNameController = TextEditingController( + final spaceNameController = TextEditingController( text: spaceModel?.modelName ?? '', ); @@ -56,7 +54,7 @@ class CreateSpaceModelDialog extends StatelessWidget { child: BlocProvider( create: (_) { final bloc = CreateSpaceModelBloc( - _spaceModelApi, + spaceModelApi, ); if (spaceModel != null) { bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels)); @@ -71,7 +69,8 @@ class CreateSpaceModelDialog extends StatelessWidget { spaceNameController.addListener(() { bloc.add(UpdateSpaceTemplateName( - name: spaceNameController.text, allModels: otherSpaceModels ?? [])); + name: spaceNameController.text, + allModels: otherSpaceModels ?? [])); }); return bloc; @@ -89,7 +88,9 @@ class CreateSpaceModelDialog extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Text( - spaceModel?.uuid == null ? 'Create New Space Model' : 'Edit Space Model', + spaceModel?.uuid == null + ? 'Create New Space Model' + : 'Edit Space Model', style: Theme.of(context) .textTheme .headlineLarge @@ -101,8 +102,10 @@ class CreateSpaceModelDialog extends StatelessWidget { child: TextField( controller: spaceNameController, onChanged: (value) { - context.read().add(UpdateSpaceTemplateName( - name: value, allModels: otherSpaceModels ?? [])); + context.read().add( + UpdateSpaceTemplateName( + name: value, + allModels: otherSpaceModels ?? [])); }, style: Theme.of(context) .textTheme @@ -176,55 +179,84 @@ class CreateSpaceModelDialog extends StatelessWidget { !isNameValid) ? null : () { - final updatedSpaceTemplate = updatedSpaceModel.copyWith( - modelName: spaceNameController.text.trim(), + final updatedSpaceTemplate = + updatedSpaceModel.copyWith( + modelName: + spaceNameController.text.trim(), ); if (updatedSpaceModel.uuid == null) { - context.read().add( + context + .read() + .add( CreateSpaceTemplate( - spaceTemplate: updatedSpaceTemplate, + spaceTemplate: + updatedSpaceTemplate, onCreate: (newModel) { if (pageContext != null) { - pageContext!.read().add( - CreateSpaceModel(newSpaceModel: newModel)); pageContext! - .read() - .add(UpdateSpaceModelCache(newModel)); + .read() + .add(CreateSpaceModel( + newSpaceModel: + newModel)); + pageContext! + .read< + SpaceManagementBloc>() + .add( + UpdateSpaceModelCache( + newModel)); } - Navigator.of(context).pop(); // Close the dialog + Navigator.of(context) + .pop(); // Close the dialog }, ), ); } else { if (pageContext != null) { - final currentState = - pageContext!.read().state; - if (currentState is SpaceModelLoaded) { - final spaceModels = List.from( - currentState.spaceModels); + final currentState = pageContext! + .read() + .state; + if (currentState + is SpaceModelLoaded) { + final spaceModels = + List.from( + currentState.spaceModels); - final SpaceTemplateModel? currentSpaceModel = - spaceModels.cast().firstWhere( - (sm) => sm?.uuid == updatedSpaceModel.uuid, + final currentSpaceModel = + spaceModels + .cast() + .firstWhere( + (sm) => + sm?.uuid == + updatedSpaceModel + .uuid, orElse: () => null, ); if (currentSpaceModel != null) { context .read() .add(ModifySpaceTemplate( - spaceTemplate: currentSpaceModel, - updatedSpaceTemplate: updatedSpaceTemplate, + spaceTemplate: + currentSpaceModel, + updatedSpaceTemplate: + updatedSpaceTemplate, onUpdate: (newModel) { - if (pageContext != null) { - pageContext!.read().add( - UpdateSpaceModel( - spaceModelUuid: - newModel.uuid ?? '')); + if (pageContext != + null) { pageContext! - .read() - .add(UpdateSpaceModelCache(newModel)); + .read< + SpaceModelBloc>() + .add(UpdateSpaceModel( + spaceModelUuid: + newModel.uuid ?? + '')); + pageContext! + .read< + SpaceManagementBloc>() + .add(UpdateSpaceModelCache( + newModel)); } - Navigator.of(context).pop(); + Navigator.of(context) + .pop(); })); } } @@ -233,11 +265,11 @@ class CreateSpaceModelDialog extends StatelessWidget { }, backgroundColor: ColorsManager.secondaryColor, borderRadius: 10, - foregroundColor: - ((state.errorMessage != null && state.errorMessage != '') || - !isNameValid) - ? ColorsManager.whiteColorsWithOpacity - : ColorsManager.whiteColors, + foregroundColor: ((state.errorMessage != null && + state.errorMessage != '') || + !isNameValid) + ? ColorsManager.whiteColorsWithOpacity + : ColorsManager.whiteColors, child: const Text('OK'), ), ), diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart index e0260887..8313360c 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart @@ -1,9 +1,10 @@ import 'dart:math'; -import 'package:flutter/material.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/linking_successful.dart'; +import 'package:flutter/material.dart'; class CustomLoadingIndicator extends StatefulWidget { + const CustomLoadingIndicator({super.key}); + @override _CustomLoadingIndicatorState createState() => _CustomLoadingIndicatorState(); } @@ -50,22 +51,22 @@ class _CustomLoadingIndicatorState extends State class LoadingPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final Paint paint = Paint() + final paint = Paint() ..strokeWidth = 5 ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke; - final double radius = size.width / 2; - final Offset center = Offset(size.width / 2, size.height / 2); + final radius = size.width / 2; + final center = Offset(size.width / 2, size.height / 2); - for (int i = 0; i < 12; i++) { - final double angle = (i * 30) * (pi / 180); - final double startX = center.dx + radius * cos(angle); - final double startY = center.dy + radius * sin(angle); - final double endX = center.dx + (radius - 8) * cos(angle); - final double endY = center.dy + (radius - 8) * sin(angle); + for (var i = 0; i < 12; i++) { + final angle = (i * 30) * (pi / 180); + final startX = center.dx + radius * cos(angle); + final startY = center.dy + radius * sin(angle); + final endX = center.dx + (radius - 8) * cos(angle); + final endY = center.dy + (radius - 8) * sin(angle); - paint.color = Colors.blue.withOpacity(i / 12); // Gradient effect + paint.color = Colors.blue.withValues(alpha: i / 12); // Gradient effect canvas.drawLine(Offset(startX, startY), Offset(endX, endY), paint); } } diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart index 8349baa4..c5a11c4a 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart @@ -6,8 +6,7 @@ import 'package:syncrow_web/utils/color_manager.dart'; class DeleteSpaceModelDialog extends StatelessWidget { final VoidCallback onConfirmDelete; - const DeleteSpaceModelDialog({Key? key, required this.onConfirmDelete}) - : super(key: key); + const DeleteSpaceModelDialog({super.key, required this.onConfirmDelete}); @override Widget build(BuildContext context) { @@ -20,7 +19,7 @@ class DeleteSpaceModelDialog extends StatelessWidget { backgroundColor: ColorsManager.whiteColors, title: Center( child: Text( - "Delete Space Model", + 'Delete Space Model', textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -34,13 +33,13 @@ class DeleteSpaceModelDialog extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Text( - "Are you sure you want to delete?", + 'Are you sure you want to delete?', textAlign: TextAlign.center, style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 15), Text( - "The existing sub-spaces, devices, and routines will remain associated with the spaces, but the connection will be removed.", + 'The existing sub-spaces, devices, and routines will remain associated with the spaces, but the connection will be removed.', textAlign: TextAlign.center, style: Theme.of(context) .textTheme @@ -60,7 +59,7 @@ class DeleteSpaceModelDialog extends StatelessWidget { onPressed: () { Navigator.of(context).pop(); // Close dialog }, - label: "Cancel", + label: 'Cancel', ), ), const SizedBox(width: 10), diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart index 4da0c642..8a4b1a67 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart @@ -47,9 +47,9 @@ class _LinkSpaceModelSpacesDialogState Widget _buildDialogContent() { widget.spaceModel.createdAt.toString(); - String formattedDate = + final formattedDate = DateFormat('yyyy-MM-dd').format(widget.spaceModel.createdAt!); - String formattedTime = + final formattedTime = DateFormat('HH:mm:ss').format(widget.spaceModel.createdAt!); return Expanded( @@ -70,7 +70,7 @@ class _LinkSpaceModelSpacesDialogState children: [ const Center( child: Text( - "Link Space Model to Spaces", + 'Link Space Model to Spaces', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, @@ -81,22 +81,21 @@ class _LinkSpaceModelSpacesDialogState const Divider(), const SizedBox(height: 16), _buildDetailRow( - "Space model name:", widget.spaceModel.modelName), + 'Space model name:', widget.spaceModel.modelName), Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ const Expanded( child: Text( - "Creation date and time:", - style: const TextStyle( - fontWeight: FontWeight.bold), + 'Creation date and time:', + style: TextStyle(fontWeight: FontWeight.bold), ), ), const SizedBox(width: 8), Expanded( child: Text( - "$formattedDate $formattedTime", + '$formattedDate $formattedTime', style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.black), @@ -107,14 +106,14 @@ class _LinkSpaceModelSpacesDialogState ), // _buildDetailRow("Creation date and time:", // widget.spaceModel.createdAt.toString()), - _buildDetailRow("Created by:", "Admin"), + _buildDetailRow('Created by:', 'Admin'), const SizedBox(height: 12), const Text( - "Link to:", + 'Link to:', style: TextStyle(fontWeight: FontWeight.bold), ), const Text( - "Please select all the spaces where you would like to link the Routine.", + 'Please select all the spaces where you would like to link the Routine.', style: TextStyle(fontSize: 12, color: Colors.grey), ), const SizedBox(height: 8), @@ -124,7 +123,7 @@ class _LinkSpaceModelSpacesDialogState children: [ Expanded( flex: 7, - child: Container( + child: ColoredBox( color: ColorsManager.whiteColors, child: SpaceTreeView( isSide: true, @@ -170,7 +169,7 @@ class _LinkSpaceModelSpacesDialogState ), ), ), - child: _buildButton("Cancel", Colors.grey, () { + child: _buildButton('Cancel', Colors.grey, () { Navigator.of(context).pop(); }), ), @@ -191,14 +190,14 @@ class _LinkSpaceModelSpacesDialogState ), ), child: _buildButton( - "Confirm", + 'Confirm', ColorsManager.onSecondaryColor, () { final spaceModelBloc = context.read(); if (!spaceModelBloc.hasSelectedSpaces) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( - content: Text("Please select at least one space")), + content: Text('Please select at least one space')), ); return; } else { diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/linking_attention_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/linking_attention_dialog.dart index 15d92029..d16f2c7e 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/linking_attention_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/linking_attention_dialog.dart @@ -62,7 +62,7 @@ class LinkingAttentionDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Overwrite", + 'Overwrite', style: Theme.of(context) .textTheme .bodyMedium @@ -93,7 +93,7 @@ class LinkingAttentionDialog extends StatelessWidget { elevation: 3, ), child: Text( - "Merge", + 'Merge', style: Theme.of(context) .textTheme .bodyMedium diff --git a/lib/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart b/lib/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart index 9f57a4b1..ca8f3aeb 100644 --- a/lib/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart +++ b/lib/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart @@ -23,7 +23,7 @@ void showOverwriteDialog( mainAxisSize: MainAxisSize.min, children: [ const Text( - "Overwrite", + 'Overwrite', style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, @@ -32,13 +32,13 @@ void showOverwriteDialog( ), const SizedBox(height: 15), const Text( - "Are you sure you want to overwrite?", + 'Are you sure you want to overwrite?', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), textAlign: TextAlign.center, ), const SizedBox(height: 5), Text( - "Selected spaces already have linked space model / sub-spaces and devices", + 'Selected spaces already have linked space model / sub-spaces and devices', style: TextStyle( fontSize: 14, color: Colors.grey[600], @@ -61,7 +61,7 @@ void showOverwriteDialog( elevation: 0, ), child: const Text( - "Cancel", + 'Cancel', style: TextStyle( fontSize: 16, color: Colors.black, @@ -88,7 +88,7 @@ void showOverwriteDialog( elevation: 3, ), child: const Text( - "OK", + 'OK', style: TextStyle( fontSize: 16, color: Colors.white, diff --git a/lib/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart b/lib/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart index 4f42e3bf..475b24ed 100644 --- a/lib/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart @@ -10,28 +10,28 @@ class DynamicProductWidget extends StatelessWidget { final double maxHeight; const DynamicProductWidget({ - Key? key, + super.key, required this.productTagCount, required this.maxWidth, required this.maxHeight, - }) : super(key: key); + }); @override Widget build(BuildContext context) { - const double itemSpacing = 8.0; - const double lineSpacing = 8.0; - const double textPadding = 16.0; - const double itemHeight = 40.0; + const itemSpacing = 8.0; + const lineSpacing = 8.0; + const textPadding = 16.0; + const itemHeight = 40.0; - List productWidgets = []; - double currentLineWidth = 0.0; - double currentHeight = itemHeight; + final productWidgets = []; + var currentLineWidth = 0.0; + var currentHeight = itemHeight; for (final product in productTagCount.entries) { - final String prodType = product.key; - final int count = product.value; + final prodType = product.key; + final count = product.value; - final TextPainter textPainter = TextPainter( + final textPainter = TextPainter( text: TextSpan( text: 'x$count', style: Theme.of(context) @@ -42,7 +42,7 @@ class DynamicProductWidget extends StatelessWidget { textDirection: TextDirection.ltr, )..layout(); - final double itemWidth = textPainter.width + textPadding + 20; + final itemWidth = textPainter.width + textPadding + 20; if (currentLineWidth + itemWidth + itemSpacing > maxWidth) { currentHeight += itemHeight + lineSpacing; diff --git a/lib/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart b/lib/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart index f3da4122..d9610ff9 100644 --- a/lib/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart @@ -8,38 +8,37 @@ class DynamicRoomWidget extends StatelessWidget { final double maxHeight; const DynamicRoomWidget({ - Key? key, + super.key, required this.subspaceModels, required this.maxWidth, required this.maxHeight, - }) : super(key: key); + }); @override Widget build(BuildContext context) { - const double itemSpacing = 8.0; - const double lineSpacing = 8.0; - const double textPadding = 16.0; - const double itemHeight = 30.0; + const itemSpacing = 8.0; + const lineSpacing = 8.0; + const textPadding = 16.0; + const itemHeight = 30.0; - List roomWidgets = []; - double currentLineWidth = 0.0; - double currentHeight = itemHeight; + final roomWidgets = []; + var currentLineWidth = 0.0; + var currentHeight = itemHeight; for (final subspace in subspaceModels!) { - final TextPainter textPainter = TextPainter( + final textPainter = TextPainter( text: TextSpan( - text: subspace.subspaceName, - style: Theme.of(context).textTheme.bodyMedium - ), + text: subspace.subspaceName, + style: Theme.of(context).textTheme.bodyMedium), textDirection: TextDirection.ltr, )..layout(); - final double itemWidth = textPainter.width + textPadding; + final itemWidth = textPainter.width + textPadding; if (currentLineWidth + itemWidth + itemSpacing > maxWidth) { currentHeight += itemHeight + lineSpacing; if (currentHeight > maxHeight) { - roomWidgets.add(const RoomNameWidget(name: "...")); + roomWidgets.add(const RoomNameWidget(name: '...')); break; } currentLineWidth = 0.0; diff --git a/lib/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart b/lib/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart index 7ede09a7..8b3f2965 100644 --- a/lib/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/utils/color_manager.dart'; class EllipsisItemWidget extends StatelessWidget { - const EllipsisItemWidget({Key? key}) : super(key: key); + const EllipsisItemWidget({super.key}); @override Widget build(BuildContext context) { @@ -14,7 +14,7 @@ class EllipsisItemWidget extends StatelessWidget { border: Border.all(color: ColorsManager.transparentColor), ), child: Text( - "...", + '...', style: Theme.of(context) .textTheme .bodySmall diff --git a/lib/pages/spaces_management/space_model/widgets/flexible_item_widget.dart b/lib/pages/spaces_management/space_model/widgets/flexible_item_widget.dart index c28a82b8..aea3b56a 100644 --- a/lib/pages/spaces_management/space_model/widgets/flexible_item_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/flexible_item_widget.dart @@ -7,10 +7,10 @@ class FlexibleItemWidget extends StatelessWidget { final int count; const FlexibleItemWidget({ - Key? key, + super.key, required this.prodType, required this.count, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/pages/spaces_management/space_model/widgets/room_name_widget.dart b/lib/pages/spaces_management/space_model/widgets/room_name_widget.dart index d59f8c1e..7ba1b095 100644 --- a/lib/pages/spaces_management/space_model/widgets/room_name_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/room_name_widget.dart @@ -4,7 +4,7 @@ import 'package:syncrow_web/utils/color_manager.dart'; class RoomNameWidget extends StatelessWidget { final String name; - const RoomNameWidget({Key? key, required this.name}) : super(key: key); + const RoomNameWidget({super.key, required this.name}); @override Widget build(BuildContext context) { diff --git a/lib/pages/spaces_management/space_model/widgets/space_model_card_widget.dart b/lib/pages/spaces_management/space_model/widgets/space_model_card_widget.dart index 4d72a419..67a72268 100644 --- a/lib/pages/spaces_management/space_model/widgets/space_model_card_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/space_model_card_widget.dart @@ -1,19 +1,19 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/linking_successful.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -27,27 +27,27 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { final bool topActionsDisabled; const SpaceModelCardWidget({ - Key? key, + super.key, required this.model, this.pageContext, this.topActionsDisabled = true, - }) : super(key: key); + }); @override Widget build(BuildContext context) { - final Map productTagCount = {}; + final productTagCount = {}; if (model.tags != null) { - for (var tag in model.tags!) { + for (final tag in model.tags!) { final prodIcon = tag.product?.icon ?? 'Unknown'; productTagCount[prodIcon] = (productTagCount[prodIcon] ?? 0) + 1; } } if (model.subspaceModels != null) { - for (var subspace in model.subspaceModels!) { + for (final subspace in model.subspaceModels!) { if (subspace.tags != null) { - for (var tag in subspace.tags!) { + for (final tag in subspace.tags!) { final prodIcon = tag.product?.icon ?? 'Unknown'; productTagCount[prodIcon] = (productTagCount[prodIcon] ?? 0) + 1; } @@ -57,7 +57,7 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { return LayoutBuilder( builder: (context, constraints) { - bool showOnlyName = constraints.maxWidth < 250; + final showOnlyName = constraints.maxWidth < 250; return Container( padding: const EdgeInsets.all(16.0), decoration: BoxDecoration( @@ -65,7 +65,7 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( - color: Colors.grey.withOpacity(0.5), + color: Colors.grey.withValues(alpha: 0.5), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), @@ -81,11 +81,12 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { Expanded( child: Text( StringUtils.capitalizeFirstLetter(model.modelName), - style: Theme.of(context).textTheme.headlineMedium?.copyWith( - color: ColorsManager.blackColor, - fontWeight: FontWeight.bold, - fontSize: isSmallScreenSize(context) ? 13 : 20, - ), + style: + Theme.of(context).textTheme.headlineMedium?.copyWith( + color: ColorsManager.blackColor, + fontWeight: FontWeight.bold, + fontSize: isSmallScreenSize(context) ? 13 : 20, + ), maxLines: 2, overflow: TextOverflow.ellipsis, ), @@ -100,12 +101,15 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { builder: (BuildContext dialogContext) { return BlocProvider( create: (_) => LinkSpaceToModelBloc(), - child: BlocListener( + child: BlocListener( listenWhen: (previous, current) { return previous != current; }, listener: (context, state) { - final _bloc = BlocProvider.of(context); + final bloc = + BlocProvider.of( + context); if (state is SpaceModelLoading) { showDialog( context: context, @@ -113,14 +117,18 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20)), + borderRadius: + BorderRadius.circular( + 20)), elevation: 10, backgroundColor: Colors.white, - child: Padding( - padding: const EdgeInsets.symmetric( - vertical: 30, horizontal: 50), + child: const Padding( + padding: EdgeInsets.symmetric( + vertical: 30, + horizontal: 50), child: Column( - mainAxisSize: MainAxisSize.min, + mainAxisSize: + MainAxisSize.min, children: [ CustomLoadingIndicator(), ], @@ -129,14 +137,19 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { ); }, ); - } else if (state is AlreadyHaveLinkedState) { + } else if (state + is AlreadyHaveLinkedState) { Navigator.of(dialogContext).pop(); - showOverwriteDialog(context, _bloc, model); - } else if (state is SpaceValidationSuccess) { - _bloc.add(LinkSpaceModelEvent( - isOverWrite: false, selectedSpaceMode: model.uuid)); + showOverwriteDialog( + context, bloc, model); + } else if (state + is SpaceValidationSuccess) { + bloc.add(LinkSpaceModelEvent( + isOverWrite: false, + selectedSpaceMode: model.uuid)); - Future.delayed(const Duration(seconds: 1), () { + Future.delayed( + const Duration(seconds: 1), () { Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop(); @@ -144,23 +157,29 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { showDialog( context: context, - builder: (BuildContext dialogContext) { + builder: + (BuildContext dialogContext) { return const LinkingSuccessful(); }, ).then((v) { - Future.delayed(const Duration(seconds: 2), () { + Future.delayed( + const Duration(seconds: 2), () { Navigator.of(dialogContext).pop(); }); }); - } else if (state is SpaceModelLinkSuccess) { + } else if (state + is SpaceModelLinkSuccess) { Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop(); showDialog( context: context, barrierDismissible: false, - builder: (BuildContext successDialogContext) { - Future.delayed(const Duration(seconds: 2), () { - Navigator.of(successDialogContext).pop(); + builder: (BuildContext + successDialogContext) { + Future.delayed( + const Duration(seconds: 2), () { + Navigator.of(successDialogContext) + .pop(); }); return const LinkingSuccessful(); @@ -218,7 +237,8 @@ class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout { ), ), ), - if (productTagCount.isNotEmpty && model.subspaceModels != null) + if (productTagCount.isNotEmpty && + model.subspaceModels != null) Container( width: 1.0, color: ColorsManager.softGray, diff --git a/lib/pages/spaces_management/space_model/widgets/subspace_chip_widget.dart b/lib/pages/spaces_management/space_model/widgets/subspace_chip_widget.dart index 70ac6e24..0d66dbac 100644 --- a/lib/pages/spaces_management/space_model/widgets/subspace_chip_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/subspace_chip_widget.dart @@ -5,9 +5,9 @@ class SubspaceChipWidget extends StatelessWidget { final String subspace; const SubspaceChipWidget({ - Key? key, + super.key, required this.subspace, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart b/lib/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart index 4ebd65df..5cb4a9ff 100644 --- a/lib/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/common/edit_chip.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; +import 'package:syncrow_web/pages/spaces_management/create_subspace_model/views/create_subspace_model_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart'; -import 'package:syncrow_web/pages/spaces_management/create_subspace_model/views/create_subspace_model_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -15,11 +15,11 @@ class SubspaceModelCreate extends StatefulWidget { final List tags; const SubspaceModelCreate({ - Key? key, + super.key, required this.subspaces, this.onSpaceModelUpdate, required this.tags, - }) : super(key: key); + }); @override _SubspaceModelCreateState createState() => _SubspaceModelCreateState(); @@ -117,9 +117,9 @@ class _SubspaceModelCreateState extends State { .where((s) => !updatedIds.contains(s.internalId)) .toList(); - final List tagsToAppendToSpace = []; + final tagsToAppendToSpace = []; - for (var s in deletedSubspaces) { + for (final s in deletedSubspaces) { if (s.tags != null) { tagsToAppendToSpace.addAll(s.tags!); } diff --git a/lib/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart b/lib/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart index 6a6aec44..c27a1436 100644 --- a/lib/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart @@ -12,7 +12,7 @@ class SubspaceNameDisplayWidget extends StatefulWidget { final bool Function(String updatedName) validateName; const SubspaceNameDisplayWidget({ - Key? key, + super.key, required this.text, this.textStyle, this.backgroundColor = ColorsManager.whiteColors, @@ -21,7 +21,7 @@ class SubspaceNameDisplayWidget extends StatefulWidget { this.borderRadius = const BorderRadius.all(Radius.circular(10)), required this.onNameChanged, required this.validateName, - }) : super(key: key); + }); @override _SubspaceNameDisplayWidgetState createState() => diff --git a/lib/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart b/lib/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart index 86f99e02..2ff1b085 100644 --- a/lib/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart +++ b/lib/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart @@ -50,7 +50,8 @@ class TagChipDisplay extends StatelessWidget { Widget build(BuildContext context) { final hasTags = spaceModel?.tags?.isNotEmpty ?? false; final hasSubspaceTags = - spaceModel?.subspaceModels?.any((e) => e.tags?.isNotEmpty ?? false) ?? false; + spaceModel?.subspaceModels?.any((e) => e.tags?.isNotEmpty ?? false) ?? + false; if (hasTags || hasSubspaceTags) { return Container( diff --git a/lib/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart b/lib/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart index 1de2ae13..23cfb1d9 100644 --- a/lib/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart +++ b/lib/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart @@ -13,7 +13,7 @@ class CenterBodyBloc extends Bloc { emit(SpaceModelState()); }); - on((event, emit) { + on((event, emit) { emit(CommunitySelectedState()); }); } diff --git a/lib/pages/spaces_management/structure_selector/bloc/center_body_event.dart b/lib/pages/spaces_management/structure_selector/bloc/center_body_event.dart index 72cdbd1c..d70a0b55 100644 --- a/lib/pages/spaces_management/structure_selector/bloc/center_body_event.dart +++ b/lib/pages/spaces_management/structure_selector/bloc/center_body_event.dart @@ -5,4 +5,4 @@ class CommunityStructureSelectedEvent extends CenterBodyEvent {} class SpaceModelSelectedEvent extends CenterBodyEvent {} -class CommunitySelectedEvent extends CenterBodyEvent {} \ No newline at end of file +class CommunitySelectedEvent extends CenterBodyEvent {} diff --git a/lib/pages/spaces_management/structure_selector/view/center_body_widget.dart b/lib/pages/spaces_management/structure_selector/view/center_body_widget.dart index dbc6c7ef..6b0ff481 100644 --- a/lib/pages/spaces_management/structure_selector/view/center_body_widget.dart +++ b/lib/pages/spaces_management/structure_selector/view/center_body_widget.dart @@ -2,11 +2,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; +import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_event.dart'; import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_state.dart'; -import '../bloc/center_body_bloc.dart'; class CenterBodyWidget extends StatelessWidget { + const CenterBodyWidget({super.key}); + @override Widget build(BuildContext context) { return BlocBuilder( @@ -52,7 +54,7 @@ class CenterBodyWidget extends StatelessWidget { .textTheme .bodyLarge! .color! - .withOpacity(0.5), + .withValues(alpha: 0.5), ), ), ), @@ -73,7 +75,7 @@ class CenterBodyWidget extends StatelessWidget { // .textTheme // .bodyLarge! // .color! - // .withOpacity(0.5), + // .withValues(alpha:0.5), // ), // ), // ), diff --git a/lib/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart b/lib/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart index 27f183a6..5ee52b08 100644 --- a/lib/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart +++ b/lib/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart @@ -1,5 +1,4 @@ import 'package:equatable/equatable.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; @@ -13,7 +12,7 @@ abstract class AddDeviceTypeModelEvent extends Equatable { class UpdateProductCountEvent extends AddDeviceTypeModelEvent { final SelectedProduct selectedProduct; - UpdateProductCountEvent({required this.selectedProduct}); + const UpdateProductCountEvent({required this.selectedProduct}); @override List get props => [selectedProduct]; diff --git a/lib/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart b/lib/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart index c0226ba8..e9823fee 100644 --- a/lib/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart +++ b/lib/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart @@ -2,10 +2,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/common/buttons/cancel_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; -import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; +import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart'; import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart'; @@ -80,7 +80,8 @@ class AddDeviceTypeModelWidget extends StatelessWidget { const SizedBox(height: 16), Expanded( child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20.0), + padding: + const EdgeInsets.symmetric(horizontal: 20.0), child: ScrollableGridViewWidget( isCreate: isCreate, products: products, @@ -152,10 +153,11 @@ class AddDeviceTypeModelWidget extends StatelessWidget { ), SizedBox( width: 140, - child: BlocBuilder( + child: + BlocBuilder( builder: (context, state) { - final isDisabled = - state is AddDeviceModelLoaded && state.selectedProducts.isEmpty; + final isDisabled = state is AddDeviceModelLoaded && + state.selectedProducts.isEmpty; return DefaultButton( backgroundColor: ColorsManager.secondaryColor, @@ -168,13 +170,15 @@ class AddDeviceTypeModelWidget extends StatelessWidget { : () async { if (state is AddDeviceModelLoaded && state.selectedProducts.isNotEmpty) { - final initialTags = TagHelper.generateInitialTags( + final initialTags = + TagHelper.generateInitialTags( spaceTagModels: spaceTagModels, subspaces: subspaces, ); - final dialogTitle = - initialTags.isNotEmpty ? 'Edit Device' : 'Assign Tags'; + final dialogTitle = initialTags.isNotEmpty + ? 'Edit Device' + : 'Assign Tags'; Navigator.of(context).pop(); await showDialog( context: context, diff --git a/lib/pages/spaces_management/tag_model/widgets/scrollable_grid_view_widget.dart b/lib/pages/spaces_management/tag_model/widgets/scrollable_grid_view_widget.dart index d1775c66..8a64fe41 100644 --- a/lib/pages/spaces_management/tag_model/widgets/scrollable_grid_view_widget.dart +++ b/lib/pages/spaces_management/tag_model/widgets/scrollable_grid_view_widget.dart @@ -12,13 +12,12 @@ class ScrollableGridViewWidget extends StatelessWidget { final List? initialProductCounts; final bool isCreate; - const ScrollableGridViewWidget({ - super.key, - required this.products, - required this.crossAxisCount, - this.initialProductCounts, - required this.isCreate - }); + const ScrollableGridViewWidget( + {super.key, + required this.products, + required this.crossAxisCount, + this.initialProductCounts, + required this.isCreate}); @override Widget build(BuildContext context) { diff --git a/lib/pages/visitor_password/bloc/visitor_password_bloc.dart b/lib/pages/visitor_password/bloc/visitor_password_bloc.dart index 438b1abf..6bcd8b62 100644 --- a/lib/pages/visitor_password/bloc/visitor_password_bloc.dart +++ b/lib/pages/visitor_password/bloc/visitor_password_bloc.dart @@ -14,14 +14,10 @@ import 'package:syncrow_web/pages/visitor_password/model/schedule_model.dart'; import 'package:syncrow_web/services/access_mang_api.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; -import 'package:syncrow_web/utils/constants/strings_manager.dart'; -import 'package:syncrow_web/utils/constants/temp_const.dart'; -import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart'; import 'package:syncrow_web/utils/snack_bar.dart'; class VisitorPasswordBloc extends Bloc { - VisitorPasswordBloc() : super(VisitorPasswordInitial()) { on(selectUsageFrequency); on(_onFetchDevice); @@ -71,13 +67,13 @@ class VisitorPasswordBloc String startTimeAccess = 'Start Time'; String endTimeAccess = 'End Time'; PasswordStatus? passwordStatus; - selectAccessType( + void selectAccessType( SelectPasswordType event, Emitter emit) { accessTypeSelected = event.type; emit(PasswordTypeSelected(event.type)); } - selectUsageFrequency( + void selectUsageFrequency( SelectUsageFrequency event, Emitter emit) { usageFrequencySelected = event.usageType; emit(UsageFrequencySelected(event.usageType)); @@ -87,7 +83,7 @@ class VisitorPasswordBloc SelectTimeVisitorPassword event, Emitter emit, ) async { - final DateTime? picked = await showDatePicker( + final picked = await showDatePicker( context: event.context, initialDate: DateTime.now(), firstDate: DateTime(2015, 8), @@ -95,7 +91,7 @@ class VisitorPasswordBloc ); if (picked != null) { - final TimeOfDay? timePicked = await showTimePicker( + final timePicked = await showTimePicker( context: event.context, initialTime: TimeOfDay.now(), builder: (context, child) { @@ -164,13 +160,13 @@ class VisitorPasswordBloc } List> days = [ - {"day": "Sun", "key": "Sun"}, - {"day": "Mon", "key": "Mon"}, - {"day": "Tue", "key": "Tue"}, - {"day": "Wed", "key": "Wed"}, - {"day": "Thu", "key": "Thu"}, - {"day": "Fri", "key": "Fri"}, - {"day": "Sat", "key": "Sat"}, + {'day': 'Sun', 'key': 'Sun'}, + {'day': 'Mon', 'key': 'Mon'}, + {'day': 'Tue', 'key': 'Tue'}, + {'day': 'Wed', 'key': 'Wed'}, + {'day': 'Thu', 'key': 'Thu'}, + {'day': 'Fri', 'key': 'Fri'}, + {'day': 'Sat', 'key': 'Sat'}, ]; List selectedDays = []; @@ -192,12 +188,12 @@ class VisitorPasswordBloc FetchDevice event, Emitter emit) async { try { emit(DeviceLoaded()); - final projectUuid = await ProjectManager.getProjectUUID() ?? ''; + final projectUuid = await ProjectManager.getProjectUUID() ?? ''; data = await AccessMangApi().fetchDoorLockDeviceList(projectUuid); emit(TableLoaded(data)); } catch (e) { - print("error: $e"); + print('error: $e'); emit(FailedState(e.toString())); } } @@ -208,7 +204,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); generate7DigitNumber(); - var res = await AccessMangApi().postOnlineOneTime( + final res = await AccessMangApi().postOnlineOneTime( email: event.email, password: passwordController, devicesUuid: selectedDevices, @@ -222,8 +218,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - String errorMessage = errorData['message']; - emit(FailedState(errorMessage.toString())); + final String errorMessage = errorData['message']; + emit(FailedState(errorMessage)); } } @@ -234,13 +230,12 @@ class VisitorPasswordBloc emit(LoadingInitialState()); await generate7DigitNumber(); - var res = await AccessMangApi().postOnlineMultipleTime( + final res = await AccessMangApi().postOnlineMultipleTime( scheduleList: [ if (repeat) Schedule( effectiveTime: getTimeFromDateTimeString(effectiveTime), - invalidTime: - getTimeFromDateTimeString(expirationTime).toString(), + invalidTime: getTimeFromDateTimeString(expirationTime), workingDay: selectedDays, ), ], @@ -257,8 +252,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - String errorMessage = errorData['message']; - emit(FailedState(errorMessage.toString())); + final String errorMessage = errorData['message']; + emit(FailedState(errorMessage)); } } @@ -268,7 +263,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); await generate7DigitNumber(); - var res = await AccessMangApi().postOffLineOneTime( + final res = await AccessMangApi().postOffLineOneTime( email: event.email, devicesUuid: selectedDevices, passwordName: event.passwordName); @@ -279,8 +274,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - String errorMessage = errorData['message']; - emit(FailedState(errorMessage.toString())); + final String errorMessage = errorData['message']; + emit(FailedState(errorMessage)); } } @@ -290,7 +285,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); await generate7DigitNumber(); - var res = await AccessMangApi().postOffLineMultipleTime( + final res = await AccessMangApi().postOffLineMultipleTime( email: event.email, devicesUuid: selectedDevices, passwordName: event.passwordName, @@ -304,8 +299,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - String errorMessage = errorData['message']; - emit(FailedState(errorMessage.toString())); + final String errorMessage = errorData['message']; + emit(FailedState(errorMessage)); } } @@ -327,9 +322,9 @@ class VisitorPasswordBloc Future generate7DigitNumber() async { passwordController = ''; - Random random = Random(); - int min = 1000000; - int max = 9999999; + final random = Random(); + const min = 1000000; + const max = 9999999; passwordController = (min + random.nextInt(max - min + 1)).toString(); return passwordController; } @@ -365,7 +360,7 @@ class VisitorPasswordBloc emit(TableLoaded(event.filteredData)); } - addDeviceToList(context) { + void addDeviceToList(context) { selectedDevices = selectedDeviceIds; Navigator.of(context).pop(selectedDevices); } @@ -373,14 +368,14 @@ class VisitorPasswordBloc Future selectTimeOfLinePassword( SelectTimeEvent event, Emitter emit) async { emit(ChangeTimeState()); - final DateTime? picked = await showDatePicker( + final picked = await showDatePicker( context: event.context, initialDate: DateTime.now(), firstDate: DateTime.now(), lastDate: DateTime.now().add(const Duration(days: 2095)), ); if (picked != null) { - final TimeOfDay? timePicked = await showHourPicker( + final timePicked = await showHourPicker( context: event.context, initialTime: TimeOfDay.now(), ); @@ -405,7 +400,7 @@ class VisitorPasswordBloc if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) { accessPeriodValidate = - "Effective Time cannot be later than Expiration Time."; + 'Effective Time cannot be later than Expiration Time.'; } else { accessPeriodValidate = ''; effectiveTime = selectedDateTime.toString().split('.').first; @@ -427,7 +422,7 @@ class VisitorPasswordBloc } } - changeTime(ChangeTimeEvent event, Emitter emit) { + void changeTime(ChangeTimeEvent event, Emitter emit) { if (event.isStartEndTime == true) { startTime = event.val; } else { @@ -437,8 +432,8 @@ class VisitorPasswordBloc DateTime? convertStringToDateTime(String dateTimeString) { try { - final DateFormat inputFormat = DateFormat('yyyy-MM-dd HH:mm:ss'); - DateTime dateTime = inputFormat.parse(dateTimeString); + final inputFormat = DateFormat('yyyy-MM-dd HH:mm:ss'); + final dateTime = inputFormat.parse(dateTimeString); return dateTime; } catch (e) { return null; @@ -446,7 +441,7 @@ class VisitorPasswordBloc } String getTimeFromDateTimeString(String dateTimeString) { - DateTime? dateTime = convertStringToDateTime(dateTimeString); + final dateTime = convertStringToDateTime(dateTimeString); if (dateTime == null) return ''; return DateFormat('HH:mm').format(dateTime); } diff --git a/lib/pages/visitor_password/bloc/visitor_password_event.dart b/lib/pages/visitor_password/bloc/visitor_password_event.dart index 6ecae200..6e7b056b 100644 --- a/lib/pages/visitor_password/bloc/visitor_password_event.dart +++ b/lib/pages/visitor_password/bloc/visitor_password_event.dart @@ -140,7 +140,7 @@ class FilterDataEvent extends VisitorPasswordEvent { class UpdateFilteredDevicesEvent extends VisitorPasswordEvent { final List filteredData; - UpdateFilteredDevicesEvent(this.filteredData); + const UpdateFilteredDevicesEvent(this.filteredData); } class SelectTimeEvent extends VisitorPasswordEvent { diff --git a/lib/pages/visitor_password/model/device_model.dart b/lib/pages/visitor_password/model/device_model.dart index f9711eed..dc6c4858 100644 --- a/lib/pages/visitor_password/model/device_model.dart +++ b/lib/pages/visitor_password/model/device_model.dart @@ -51,8 +51,8 @@ class DeviceModel { // Deserialize from JSON factory DeviceModel.fromJson(Map json) { - String tempIcon = ''; - DeviceType type = devicesTypesMap[json['productType']] ?? DeviceType.Other; + var tempIcon = ''; + final type = devicesTypesMap[json['productType']] ?? DeviceType.Other; if (type == DeviceType.LightBulb) { tempIcon = Assets.lightBulb; } else if (type == DeviceType.CeilingSensor || diff --git a/lib/pages/visitor_password/model/failed_operation.dart b/lib/pages/visitor_password/model/failed_operation.dart index 223f9ac5..02bd6802 100644 --- a/lib/pages/visitor_password/model/failed_operation.dart +++ b/lib/pages/visitor_password/model/failed_operation.dart @@ -26,8 +26,6 @@ class FailedOperation { } } - - class SuccessOperation { final bool success; // final Result result; @@ -92,8 +90,6 @@ class SuccessOperation { // } // } - - class PasswordStatus { final List successOperations; final List failedOperations; @@ -121,4 +117,3 @@ class PasswordStatus { }; } } - diff --git a/lib/pages/visitor_password/view/add_device_dialog.dart b/lib/pages/visitor_password/view/add_device_dialog.dart index d69aa21d..68f970b3 100644 --- a/lib/pages/visitor_password/view/add_device_dialog.dart +++ b/lib/pages/visitor_password/view/add_device_dialog.dart @@ -2,15 +2,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:syncrow_web/pages/common/access_device_table.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; -import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; +import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart'; import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart'; import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_event.dart'; import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_state.dart'; import 'package:syncrow_web/utils/color_manager.dart'; -import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/app_enum.dart'; +import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/style.dart'; class AddDeviceDialog extends StatelessWidget { @@ -18,15 +17,14 @@ class AddDeviceDialog extends StatelessWidget { const AddDeviceDialog({super.key, this.selectedDeviceIds}); @override Widget build(BuildContext context) { - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; return BlocProvider( - create: (context) => - VisitorPasswordBloc()..add(FetchDevice()), + create: (context) => VisitorPasswordBloc()..add(FetchDevice()), child: BlocBuilder( builder: (BuildContext context, VisitorPasswordState state) { final visitorBloc = BlocProvider.of(context); if (state is TableLoaded) { - for (var device in selectedDeviceIds!) { + for (final device in selectedDeviceIds!) { if (selectedDeviceIds!.contains(device)) { visitorBloc.add(SelectDeviceEvent(device)); } @@ -54,7 +52,7 @@ class AddDeviceDialog extends StatelessWidget { padding: const EdgeInsets.all(15), decoration: containerDecoration.copyWith( color: ColorsManager.worningColor, - border: Border.all(color: Color(0xffFFD22F)), + border: Border.all(color: const Color(0xffFFD22F)), boxShadow: []), child: Row( children: [ @@ -128,9 +126,7 @@ class AddDeviceDialog extends StatelessWidget { width: size.width * 0.06, child: Center( child: DefaultButton( - onPressed: () { - visitorBloc.filterDevices(); - }, + onPressed: visitorBloc.filterDevices, borderRadius: 9, child: const Text('Search'), ), @@ -141,7 +137,7 @@ class AddDeviceDialog extends StatelessWidget { const SizedBox(width: 10), Expanded( flex: 2, - child: Container( + child: SizedBox( width: size.width * 0.06, child: DefaultButton( backgroundColor: ColorsManager.whiteColors, @@ -177,7 +173,7 @@ class AddDeviceDialog extends StatelessWidget { isEmpty: visitorBloc.data.isEmpty, selectAll: (p0) { visitorBloc.selectedDeviceIds.clear(); - for (var item in state.data) { + for (final item in state.data) { visitorBloc .add(SelectDeviceEvent(item.uuid)); } @@ -201,7 +197,7 @@ class AddDeviceDialog extends StatelessWidget { item.uuid.toString(), item.productType.toString(), item.spaceName.toString(), - item.online.value.toString(), + item.online.value, ]; }).toList(), ) @@ -223,7 +219,7 @@ class AddDeviceDialog extends StatelessWidget { backgroundColor: Colors.white, child: Text( 'Cancel', - style: Theme.of(context).textTheme.bodyMedium!, + style: Theme.of(context).textTheme.bodyMedium, ), ), ), @@ -235,7 +231,7 @@ class AddDeviceDialog extends StatelessWidget { visitorBloc.addDeviceToList(context); }, borderRadius: 8, - child: Text('Ok'), + child: const Text('Ok'), ), ), ], diff --git a/lib/pages/visitor_password/view/repeat_widget.dart b/lib/pages/visitor_password/view/repeat_widget.dart index 8b40b580..621dbbba 100644 --- a/lib/pages/visitor_password/view/repeat_widget.dart +++ b/lib/pages/visitor_password/view/repeat_widget.dart @@ -14,7 +14,7 @@ class RepeatWidget extends StatelessWidget { @override Widget build(BuildContext context) { - Size size = MediaQuery.of(context).size; + final size = MediaQuery.of(context).size; return BlocBuilder( builder: (context, state) { final visitorBloc = BlocProvider.of(context); @@ -29,7 +29,7 @@ class RepeatWidget extends StatelessWidget { children: visitorBloc.days.map((day) { return Container( width: 70, // Adjust width as needed - margin: EdgeInsets.all(5), + margin: const EdgeInsets.all(5), child: CheckboxListTile( contentPadding: EdgeInsets.zero, title: Text( diff --git a/lib/pages/visitor_password/view/visitor_password_dialog.dart b/lib/pages/visitor_password/view/visitor_password_dialog.dart index 1e43af46..1849ccf2 100644 --- a/lib/pages/visitor_password/view/visitor_password_dialog.dart +++ b/lib/pages/visitor_password/view/visitor_password_dialog.dart @@ -2,7 +2,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/common/date_time_widget.dart'; import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart'; @@ -20,8 +19,11 @@ class VisitorPasswordDialog extends StatelessWidget { @override Widget build(BuildContext context) { - Size size = MediaQuery.of(context).size; - var text = Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.black, fontSize: 13); + final size = MediaQuery.of(context).size; + final text = Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.black, fontSize: 13); return BlocProvider( create: (context) => VisitorPasswordBloc(), child: BlocListener( @@ -35,7 +37,8 @@ class VisitorPasswordDialog extends StatelessWidget { title: 'Sent Successfully', widgeta: Column( children: [ - if (visitorBloc.passwordStatus!.failedOperations.isNotEmpty) + if (visitorBloc + .passwordStatus!.failedOperations.isNotEmpty) Column( children: [ const Text('Failed Devices'), @@ -45,22 +48,26 @@ class VisitorPasswordDialog extends StatelessWidget { child: ListView.builder( scrollDirection: Axis.horizontal, shrinkWrap: true, - itemCount: visitorBloc.passwordStatus!.failedOperations.length, + itemCount: visitorBloc + .passwordStatus!.failedOperations.length, itemBuilder: (context, index) { return Container( - margin: EdgeInsets.all(5), + margin: const EdgeInsets.all(5), decoration: containerDecoration, height: 45, child: Center( child: Text(visitorBloc - .passwordStatus!.failedOperations[index].deviceUuid)), + .passwordStatus! + .failedOperations[index] + .deviceUuid)), ); }, ), ), ], ), - if (visitorBloc.passwordStatus!.successOperations.isNotEmpty) + if (visitorBloc + .passwordStatus!.successOperations.isNotEmpty) Column( children: [ const Text('Success Devices'), @@ -70,15 +77,18 @@ class VisitorPasswordDialog extends StatelessWidget { child: ListView.builder( scrollDirection: Axis.horizontal, shrinkWrap: true, - itemCount: visitorBloc.passwordStatus!.successOperations.length, + itemCount: visitorBloc + .passwordStatus!.successOperations.length, itemBuilder: (context, index) { return Container( - margin: EdgeInsets.all(5), + margin: const EdgeInsets.all(5), decoration: containerDecoration, height: 45, child: Center( - child: Text(visitorBloc.passwordStatus! - .successOperations[index].deviceUuid)), + child: Text(visitorBloc + .passwordStatus! + .successOperations[index] + .deviceUuid)), ); }, ), @@ -89,7 +99,6 @@ class VisitorPasswordDialog extends StatelessWidget { )) .then((v) { Navigator.of(context).pop(true); - }); } else if (state is FailedState) { visitorBloc.stateDialog( @@ -102,15 +111,16 @@ class VisitorPasswordDialog extends StatelessWidget { child: BlocBuilder( builder: (BuildContext context, VisitorPasswordState state) { final visitorBloc = BlocProvider.of(context); - bool isRepeat = state is IsRepeatState ? state.repeat : visitorBloc.repeat; + final isRepeat = + state is IsRepeatState ? state.repeat : visitorBloc.repeat; return AlertDialog( backgroundColor: Colors.white, title: Text( 'Create visitor password', - style: Theme.of(context) - .textTheme - .headlineLarge! - .copyWith(fontWeight: FontWeight.w400, fontSize: 24, color: Colors.black), + style: Theme.of(context).textTheme.headlineLarge!.copyWith( + fontWeight: FontWeight.w400, + fontSize: 24, + color: Colors.black), ), content: state is LoadingInitialState ? const Center(child: CircularProgressIndicator()) @@ -128,7 +138,8 @@ class VisitorPasswordDialog extends StatelessWidget { flex: 2, child: CustomWebTextField( validator: visitorBloc.validate, - controller: visitorBloc.userNameController, + controller: + visitorBloc.userNameController, isRequired: true, textFieldName: 'Name', description: '', @@ -177,20 +188,26 @@ class VisitorPasswordDialog extends StatelessWidget { SizedBox( width: size.width * 0.12, child: RadioListTile( - contentPadding: EdgeInsets.zero, + contentPadding: + EdgeInsets.zero, title: Text( 'Online Password', style: text, ), value: 'Online Password', - groupValue: (state is PasswordTypeSelected) + groupValue: (state + is PasswordTypeSelected) ? state.selectedType - : visitorBloc.accessTypeSelected, + : visitorBloc + .accessTypeSelected, onChanged: (String? value) { if (value != null) { context - .read() - .add(SelectPasswordType(value)); + .read< + VisitorPasswordBloc>() + .add( + SelectPasswordType( + value)); } }, ), @@ -198,17 +215,25 @@ class VisitorPasswordDialog extends StatelessWidget { SizedBox( width: size.width * 0.12, child: RadioListTile( - contentPadding: EdgeInsets.zero, - title: Text('Offline Password', style: text), + contentPadding: + EdgeInsets.zero, + title: Text( + 'Offline Password', + style: text), value: 'Offline Password', - groupValue: (state is PasswordTypeSelected) + groupValue: (state + is PasswordTypeSelected) ? state.selectedType - : visitorBloc.accessTypeSelected, + : visitorBloc + .accessTypeSelected, onChanged: (String? value) { if (value != null) { context - .read() - .add(SelectPasswordType(value)); + .read< + VisitorPasswordBloc>() + .add( + SelectPasswordType( + value)); } }, ), @@ -242,21 +267,29 @@ class VisitorPasswordDialog extends StatelessWidget { ), ], ), - if (visitorBloc.accessTypeSelected == 'Online Password') + if (visitorBloc.accessTypeSelected == + 'Online Password') Text( 'Only currently online devices can be selected. It is recommended to use when the device network is stable, and the system randomly generates a digital password', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - fontWeight: FontWeight.w400, - color: ColorsManager.grayColor, - fontSize: 9), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + fontWeight: FontWeight.w400, + color: ColorsManager.grayColor, + fontSize: 9), ), - if (visitorBloc.accessTypeSelected == 'Offline Password') + if (visitorBloc.accessTypeSelected == + 'Offline Password') Text( 'Unaffected by the online status of the device, you can select online or offline device, and the system randomly generates a digital password', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - fontWeight: FontWeight.w400, - color: ColorsManager.grayColor, - fontSize: 9), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + fontWeight: FontWeight.w400, + color: ColorsManager.grayColor, + fontSize: 9), ), // if (visitorBloc.accessTypeSelected == 'Dynamic Password') // Text( @@ -271,143 +304,206 @@ class VisitorPasswordDialog extends StatelessWidget { ) ], ), - visitorBloc.accessTypeSelected == 'Dynamic Password' - ? const SizedBox() - : Column( - crossAxisAlignment: CrossAxisAlignment.start, + if (visitorBloc.accessTypeSelected == + 'Dynamic Password') + const SizedBox() + else + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( children: [ - Row( - children: [ - Text( - '* ', - style: Theme.of(context) - .textTheme - .bodyMedium! - .copyWith(color: Colors.red), - ), - Text( - 'Usage Frequency', - style: text, - ), - ], + Text( + '* ', + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(color: Colors.red), ), - Row( - children: [ - SizedBox( - width: size.width * 0.12, - child: RadioListTile( - contentPadding: EdgeInsets.zero, - title: Text( - 'One-Time', - style: text, - ), - value: 'One-Time', - groupValue: (state is UsageFrequencySelected) - ? state.selectedFrequency - : visitorBloc.usageFrequencySelected, - onChanged: (String? value) { - if (value != null) { - context - .read() - .add(SelectUsageFrequency(value)); - } - }, - ), - ), - SizedBox( - width: size.width * 0.12, - child: RadioListTile( - contentPadding: EdgeInsets.zero, - title: Text('Periodic', style: text), - value: 'Periodic', - groupValue: (state is UsageFrequencySelected) - ? state.selectedFrequency - : visitorBloc.usageFrequencySelected, - onChanged: (String? value) { - if (value != null) { - context.read() - .add(SelectUsageFrequency(value)); - } - }, - ), - ), - ], + Text( + 'Usage Frequency', + style: text, ), - - //One-Time - if (visitorBloc.usageFrequencySelected == 'One-Time' && - visitorBloc.accessTypeSelected == 'Online Password') - Text( - 'Within the validity period, each device can be unlocked only once.', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.grayColor, fontSize: 9), - ), - if (visitorBloc.usageFrequencySelected == 'One-Time' && - visitorBloc.accessTypeSelected == 'Offline Password') - Text( - 'Within the validity period, each device can be unlocked only once, and the maximum validity period is 6 hours', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.grayColor, fontSize: 9), - ), - - // Periodic - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Offline Password') - Text( - 'Within the validity period, there is no limit to the number of times each device can be unlocked, and it should be used at least once within 24 hours after the entry into force.', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.grayColor, fontSize: 9), - ), - - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Online Password') - Text( - 'Within the validity period, there is no limit to the number of times each device can be unlocked.', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - color: ColorsManager.grayColor, fontSize: 9), - ), ], ), + Row( + children: [ + SizedBox( + width: size.width * 0.12, + child: RadioListTile( + contentPadding: EdgeInsets.zero, + title: Text( + 'One-Time', + style: text, + ), + value: 'One-Time', + groupValue: (state + is UsageFrequencySelected) + ? state.selectedFrequency + : visitorBloc + .usageFrequencySelected, + onChanged: (String? value) { + if (value != null) { + context + .read() + .add(SelectUsageFrequency( + value)); + } + }, + ), + ), + SizedBox( + width: size.width * 0.12, + child: RadioListTile( + contentPadding: EdgeInsets.zero, + title: + Text('Periodic', style: text), + value: 'Periodic', + groupValue: (state + is UsageFrequencySelected) + ? state.selectedFrequency + : visitorBloc + .usageFrequencySelected, + onChanged: (String? value) { + if (value != null) { + context + .read() + .add(SelectUsageFrequency( + value)); + } + }, + ), + ), + ], + ), + + //One-Time + if (visitorBloc.usageFrequencySelected == + 'One-Time' && + visitorBloc.accessTypeSelected == + 'Online Password') + Text( + 'Within the validity period, each device can be unlocked only once.', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + color: ColorsManager.grayColor, + fontSize: 9), + ), + if (visitorBloc.usageFrequencySelected == + 'One-Time' && + visitorBloc.accessTypeSelected == + 'Offline Password') + Text( + 'Within the validity period, each device can be unlocked only once, and the maximum validity period is 6 hours', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + color: ColorsManager.grayColor, + fontSize: 9), + ), + + // Periodic + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') + Text( + 'Within the validity period, there is no limit to the number of times each device can be unlocked, and it should be used at least once within 24 hours after the entry into force.', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + color: ColorsManager.grayColor, + fontSize: 9), + ), + + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Online Password') + Text( + 'Within the validity period, there is no limit to the number of times each device can be unlocked.', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + color: ColorsManager.grayColor, + fontSize: 9), + ), + ], + ), const SizedBox( height: 20, ), - if ((visitorBloc.usageFrequencySelected != 'One-Time' || - visitorBloc.accessTypeSelected != 'Offline Password') && + if ((visitorBloc.usageFrequencySelected != + 'One-Time' || + visitorBloc.accessTypeSelected != + 'Offline Password') && (visitorBloc.usageFrequencySelected != '')) DateTimeWebWidget( isRequired: true, title: 'Access Period', size: size, endTime: () { - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Offline Password') { - visitorBloc.add(SelectTimeEvent(context: context, isEffective: false)); + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') { + visitorBloc.add(SelectTimeEvent( + context: context, + isEffective: false)); } else { - visitorBloc.add(SelectTimeVisitorPassword(context: context, isStart: false, isRepeat: false)); + visitorBloc.add( + SelectTimeVisitorPassword( + context: context, + isStart: false, + isRepeat: false)); } }, startTime: () { - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Offline Password') { - visitorBloc.add( - SelectTimeEvent(context: context, isEffective: true)); + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') { + visitorBloc.add(SelectTimeEvent( + context: context, + isEffective: true)); } else { - visitorBloc.add(SelectTimeVisitorPassword( - context: context, isStart: true, isRepeat: false)); + visitorBloc.add( + SelectTimeVisitorPassword( + context: context, + isStart: true, + isRepeat: false)); } }, - firstString: (visitorBloc.usageFrequencySelected == - 'Periodic' && visitorBloc.accessTypeSelected == 'Offline Password') + firstString: (visitorBloc + .usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') ? visitorBloc.effectiveTime - : visitorBloc.startTimeAccess.toString(), - secondString: (visitorBloc.usageFrequencySelected == - 'Periodic' && visitorBloc.accessTypeSelected == 'Offline Password') + : visitorBloc.startTimeAccess, + secondString: (visitorBloc + .usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') ? visitorBloc.expirationTime - : visitorBloc.endTimeAccess.toString(), + : visitorBloc.endTimeAccess, icon: Assets.calendarIcon), - const SizedBox(height: 10,), - Text(visitorBloc.accessPeriodValidate, - style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: ColorsManager.red),), + const SizedBox( + height: 10, + ), + Text( + visitorBloc.accessPeriodValidate, + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(color: ColorsManager.red), + ), const SizedBox( height: 20, ), @@ -431,16 +527,21 @@ class VisitorPasswordDialog extends StatelessWidget { ), Text( 'Within the validity period, each device can be unlocked only once.', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - fontWeight: FontWeight.w400, - color: ColorsManager.grayColor, - fontSize: 9), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + fontWeight: FontWeight.w400, + color: ColorsManager.grayColor, + fontSize: 9), ), const SizedBox( height: 20, ), - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Online Password') + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Online Password') SizedBox( width: 100, child: Column( @@ -451,7 +552,8 @@ class VisitorPasswordDialog extends StatelessWidget { child: CupertinoSwitch( value: visitorBloc.repeat, onChanged: (value) { - visitorBloc.add(ToggleRepeatEvent()); + visitorBloc + .add(ToggleRepeatEvent()); }, applyTheme: true, ), @@ -459,9 +561,13 @@ class VisitorPasswordDialog extends StatelessWidget { ], ), ), - if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Online Password') - isRepeat ? const RepeatWidget() : const SizedBox(), + if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Online Password') + isRepeat + ? const RepeatWidget() + : const SizedBox(), Container( decoration: containerDecoration, width: size.width / 9, @@ -472,22 +578,28 @@ class VisitorPasswordDialog extends StatelessWidget { barrierDismissible: false, builder: (BuildContext context) { return AddDeviceDialog( - selectedDeviceIds: visitorBloc.selectedDevices, + selectedDeviceIds: + visitorBloc.selectedDevices, ); }, ).then((listDevice) { if (listDevice != null) { - visitorBloc.selectedDevices = listDevice; + visitorBloc.selectedDevices = + listDevice; } }); }, borderRadius: 8, child: Text( '+ Add Device', - style: Theme.of(context).textTheme.bodySmall!.copyWith( - fontWeight: FontWeight.w400, - color: ColorsManager.whiteColors, - fontSize: 12), + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith( + fontWeight: FontWeight.w400, + color: + ColorsManager.whiteColors, + fontSize: 12), ), ), ), @@ -525,30 +637,35 @@ class VisitorPasswordDialog extends StatelessWidget { onPressed: () { if (visitorBloc.forgetFormKey.currentState!.validate()) { if (visitorBloc.selectedDevices.isNotEmpty) { - if (visitorBloc.usageFrequencySelected == 'One-Time' && - visitorBloc.accessTypeSelected == 'Offline Password') { + if (visitorBloc.usageFrequencySelected == + 'One-Time' && + visitorBloc.accessTypeSelected == + 'Offline Password') { setPasswordFunction(context, size, visitorBloc); - } else if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Offline Password') { + } else if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') { if (visitorBloc.expirationTime != 'End Time' && - visitorBloc.effectiveTime != 'Start Time' ) { + visitorBloc.effectiveTime != 'Start Time') { setPasswordFunction(context, size, visitorBloc); - }else{ + } else { visitorBloc.stateDialog( context: context, - message: 'Please select Access Period to continue', + message: + 'Please select Access Period to continue', title: 'Access Period'); } - } else if( - visitorBloc.endTimeAccess.toString()!='End Time' - &&visitorBloc.startTimeAccess.toString()!='Start Time') { + } else if (visitorBloc.endTimeAccess != 'End Time' && + visitorBloc.startTimeAccess != 'Start Time') { if (visitorBloc.effectiveTimeTimeStamp != null && visitorBloc.expirationTimeTimeStamp != null) { if (isRepeat == true) { if (visitorBloc.expirationTime != 'End Time' && visitorBloc.effectiveTime != 'Start Time' && visitorBloc.selectedDays.isNotEmpty) { - setPasswordFunction(context, size, visitorBloc); + setPasswordFunction( + context, size, visitorBloc); } else { visitorBloc.stateDialog( context: context, @@ -562,14 +679,16 @@ class VisitorPasswordDialog extends StatelessWidget { } else { visitorBloc.stateDialog( context: context, - message: 'Please select Access Period to continue', + message: + 'Please select Access Period to continue', title: 'Access Period'); } - }else{ - visitorBloc.stateDialog( - context: context, - message: 'Please select Access Period to continue', - title: 'Access Period'); + } else { + visitorBloc.stateDialog( + context: context, + message: + 'Please select Access Period to continue', + title: 'Access Period'); } } else { visitorBloc.stateDialog( @@ -614,8 +733,9 @@ class VisitorPasswordDialog extends StatelessWidget { alignment: Alignment.center, content: SizedBox( height: size.height * 0.25, - child: Center( - child: CircularProgressIndicator(), // Display a loading spinner + child: const Center( + child: + CircularProgressIndicator(), // Display a loading spinner ), ), ); @@ -639,7 +759,10 @@ class VisitorPasswordDialog extends StatelessWidget { ), Text( 'Set Password', - style: Theme.of(context).textTheme.headlineLarge!.copyWith( + style: Theme.of(context) + .textTheme + .headlineLarge! + .copyWith( fontSize: 30, fontWeight: FontWeight.w400, color: Colors.black, @@ -689,37 +812,45 @@ class VisitorPasswordDialog extends StatelessWidget { onPressed: () { Navigator.pop(context); if (visitorBloc.usageFrequencySelected == 'One-Time' && - visitorBloc.accessTypeSelected == 'Online Password') { + visitorBloc.accessTypeSelected == + 'Online Password') { visitorBloc.add(OnlineOneTimePasswordEvent( context: context, passwordName: visitorBloc.userNameController.text, email: visitorBloc.emailController.text, )); - } - else if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Online Password') { + } else if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Online Password') { visitorBloc.add(OnlineMultipleTimePasswordEvent( passwordName: visitorBloc.userNameController.text, email: visitorBloc.emailController.text, - effectiveTime: visitorBloc.effectiveTimeTimeStamp.toString(), - invalidTime: visitorBloc.expirationTimeTimeStamp.toString(), + effectiveTime: + visitorBloc.effectiveTimeTimeStamp.toString(), + invalidTime: + visitorBloc.expirationTimeTimeStamp.toString(), )); - } - else if (visitorBloc.usageFrequencySelected == 'One-Time' && - visitorBloc.accessTypeSelected == 'Offline Password') { + } else if (visitorBloc.usageFrequencySelected == + 'One-Time' && + visitorBloc.accessTypeSelected == + 'Offline Password') { visitorBloc.add(OfflineOneTimePasswordEvent( context: context, passwordName: visitorBloc.userNameController.text, email: visitorBloc.emailController.text, )); - } - else if (visitorBloc.usageFrequencySelected == 'Periodic' && - visitorBloc.accessTypeSelected == 'Offline Password') { + } else if (visitorBloc.usageFrequencySelected == + 'Periodic' && + visitorBloc.accessTypeSelected == + 'Offline Password') { visitorBloc.add(OfflineMultipleTimePasswordEvent( passwordName: visitorBloc.userNameController.text, email: visitorBloc.emailController.text, - effectiveTime: visitorBloc.effectiveTimeTimeStamp.toString(), - invalidTime: visitorBloc.expirationTimeTimeStamp.toString(), + effectiveTime: + visitorBloc.effectiveTimeTimeStamp.toString(), + invalidTime: + visitorBloc.expirationTimeTimeStamp.toString(), )); } }, diff --git a/lib/services/access_mang_api.dart b/lib/services/access_mang_api.dart index a780a12b..a10292c5 100644 --- a/lib/services/access_mang_api.dart +++ b/lib/services/access_mang_api.dart @@ -12,7 +12,8 @@ class AccessMangApi { void _validateEndpoints() { if (!ApiEndpoints.getDevices.contains('{projectId}')) { - throw Exception("Endpoint 'getDevices' must contain '{projectId}' placeholder."); + throw Exception( + "Endpoint 'getDevices' must contain '{projectId}' placeholder."); } } @@ -22,8 +23,8 @@ class AccessMangApi { path: ApiEndpoints.visitorPassword, showServerMessage: true, expectedResponseModel: (json) { - List jsonData = json['data'] ?? []; - List passwordList = jsonData.map((jsonItem) { + final List jsonData = json['data'] ?? []; + final passwordList = jsonData.map((jsonItem) { return PasswordModel.fromJson(jsonItem); }).toList(); return passwordList; @@ -46,8 +47,8 @@ class AccessMangApi { }, showServerMessage: true, expectedResponseModel: (json) { - List jsonData = json['data'] ?? []; - List deviceList = jsonData.map((jsonItem) { + final List jsonData = json['data'] ?? []; + final deviceList = jsonData.map((jsonItem) { return DeviceModel.fromJson(jsonItem); }).toList(); return deviceList; @@ -69,13 +70,13 @@ class AccessMangApi { final response = await HTTPService().post( path: ApiEndpoints.visitorPassword, body: jsonEncode({ - "email": email, - "passwordName": passwordName, - "password": password, - "devicesUuid": devicesUuid, - "effectiveTime": effectiveTime, - "invalidTime": invalidTime, - "operationType": "ONLINE_ONE_TIME", + 'email': email, + 'passwordName': passwordName, + 'password': password, + 'devicesUuid': devicesUuid, + 'effectiveTime': effectiveTime, + 'invalidTime': invalidTime, + 'operationType': 'ONLINE_ONE_TIME', }), showServerMessage: true, expectedResponseModel: (json) { @@ -93,17 +94,18 @@ class AccessMangApi { String? passwordName, List? scheduleList, List? devicesUuid}) async { - Map body = { - "email": email, - "devicesUuid": devicesUuid, - "passwordName": passwordName, - "password": password, - "effectiveTime": effectiveTime, - "invalidTime": invalidTime, - "operationType": "ONLINE_MULTIPLE_TIME", + final body = { + 'email': email, + 'devicesUuid': devicesUuid, + 'passwordName': passwordName, + 'password': password, + 'effectiveTime': effectiveTime, + 'invalidTime': invalidTime, + 'operationType': 'ONLINE_MULTIPLE_TIME', }; if (scheduleList != null) { - body["scheduleList"] = scheduleList.map((schedule) => schedule.toJson()).toList(); + body['scheduleList'] = + scheduleList.map((schedule) => schedule.toJson()).toList(); } final response = await HTTPService().post( path: ApiEndpoints.visitorPassword, @@ -123,10 +125,10 @@ class AccessMangApi { final response = await HTTPService().post( path: ApiEndpoints.visitorPassword, body: jsonEncode({ - "operationType": "OFFLINE_ONE_TIME", - "email": email, - "passwordName": passwordName, - "devicesUuid": devicesUuid + 'operationType': 'OFFLINE_ONE_TIME', + 'email': email, + 'passwordName': passwordName, + 'devicesUuid': devicesUuid }), showServerMessage: true, expectedResponseModel: (json) { @@ -145,12 +147,12 @@ class AccessMangApi { final response = await HTTPService().post( path: ApiEndpoints.visitorPassword, body: jsonEncode({ - "email": email, - "devicesUuid": devicesUuid, - "passwordName": passwordName, - "effectiveTime": effectiveTime, - "invalidTime": invalidTime, - "operationType": "OFFLINE_MULTIPLE_TIME", + 'email': email, + 'devicesUuid': devicesUuid, + 'passwordName': passwordName, + 'effectiveTime': effectiveTime, + 'invalidTime': invalidTime, + 'operationType': 'OFFLINE_MULTIPLE_TIME', }), showServerMessage: true, expectedResponseModel: (json) { diff --git a/lib/services/api/http_interceptor.dart b/lib/services/api/http_interceptor.dart index bef8d804..f6762daf 100644 --- a/lib/services/api/http_interceptor.dart +++ b/lib/services/api/http_interceptor.dart @@ -1,10 +1,10 @@ +import 'dart:async'; import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:syncrow_web/pages/auth/model/token.dart'; import 'package:syncrow_web/services/api/network_exception.dart'; -import 'dart:async'; import 'package:syncrow_web/utils/constants/api_const.dart'; import 'package:syncrow_web/utils/snack_bar.dart'; @@ -18,7 +18,8 @@ class HTTPInterceptor extends InterceptorsWrapper { ]; @override - void onResponse(Response response, ResponseInterceptorHandler handler) async { + Future onResponse( + Response response, ResponseInterceptorHandler handler) async { if (await validateResponse(response)) { super.onResponse(response, handler); } else { @@ -28,26 +29,27 @@ class HTTPInterceptor extends InterceptorsWrapper { } @override - void onRequest( + Future onRequest( RequestOptions options, RequestInterceptorHandler handler) async { - var storage = const FlutterSecureStorage(); - var token = await storage.read(key: Token.loginAccessTokenKey); + const storage = FlutterSecureStorage(); + final token = await storage.read(key: Token.loginAccessTokenKey); if (checkHeaderExclusionListOfAddedParameters(options.path)) { options.headers - .putIfAbsent(HttpHeaders.authorizationHeader, () => "Bearer $token"); + .putIfAbsent(HttpHeaders.authorizationHeader, () => 'Bearer $token'); } // options.headers['Authorization'] = 'Bearer ${'${token!}123'}'; super.onRequest(options, handler); } @override - void onError(DioException err, ErrorInterceptorHandler handler) async { - ServerFailure failure = ServerFailure.fromDioError(err); + Future onError( + DioException err, ErrorInterceptorHandler handler) async { + final failure = ServerFailure.fromDioError(err); if (failure.toString().isNotEmpty) { CustomSnackBar.displaySnackBar(failure.toString()); } - var storage = const FlutterSecureStorage(); - var token = await storage.read(key: Token.loginAccessTokenKey); + const storage = FlutterSecureStorage(); + final token = await storage.read(key: Token.loginAccessTokenKey); if (err.response?.statusCode == 401 && token != null) { // await AuthCubit.get(NavigationService.navigatorKey.currentContext!).logout(); } @@ -72,10 +74,10 @@ class HTTPInterceptor extends InterceptorsWrapper { } } - checkHeaderExclusionListOfAddedParameters(String path) { - bool shouldAddHeader = true; + bool checkHeaderExclusionListOfAddedParameters(String path) { + var shouldAddHeader = true; - for (var urlConstant in headerExclusionListOfAddedParameters) { + for (final urlConstant in headerExclusionListOfAddedParameters) { if (path.contains(urlConstant)) { shouldAddHeader = false; } diff --git a/lib/services/api/http_service.dart b/lib/services/api/http_service.dart index c76291bf..8e0d0616 100644 --- a/lib/services/api/http_service.dart +++ b/lib/services/api/http_service.dart @@ -8,10 +8,10 @@ class HTTPService { // final navigatorKey = GlobalKey(); - String certificateString = ""; + String certificateString = ''; static Dio setupDioClient() { - Dio client = Dio( + final client = Dio( BaseOptions( baseUrl: ApiEndpoints.baseUrl, receiveDataWhenStatusError: true, diff --git a/lib/services/api/network_exception.dart b/lib/services/api/network_exception.dart index d85ef27c..9ebc8486 100644 --- a/lib/services/api/network_exception.dart +++ b/lib/services/api/network_exception.dart @@ -17,34 +17,34 @@ class ServerFailure extends Failure { factory ServerFailure.fromDioError(DioException dioError) { switch (dioError.type) { case DioExceptionType.connectionTimeout: - return ServerFailure("Connection timeout with the Server."); + return ServerFailure('Connection timeout with the Server.'); case DioExceptionType.sendTimeout: - return ServerFailure("Send timeout with the Server."); + return ServerFailure('Send timeout with the Server.'); case DioExceptionType.receiveTimeout: - return ServerFailure("Receive timeout with the Server."); + return ServerFailure('Receive timeout with the Server.'); case DioExceptionType.badCertificate: - return ServerFailure("Bad certificate!"); + return ServerFailure('Bad certificate!'); case DioExceptionType.badResponse: { // var document = parser.parse(dioError.response!.data.toString()); // var message = document.body!.text; - return ServerFailure.fromResponse(dioError.response!.statusCode!, - dioError.response?.data['message'] ?? "Error"); + return ServerFailure.fromResponse(dioError.response!.statusCode, + dioError.response?.data['message'] ?? 'Error'); } case DioExceptionType.cancel: - return ServerFailure("The request to ApiServer was canceled"); + return ServerFailure('The request to ApiServer was canceled'); case DioExceptionType.connectionError: - return ServerFailure("No Internet Connection"); + return ServerFailure('No Internet Connection'); case DioExceptionType.unknown: - return ServerFailure("Unexpected Error, Please try again!"); + return ServerFailure('Unexpected Error, Please try again!'); default: - return ServerFailure("Unexpected Error, Please try again!"); + return ServerFailure('Unexpected Error, Please try again!'); } } @@ -54,9 +54,9 @@ class ServerFailure extends Failure { case 403: return ServerFailure(responseMessage); case 400: - List errors = []; + final errors = []; if (responseMessage is List) { - for (var error in responseMessage) { + for (final error in responseMessage) { errors.add(error); } } else { @@ -64,11 +64,11 @@ class ServerFailure extends Failure { } return ServerFailure(errors.join('\n')); case 404: - return ServerFailure(""); + return ServerFailure(''); case 500: return ServerFailure(responseMessage); default: - return ServerFailure("Opps there was an Error, Please try again!"); + return ServerFailure('Opps there was an Error, Please try again!'); } } } diff --git a/lib/services/auth_api.dart b/lib/services/auth_api.dart index 18d951c1..ad4fec5f 100644 --- a/lib/services/auth_api.dart +++ b/lib/services/auth_api.dart @@ -31,7 +31,7 @@ class AuthenticationAPI { try { final response = await HTTPService().post( path: ApiEndpoints.forgetPassword, - body: {"email": email, "password": password, "otpCode": otpCode}, + body: {'email': email, 'password': password, 'otpCode': otpCode}, showServerMessage: true, expectedResponseModel: (json) {}); return response; @@ -45,7 +45,7 @@ class AuthenticationAPI { static Future sendOtp({required String email}) async { final response = await HTTPService().post( path: ApiEndpoints.sendOtp, - body: {"email": email, "type": "PASSWORD"}, + body: {'email': email, 'type': 'PASSWORD'}, showServerMessage: true, expectedResponseModel: (json) { return json['data']['cooldown']; @@ -58,7 +58,7 @@ class AuthenticationAPI { try { final response = await HTTPService().post( path: ApiEndpoints.verifyOtp, - body: {"email": email, "type": "PASSWORD", "otpCode": otpCode}, + body: {'email': email, 'type': 'PASSWORD', 'otpCode': otpCode}, showServerMessage: true, expectedResponseModel: (json) { if (json['message'] == 'Otp Verified Successfully') { diff --git a/lib/services/batch_control_devices_service.dart b/lib/services/batch_control_devices_service.dart index f78cdef4..16542c8c 100644 --- a/lib/services/batch_control_devices_service.dart +++ b/lib/services/batch_control_devices_service.dart @@ -11,7 +11,8 @@ abstract interface class BatchControlDevicesService { }); } -final class RemoteBatchControlDevicesService implements BatchControlDevicesService { +final class RemoteBatchControlDevicesService + implements BatchControlDevicesService { @override Future batchControlDevices({ required List uuids, diff --git a/lib/services/devices_mang_api.dart b/lib/services/devices_mang_api.dart index 6f60e34f..06fe635c 100644 --- a/lib/services/devices_mang_api.dart +++ b/lib/services/devices_mang_api.dart @@ -23,8 +23,8 @@ class DevicesManagementApi { : ApiEndpoints.getAllDevices.replaceAll('{projectId}', projectId), showServerMessage: true, expectedResponseModel: (json) { - List jsonData = json['data']; - List devicesList = jsonData.map((jsonItem) { + final List jsonData = json['data']; + final devicesList = jsonData.map((jsonItem) { return AllDevicesModel.fromJson(jsonItem); }).toList(); return devicesList; @@ -123,11 +123,11 @@ class DevicesManagementApi { path: ApiEndpoints.gatewayApi.replaceAll('{gatewayUuid}', gatewayId), showServerMessage: false, expectedResponseModel: (json) { - List devices = []; + final devices = []; if (json == null || json.isEmpty || json == []) { return devices; } - for (var device in json['data']['devices']) { + for (final device in json['data']['devices']) { devices.add(DeviceModel.fromJson(device)); } return devices; @@ -203,7 +203,7 @@ class DevicesManagementApi { } } - getPowerStatus(List uuids) async { + Future getPowerStatus(List uuids) async { try { final queryParameters = { 'devicesUuid': uuids.join(','), @@ -254,8 +254,8 @@ class DevicesManagementApi { .replaceAll('{category}', category), showServerMessage: true, expectedResponseModel: (json) { - List schedules = []; - for (var schedule in json) { + final schedules = []; + for (final schedule in json) { schedules.add(ScheduleModel.fromMap(schedule)); } return schedules; @@ -350,7 +350,7 @@ class DevicesManagementApi { try { final response = await HTTPService().put( path: ApiEndpoints.deviceByUuid.replaceAll('{deviceUuid}', deviceId), - body: {"deviceName": deviceName}, + body: {'deviceName': deviceName}, expectedResponseModel: (json) { return json['data']; }, @@ -378,7 +378,7 @@ class DevicesManagementApi { path: ApiEndpoints.resetDevice.replaceAll('{deviceUuid}', devicesUuid!), showServerMessage: false, body: { - "devicesUuid": [devicesUuid] + 'devicesUuid': [devicesUuid] }, expectedResponseModel: (json) { return json; diff --git a/lib/services/locator.dart b/lib/services/locator.dart index 055deb05..27f78ab9 100644 --- a/lib/services/locator.dart +++ b/lib/services/locator.dart @@ -5,7 +5,7 @@ import 'package:syncrow_web/services/api/http_service.dart'; final GetIt serviceLocator = GetIt.instance; //setupLocator() // to search for dependency injection in flutter -initialSetup() { +void initialSetup() { serviceLocator.registerSingleton(HTTPInterceptor()); //Base classes serviceLocator.registerSingleton(HTTPService.setupDioClient()); diff --git a/lib/services/product_api.dart b/lib/services/product_api.dart index 02c9f143..90dab310 100644 --- a/lib/services/product_api.dart +++ b/lib/services/product_api.dart @@ -9,9 +9,9 @@ class ProductApi { final response = await HTTPService().get( path: ApiEndpoints.listProducts, expectedResponseModel: (json) { - List jsonData = json['data']; + final List jsonData = json['data']; - List productList = jsonData.map((jsonItem) { + final productList = jsonData.map((jsonItem) { return ProductModel.fromMap(jsonItem); }).toList(); return productList; diff --git a/lib/services/routines_api.dart b/lib/services/routines_api.dart index bdc46ac1..f0d0b52a 100644 --- a/lib/services/routines_api.dart +++ b/lib/services/routines_api.dart @@ -29,7 +29,7 @@ class SceneApi { debugPrint('create scene response: $response'); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -52,7 +52,7 @@ class SceneApi { debugPrint('create automation response: $response'); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -63,7 +63,7 @@ class SceneApi { path: ApiEndpoints.getIconScene, showServerMessage: false, expectedResponseModel: (json) { - List iconsList = []; + final iconsList = []; json.forEach((element) { iconsList.add(IconModel.fromJson(element)); }); @@ -89,8 +89,8 @@ class SceneApi { expectedResponseModel: (json) { final scenesJson = json['data'] as List; - List scenes = []; - for (var scene in scenesJson) { + final scenes = []; + for (final scene in scenesJson) { scenes.add(ScenesModel.fromJson(scene, isAutomation: false)); } return scenes; @@ -114,8 +114,8 @@ class SceneApi { .replaceAll('{projectId}', projectId), showServerMessage: false, expectedResponseModel: (json) { - List scenes = []; - for (var scene in json) { + final scenes = []; + for (final scene in json) { scenes.add(ScenesModel.fromJson(scene, isAutomation: true)); } return scenes; @@ -158,7 +158,8 @@ class SceneApi { } //update Scene - static updateScene(CreateSceneModel createSceneModel, String sceneId) async { + static Future updateScene( + CreateSceneModel createSceneModel, String sceneId) async { try { final response = await _httpService.put( path: ApiEndpoints.updateScene.replaceAll('{sceneId}', sceneId), @@ -170,14 +171,14 @@ class SceneApi { ); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } } //update automation - static updateAutomation(CreateAutomationModel createAutomationModel, + static Future updateAutomation(CreateAutomationModel createAutomationModel, String automationId, String projectId) async { try { final response = await _httpService.put( @@ -192,7 +193,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -226,7 +227,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -247,7 +248,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - String errorMessage = + final String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -295,8 +296,8 @@ class SceneApi { .replaceAll('{projectId}', projectId), showServerMessage: false, expectedResponseModel: (json) { - List scenes = []; - for (var scene in json) { + final scenes = []; + for (final scene in json) { scenes.add(ScenesModel.fromJson(scene)); } return scenes; diff --git a/lib/services/space_mana_api.dart b/lib/services/space_mana_api.dart index 14902bca..901d623f 100644 --- a/lib/services/space_mana_api.dart +++ b/lib/services/space_mana_api.dart @@ -5,22 +5,19 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_m import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_response_model.dart'; +import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_body_model.dart'; -import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart'; import 'package:syncrow_web/services/api/http_service.dart'; import 'package:syncrow_web/utils/constants/api_const.dart'; -import '../pages/spaces_management/all_spaces/model/subspace_model.dart'; - class CommunitySpaceManagementApi { // Community Management APIs Future> fetchCommunities(String projectId, {int page = 1}) async { try { - List allCommunities = []; - bool hasNext = true; + final allCommunities = []; + var hasNext = true; while (hasNext) { await HTTPService().get( @@ -31,10 +28,10 @@ class CommunitySpaceManagementApi { }, expectedResponseModel: (json) { try { - List jsonData = json['data'] ?? []; + final List jsonData = json['data'] ?? []; hasNext = json['hasNext'] ?? false; - int currentPage = json['page'] ?? 1; - List communityList = jsonData.map((jsonItem) { + final int currentPage = json['page'] ?? 1; + final communityList = jsonData.map((jsonItem) { return CommunityModel.fromJson(jsonItem); }).toList(); allCommunities.addAll(communityList); @@ -56,10 +53,10 @@ class CommunitySpaceManagementApi { Future fetchCommunitiesAndSpaces( {required String projectId, int page = 1, String search = ''}) async { - PaginationModel paginationModel = const PaginationModel.emptyConstructor(); + var paginationModel = const PaginationModel.emptyConstructor(); try { - bool hasNext = false; + var hasNext = false; await HTTPService().get( path: ApiEndpoints.getCommunityList.replaceAll('{projectId}', projectId), @@ -71,10 +68,10 @@ class CommunitySpaceManagementApi { }, expectedResponseModel: (json) { try { - List jsonData = json['data'] ?? []; + final List jsonData = json['data'] ?? []; hasNext = json['hasNext'] ?? false; - int currentPage = json['page'] ?? 1; - List communityList = jsonData.map((jsonItem) { + final int currentPage = json['page'] ?? 1; + final communityList = jsonData.map((jsonItem) { return CommunityModel.fromJson(jsonItem); }).toList(); @@ -379,12 +376,12 @@ class CommunitySpaceManagementApi { final response = await HTTPService().get( path: path, - queryParameters: {"page": 1, "pageSize": 10}, + queryParameters: {'page': 1, 'pageSize': 10}, showServerMessage: false, expectedResponseModel: (json) { - List rooms = []; + final rooms = []; if (json['data'] != null) { - for (var subspace in json['data']) { + for (final subspace in json['data']) { rooms.add(SubSpaceModel.fromJson(subspace)); } } @@ -393,7 +390,7 @@ class CommunitySpaceManagementApi { ); return response; - } catch (error, stackTrace) { + } catch (error) { return []; } } diff --git a/lib/services/space_model_mang_api.dart b/lib/services/space_model_mang_api.dart index cbb9cfeb..c6fff07d 100644 --- a/lib/services/space_model_mang_api.dart +++ b/lib/services/space_model_mang_api.dart @@ -79,7 +79,7 @@ class SpaceModelManagementApi { .replaceAll('{projectId}', projectId) .replaceAll('{spaceModelUuid}', spaceModelUuid), showServerMessage: true, - body: {"spaceUuids": spaceUuids, "overwrite": isOverWrite}, + body: {'spaceUuids': spaceUuids, 'overwrite': isOverWrite}, expectedResponseModel: (json) { return json; }, @@ -92,7 +92,7 @@ class SpaceModelManagementApi { path: ApiEndpoints.validateSpaceModel .replaceAll('{projectId}', projectId), showServerMessage: true, - body: {"spacesUuids": spaceUuids}, + body: {'spacesUuids': spaceUuids}, expectedResponseModel: (json) { return json; }); @@ -116,7 +116,7 @@ class SpaceModelManagementApi { final response = await HTTPService().get( path: ApiEndpoints.listTags.replaceAll('{projectId}', projectId), expectedResponseModel: (json) { - List jsonData = json['data']; + final List jsonData = json['data']; return jsonData.map((jsonItem) { return Tag.fromJson(jsonItem); }).toList(); diff --git a/lib/services/user_permission.dart b/lib/services/user_permission.dart index 3f02663d..881f92df 100644 --- a/lib/services/user_permission.dart +++ b/lib/services/user_permission.dart @@ -23,18 +23,18 @@ class UserPermissionApi { }, ); return response; - } catch (e, stackTrace) { + } catch (e) { debugPrint('Error in fetchUsers: $e'); rethrow; } } - fetchRoles() async { + Future> fetchRoles() async { final response = await _httpService.get( path: ApiEndpoints.roleTypes, showServerMessage: true, expectedResponseModel: (json) { - final List fetchedRoles = (json['data'] as List) + final fetchedRoles = (json['data'] as List) .map((item) => RoleTypeModel.fromJson(item)) .toList(); return fetchedRoles; @@ -45,7 +45,7 @@ class UserPermissionApi { Future> fetchPermission(roleUuid) async { final response = await _httpService.get( - path: ApiEndpoints.permission.replaceAll("roleUuid", roleUuid), + path: ApiEndpoints.permission.replaceAll('roleUuid', roleUuid), showServerMessage: true, expectedResponseModel: (json) { return (json as List) @@ -68,14 +68,14 @@ class UserPermissionApi { }) async { try { final body = { - "firstName": firstName, - "lastName": lastName, - "email": email, - "jobTitle": jobTitle != '' ? jobTitle : null, - "phoneNumber": phoneNumber != '' ? phoneNumber : null, - "roleUuid": roleUuid, - "projectUuid": projectUuid, - "spaceUuids": spaceUuids, + 'firstName': firstName, + 'lastName': lastName, + 'email': email, + 'jobTitle': jobTitle != '' ? jobTitle : null, + 'phoneNumber': phoneNumber != '' ? phoneNumber : null, + 'roleUuid': roleUuid, + 'projectUuid': projectUuid, + 'spaceUuids': spaceUuids, }; final response = await _httpService.post( path: ApiEndpoints.inviteUser, @@ -83,7 +83,7 @@ class UserPermissionApi { body: jsonEncode(body), expectedResponseModel: (json) { if (json['statusCode'] != 400) { - return json["success"]; + return json['success']; } else { return false; } @@ -91,7 +91,7 @@ class UserPermissionApi { ); return response ?? []; - } on DioException catch (e) { + } on DioException { return false; } catch (e) { return false; @@ -103,10 +103,10 @@ class UserPermissionApi { final response = await _httpService.post( path: ApiEndpoints.checkEmail, showServerMessage: true, - body: {"email": email}, + body: {'email': email}, expectedResponseModel: (json) { if (json['statusCode'] != 400) { - var message = json["message"]; + final message = json['message']; if (message is String) { return message; } else { @@ -128,11 +128,11 @@ class UserPermissionApi { Future fetchUserById(userUuid, String projectId) async { final response = await _httpService.get( path: ApiEndpoints.getUserById - .replaceAll("{userUuid}", userUuid) - .replaceAll("{projectId}", projectId), + .replaceAll('{userUuid}', userUuid) + .replaceAll('{projectId}', projectId), showServerMessage: true, expectedResponseModel: (json) { - EditUserModel res = EditUserModel.fromJson(json['data']); + final res = EditUserModel.fromJson(json['data']); return res; }, ); @@ -151,27 +151,27 @@ class UserPermissionApi { }) async { try { final body = { - "firstName": firstName, - "lastName": lastName, - "jobTitle": jobTitle != '' ? jobTitle : " ", - "phoneNumber": phoneNumber != '' ? phoneNumber : " ", - "roleUuid": roleUuid, - "projectUuid": projectUuid, - "spaceUuids": spaceUuids, + 'firstName': firstName, + 'lastName': lastName, + 'jobTitle': jobTitle != '' ? jobTitle : ' ', + 'phoneNumber': phoneNumber != '' ? phoneNumber : ' ', + 'roleUuid': roleUuid, + 'projectUuid': projectUuid, + 'spaceUuids': spaceUuids, }; final response = await _httpService.put( path: ApiEndpoints.editUser.replaceAll('{inviteUserUuid}', userId!), body: jsonEncode(body), expectedResponseModel: (json) { if (json['statusCode'] != 400) { - return json["success"]; + return json['success']; } else { return false; } }, ); return response; - } on DioException catch (e) { + } on DioException { return false; } catch (e) { return false; @@ -181,7 +181,7 @@ class UserPermissionApi { Future deleteUserById(userUuid) async { try { final response = await _httpService.delete( - path: ApiEndpoints.deleteUser.replaceAll("{inviteUserUuid}", userUuid), + path: ApiEndpoints.deleteUser.replaceAll('{inviteUserUuid}', userUuid), showServerMessage: true, expectedResponseModel: (json) { return json['success']; @@ -193,16 +193,17 @@ class UserPermissionApi { } } - Future changeUserStatusById(userUuid, status, String projectUuid) async { + Future changeUserStatusById( + userUuid, status, String projectUuid) async { try { - Map bodya = { - "disable": status, - "projectUuid": projectUuid + final bodya = { + 'disable': status, + 'projectUuid': projectUuid }; final response = await _httpService.put( path: ApiEndpoints.changeUserStatus - .replaceAll("{invitedUserUuid}", userUuid), + .replaceAll('{invitedUserUuid}', userUuid), body: bodya, expectedResponseModel: (json) { return json['success']; diff --git a/lib/utils/color_manager.dart b/lib/utils/color_manager.dart index 50170ed9..2b164590 100644 --- a/lib/utils/color_manager.dart +++ b/lib/utils/color_manager.dart @@ -6,15 +6,15 @@ abstract class ColorsManager { static const Color primaryColor = Color(0xFF0030CB); //023DFE static const Color secondaryTextColor = Color(0xFF848484); static Color primaryColorWithOpacity = - const Color(0xFF023DFE).withOpacity(0.6); + const Color(0xFF023DFE).withValues(alpha: 0.6); static const Color whiteColors = Colors.white; - static Color whiteColorsWithOpacity = Colors.white.withOpacity(0.6); + static Color whiteColorsWithOpacity = Colors.white.withValues(alpha: 0.6); static const Color secondaryColor = Color(0xFF023DFE); static const Color onSecondaryColor = Color(0xFF023DFE); - static Color shadowBlackColor = Colors.black.withOpacity(0.2); + static Color shadowBlackColor = Colors.black.withValues(alpha: 0.2); - static Color dialogBlueTitle = const Color(0xFF023DFE).withOpacity(0.6); + static Color dialogBlueTitle = const Color(0xFF023DFE).withValues(alpha: 0.6); static const Color primaryTextColor = Colors.black; @@ -83,7 +83,5 @@ abstract class ColorsManager { static const Color maxPurpleDot = Color(0xFF5F00BD); static const Color minBlue = Color(0xFF93AAFD); static const Color minBlueDot = Color(0xFF023DFE); - static const Color grey25 = Color(0xFFF9F9F9); - - + static const Color grey25 = Color(0xFFF9F9F9); } diff --git a/lib/utils/constants/api_const.dart b/lib/utils/constants/api_const.dart index 411e72a5..bfdb729d 100644 --- a/lib/utils/constants/api_const.dart +++ b/lib/utils/constants/api_const.dart @@ -1,7 +1,7 @@ import 'package:flutter_dotenv/flutter_dotenv.dart'; abstract class ApiEndpoints { - static const String projectUuid = "0e62577c-06fa-41b9-8a92-99a21fbaf51c"; + static const String projectUuid = '0e62577c-06fa-41b9-8a92-99a21fbaf51c'; static String baseUrl = dotenv.env['BASE_URL'] ?? ''; static const String signUp = '/authentication/user/signup'; static const String login = '/authentication/user/login'; diff --git a/lib/utils/constants/app_enum.dart b/lib/utils/constants/app_enum.dart index d603c3ea..ec5aeb2d 100644 --- a/lib/utils/constants/app_enum.dart +++ b/lib/utils/constants/app_enum.dart @@ -9,28 +9,28 @@ extension AccessTypeExtension on AccessType { String get value { switch (this) { case AccessType.onlineOnetime: - return "Online Password"; + return 'Online Password'; case AccessType.onlineMultiple: - return "online Multiple Password"; + return 'online Multiple Password'; case AccessType.offlineOnetime: - return "Offline Onetime Password"; + return 'Offline Onetime Password'; case AccessType.offlineMultiple: - return "Offline Multiple Password"; + return 'Offline Multiple Password'; } } static AccessType fromString(String value) { switch (value) { - case "ONLINE_ONETIME": + case 'ONLINE_ONETIME': return AccessType.onlineOnetime; - case "ONLINE_MULTIPLE": + case 'ONLINE_MULTIPLE': return AccessType.onlineMultiple; - case "OFFLINE_ONETIME": + case 'OFFLINE_ONETIME': return AccessType.offlineOnetime; - case "OFFLINE_MULTIPLE": + case 'OFFLINE_MULTIPLE': return AccessType.offlineMultiple; default: - throw ArgumentError("Invalid access type: $value"); + throw ArgumentError('Invalid access type: $value'); } } } @@ -44,9 +44,9 @@ extension OnlineTypeExtension on DeviseStatus { String get value { switch (this) { case DeviseStatus.online: - return "Online"; + return 'Online'; case DeviseStatus.offline: - return "Offline"; + return 'Offline'; } } @@ -57,7 +57,7 @@ extension OnlineTypeExtension on DeviseStatus { case true: return DeviseStatus.online; default: - throw ArgumentError("Invalid access type: $value"); + throw ArgumentError('Invalid access type: $value'); } } } @@ -72,24 +72,24 @@ extension AccessStatusExtension on AccessStatus { String get value { switch (this) { case AccessStatus.expired: - return "Expired"; + return 'Expired'; case AccessStatus.effective: - return "Effective"; + return 'Effective'; case AccessStatus.toBeEffective: - return "To be effective"; + return 'To be effective'; } } static AccessStatus fromString(String value) { switch (value) { - case "EXPIRED": + case 'EXPIRED': return AccessStatus.expired; - case "EFFECTIVE": + case 'EFFECTIVE': return AccessStatus.effective; - case "TO_BE_EFFECTIVE": + case 'TO_BE_EFFECTIVE': return AccessStatus.toBeEffective; default: - throw ArgumentError("Invalid access type: $value"); + throw ArgumentError('Invalid access type: $value'); } } } diff --git a/lib/utils/constants/assets.dart b/lib/utils/constants/assets.dart index dfc0b394..5f030841 100644 --- a/lib/utils/constants/assets.dart +++ b/lib/utils/constants/assets.dart @@ -1,138 +1,138 @@ class Assets { Assets._(); - static const String background = "assets/images/Background.png"; - static const String webBackground = "assets/images/web_Background.svg"; - static const String webBackgroundPng = "assets/images/web_Background.png"; - static const String blackLogo = "assets/images/black-logo.png"; - static const String logo = "assets/images/Logo.svg"; - static const String logoHorizontal = "assets/images/logo_horizontal.png"; - static const String vector = "assets/images/Vector.png"; - static const String loginLogo = "assets/images/login_logo.svg"; - static const String whiteLogo = "assets/images/white-logo.png"; - static const String window = "assets/images/Window.png"; - static const String liftLine = "assets/images/lift_line.png"; - static const String rightLine = "assets/images/right_line.png"; - static const String google = "assets/images/google.svg"; - static const String facebook = "assets/images/facebook.svg"; + static const String background = 'assets/images/Background.png'; + static const String webBackground = 'assets/images/web_Background.svg'; + static const String webBackgroundPng = 'assets/images/web_Background.png'; + static const String blackLogo = 'assets/images/black-logo.png'; + static const String logo = 'assets/images/Logo.svg'; + static const String logoHorizontal = 'assets/images/logo_horizontal.png'; + static const String vector = 'assets/images/Vector.png'; + static const String loginLogo = 'assets/images/login_logo.svg'; + static const String whiteLogo = 'assets/images/white-logo.png'; + static const String window = 'assets/images/Window.png'; + static const String liftLine = 'assets/images/lift_line.png'; + static const String rightLine = 'assets/images/right_line.png'; + static const String google = 'assets/images/google.svg'; + static const String facebook = 'assets/images/facebook.svg'; static const String invisiblePassword = - "assets/images/Password_invisible.svg"; - static const String visiblePassword = "assets/images/password_visible.svg"; - static const String accessIcon = "assets/images/access_icon.svg"; + 'assets/images/Password_invisible.svg'; + static const String visiblePassword = 'assets/images/password_visible.svg'; + static const String accessIcon = 'assets/images/access_icon.svg'; static const String spaseManagementIcon = - "assets/images/spase_management_icon.svg"; - static const String devicesIcon = "assets/images/devices_icon.svg"; - static const String analyticsIcon = "assets/icons/landing_analytics.svg"; + 'assets/images/spase_management_icon.svg'; + static const String devicesIcon = 'assets/images/devices_icon.svg'; + static const String analyticsIcon = 'assets/icons/landing_analytics.svg'; - static const String moveinIcon = "assets/images/movein_icon.svg"; - static const String constructionIcon = "assets/images/construction_icon.svg"; - static const String energyIcon = "assets/images/energy_icon.svg"; - static const String integrationsIcon = "assets/images/Integrations_icon.svg"; - static const String assetIcon = "assets/images/asset_icon.svg"; - static const String calendarIcon = "assets/images/calendar_icon.svg"; - static const String deviceNoteIcon = "assets/images/device_note.svg"; - static const String timeIcon = "assets/images/time_icon.svg"; - static const String emptyTable = "assets/images/empty_table.svg"; + static const String moveinIcon = 'assets/images/movein_icon.svg'; + static const String constructionIcon = 'assets/images/construction_icon.svg'; + static const String energyIcon = 'assets/images/energy_icon.svg'; + static const String integrationsIcon = 'assets/images/Integrations_icon.svg'; + static const String assetIcon = 'assets/images/asset_icon.svg'; + static const String calendarIcon = 'assets/images/calendar_icon.svg'; + static const String deviceNoteIcon = 'assets/images/device_note.svg'; + static const String timeIcon = 'assets/images/time_icon.svg'; + static const String emptyTable = 'assets/images/empty_table.svg'; // General assets static const String motionlessDetection = - "assets/icons/motionless_detection.svg"; - static const String acHeating = "assets/icons/ac_heating.svg"; - static const String acPowerOff = "assets/icons/ac_power_off.svg"; - static const String acFanMiddle = "assets/icons/ac_fan_middle.svg"; - static const String switchAlarmSound = "assets/icons/switch_alarm_sound.svg"; - static const String resetOff = "assets/icons/reset_off.svg"; + 'assets/icons/motionless_detection.svg'; + static const String acHeating = 'assets/icons/ac_heating.svg'; + static const String acPowerOff = 'assets/icons/ac_power_off.svg'; + static const String acFanMiddle = 'assets/icons/ac_fan_middle.svg'; + static const String switchAlarmSound = 'assets/icons/switch_alarm_sound.svg'; + static const String resetOff = 'assets/icons/reset_off.svg'; static const String sensitivityOperationIcon = - "assets/icons/sesitivity_operation_icon.svg"; - static const String motionDetection = "assets/icons/motion_detection.svg"; - static const String freezing = "assets/icons/freezing.svg"; - static const String indicator = "assets/icons/indicator.svg"; - static const String sceneRefresh = "assets/icons/scene_refresh.svg"; - static const String temperature = "assets/icons/tempreture.svg"; - static const String acFanHigh = "assets/icons/ac_fan_high.svg"; - static const String fanSpeed = "assets/icons/fan_speed.svg"; - static const String acFanLow = "assets/icons/ac_fan_low.svg"; - static const String sensitivity = "assets/icons/sensitivity.svg"; - static const String lightCountdown = "assets/icons/light_countdown.svg"; - static const String farDetection = "assets/icons/far_detection.svg"; - static const String sceneChildUnlock = "assets/icons/scene_child_unlock.svg"; - static const String acFanAuto = "assets/icons/ac_fan_auto.svg"; - static const String childLock = "assets/icons/child_lock.svg"; - static const String factoryReset = "assets/icons/factory_reset.svg"; - static const String acCooling = "assets/icons/ac_cooling.svg"; - static const String sceneChildLock = "assets/icons/scene_child_lock.svg"; - static const String celsiusDegrees = "assets/icons/celsius_degrees.svg"; - static const String masterState = "assets/icons/master_state.svg"; - static const String acPower = "assets/icons/ac_power.svg"; + 'assets/icons/sesitivity_operation_icon.svg'; + static const String motionDetection = 'assets/icons/motion_detection.svg'; + static const String freezing = 'assets/icons/freezing.svg'; + static const String indicator = 'assets/icons/indicator.svg'; + static const String sceneRefresh = 'assets/icons/scene_refresh.svg'; + static const String temperature = 'assets/icons/tempreture.svg'; + static const String acFanHigh = 'assets/icons/ac_fan_high.svg'; + static const String fanSpeed = 'assets/icons/fan_speed.svg'; + static const String acFanLow = 'assets/icons/ac_fan_low.svg'; + static const String sensitivity = 'assets/icons/sensitivity.svg'; + static const String lightCountdown = 'assets/icons/light_countdown.svg'; + static const String farDetection = 'assets/icons/far_detection.svg'; + static const String sceneChildUnlock = 'assets/icons/scene_child_unlock.svg'; + static const String acFanAuto = 'assets/icons/ac_fan_auto.svg'; + static const String childLock = 'assets/icons/child_lock.svg'; + static const String factoryReset = 'assets/icons/factory_reset.svg'; + static const String acCooling = 'assets/icons/ac_cooling.svg'; + static const String sceneChildLock = 'assets/icons/scene_child_lock.svg'; + static const String celsiusDegrees = 'assets/icons/celsius_degrees.svg'; + static const String masterState = 'assets/icons/master_state.svg'; + static const String acPower = 'assets/icons/ac_power.svg'; static const String farDetectionFunction = - "assets/icons/far_detection_function.svg"; - static const String nobodyTime = "assets/icons/nobody_time.svg"; + 'assets/icons/far_detection_function.svg'; + static const String nobodyTime = 'assets/icons/nobody_time.svg'; // Automation functions static const String tempPasswordUnlock = - "assets/icons/automation_functions/temp_password_unlock.svg"; + 'assets/icons/automation_functions/temp_password_unlock.svg'; static const String doorlockNormalOpen = - "assets/icons/automation_functions/doorlock_normal_open.svg"; + 'assets/icons/automation_functions/doorlock_normal_open.svg'; static const String doorbell = - "assets/icons/automation_functions/doorbell.svg"; + 'assets/icons/automation_functions/doorbell.svg'; static const String remoteUnlockViaApp = - "assets/icons/automation_functions/remote_unlock_via_app.svg"; + 'assets/icons/automation_functions/remote_unlock_via_app.svg'; static const String doubleLock = - "assets/icons/automation_functions/double_lock.svg"; + 'assets/icons/automation_functions/double_lock.svg'; static const String selfTestResult = - "assets/icons/automation_functions/self_test_result.svg"; + 'assets/icons/automation_functions/self_test_result.svg'; static const String lockAlarm = - "assets/icons/automation_functions/lock_alarm.svg"; + 'assets/icons/automation_functions/lock_alarm.svg'; static const String presenceState = - "assets/icons/automation_functions/presence_state.svg"; + 'assets/icons/automation_functions/presence_state.svg'; static const String currentTemp = - "assets/icons/automation_functions/current_temp.svg"; + 'assets/icons/automation_functions/current_temp.svg'; static const String presence = - "assets/icons/automation_functions/presence.svg"; + 'assets/icons/automation_functions/presence.svg'; static const String residualElectricity = - "assets/icons/automation_functions/residual_electricity.svg"; + 'assets/icons/automation_functions/residual_electricity.svg'; static const String hijackAlarm = - "assets/icons/automation_functions/hijack_alarm.svg"; + 'assets/icons/automation_functions/hijack_alarm.svg'; static const String passwordUnlock = - "assets/icons/automation_functions/password_unlock.svg"; + 'assets/icons/automation_functions/password_unlock.svg'; static const String remoteUnlockRequest = - "assets/icons/automation_functions/remote_unlock_req.svg"; + 'assets/icons/automation_functions/remote_unlock_req.svg'; static const String cardUnlock = - "assets/icons/automation_functions/card_unlock.svg"; - static const String motion = "assets/icons/automation_functions/motion.svg"; + 'assets/icons/automation_functions/card_unlock.svg'; + static const String motion = 'assets/icons/automation_functions/motion.svg'; static const String fingerprintUnlock = - "assets/icons/automation_functions/fingerprint_unlock.svg"; + 'assets/icons/automation_functions/fingerprint_unlock.svg'; // Presence Sensor Assets - static const String sensorMotionIcon = "assets/icons/sensor_motion_ic.svg"; + static const String sensorMotionIcon = 'assets/icons/sensor_motion_ic.svg'; static const String sensorPresenceIcon = - "assets/icons/sensor_presence_ic.svg"; - static const String sensorVacantIcon = "assets/icons/sensor_vacant_ic.svg"; + 'assets/icons/sensor_presence_ic.svg'; + static const String sensorVacantIcon = 'assets/icons/sensor_vacant_ic.svg'; static const String illuminanceRecordIcon = - "assets/icons/illuminance_record_ic.svg"; + 'assets/icons/illuminance_record_ic.svg'; static const String presenceRecordIcon = - "assets/icons/presence_record_ic.svg"; + 'assets/icons/presence_record_ic.svg'; static const String helpDescriptionIcon = - "assets/icons/help_description_ic.svg"; + 'assets/icons/help_description_ic.svg'; - static const String lightPulp = "assets/icons/light_pulb.svg"; - static const String acDevice = "assets/icons/ac_device.svg"; - static const String acAirConditioner = "assets/icons/ac_air.svg"; - static const String acSun = "assets/icons/ac_sun.svg"; + static const String lightPulp = 'assets/icons/light_pulb.svg'; + static const String acDevice = 'assets/icons/ac_device.svg'; + static const String acAirConditioner = 'assets/icons/ac_air.svg'; + static const String acSun = 'assets/icons/ac_sun.svg'; //assets/icons/3GangSwitch.svg - static const String gangSwitch = "assets/icons/3GangSwitch.svg"; + static const String gangSwitch = 'assets/icons/3GangSwitch.svg'; //assets/icons/AC.svg - static const String ac = "assets/icons/AC.svg"; + static const String ac = 'assets/icons/AC.svg'; //assets/icons/Curtain.svg - static const String curtain = "assets/icons/Curtain.svg"; + static const String curtain = 'assets/icons/Curtain.svg'; //assets/icons/doorLock.svg - static const String doorLock = "assets/icons/doorLock.svg"; + static const String doorLock = 'assets/icons/doorLock.svg'; //assets/icons/Gateway.svg - static const String gateway = "assets/icons/Gateway.svg"; + static const String gateway = 'assets/icons/Gateway.svg'; //assets/icons/Light.svg - static const String lightBulb = "assets/icons/Light.svg"; + static const String lightBulb = 'assets/icons/Light.svg'; //assets/icons/sensors.svg - static const String sensors = "assets/icons/sensors.svg"; + static const String sensors = 'assets/icons/sensors.svg'; //assets/icons/door_un_look_ic.svg static const String doorUnlock = 'assets/icons/door_un_look_ic.svg'; @@ -175,7 +175,7 @@ class Assets { static const String Gang1SwitchIcon = 'assets/icons/1_Gang_switch_icon.svg'; static const String DoorLockIcon = 'assets/icons/door_lock.svg'; static const String SmartGatewayIcon = 'assets/icons/smart_gateway_icon.svg'; - static const String curtainIcon = "assets/images/curtain.svg"; + static const String curtainIcon = 'assets/images/curtain.svg'; static const String unlock = 'assets/icons/unlock_ic.svg'; static const String firmware = 'assets/icons/firmware.svg'; //assets/images/scheduling.svg @@ -227,12 +227,12 @@ class Assets { //assets/icons/2gang.svg static const String twoGang = 'assets/icons/2gang.svg'; - static const String frequencyIcon = "assets/icons/frequency_icon.svg"; - static const String voltMeterIcon = "assets/icons/volt_meter_icon.svg"; - static const String powerActiveIcon = "assets/icons/power_active_icon.svg"; - static const String searchIcon = "assets/icons/search_icon.svg"; - static const String voltageIcon = "assets/icons/voltage_icon.svg"; - static const String speedoMeter = "assets/icons/speedo_meter.svg"; + static const String frequencyIcon = 'assets/icons/frequency_icon.svg'; + static const String voltMeterIcon = 'assets/icons/volt_meter_icon.svg'; + static const String powerActiveIcon = 'assets/icons/power_active_icon.svg'; + static const String searchIcon = 'assets/icons/search_icon.svg'; + static const String voltageIcon = 'assets/icons/voltage_icon.svg'; + static const String speedoMeter = 'assets/icons/speedo_meter.svg'; //assets/icons/account_setting.svg static const String accountSetting = 'assets/icons/account_setting.svg'; @@ -284,99 +284,99 @@ class Assets { // Assets for functions_icons static const String assetsSensitivityFunction = - "assets/icons/functions_icons/sensitivity.svg"; + 'assets/icons/functions_icons/sensitivity.svg'; static const String assetsSensitivityOperationIcon = - "assets/icons/functions_icons/sesitivity_operation_icon.svg"; + 'assets/icons/functions_icons/sesitivity_operation_icon.svg'; static const String assetsAcPower = - "assets/icons/functions_icons/ac_power.svg"; + 'assets/icons/functions_icons/ac_power.svg'; static const String assetsAcPowerOFF = - "assets/icons/functions_icons/ac_power_off.svg"; + 'assets/icons/functions_icons/ac_power_off.svg'; static const String assetsChildLock = - "assets/icons/functions_icons/child_lock.svg"; + 'assets/icons/functions_icons/child_lock.svg'; static const String assetsFreezing = - "assets/icons/functions_icons/freezing.svg"; + 'assets/icons/functions_icons/freezing.svg'; static const String assetsFanSpeed = - "assets/icons/functions_icons/fan_speed.svg"; + 'assets/icons/functions_icons/fan_speed.svg'; static const String assetsAcCooling = - "assets/icons/functions_icons/ac_cooling.svg"; + 'assets/icons/functions_icons/ac_cooling.svg'; static const String assetsAcHeating = - "assets/icons/functions_icons/ac_heating.svg"; + 'assets/icons/functions_icons/ac_heating.svg'; static const String assetsCelsiusDegrees = - "assets/icons/functions_icons/celsius_degrees.svg"; + 'assets/icons/functions_icons/celsius_degrees.svg'; static const String assetsTempreture = - "assets/icons/functions_icons/tempreture.svg"; + 'assets/icons/functions_icons/tempreture.svg'; static const String assetsAcFanLow = - "assets/icons/functions_icons/ac_fan_low.svg"; + 'assets/icons/functions_icons/ac_fan_low.svg'; static const String assetsAcFanMiddle = - "assets/icons/functions_icons/ac_fan_middle.svg"; + 'assets/icons/functions_icons/ac_fan_middle.svg'; static const String assetsAcFanHigh = - "assets/icons/functions_icons/ac_fan_high.svg"; + 'assets/icons/functions_icons/ac_fan_high.svg'; static const String assetsAcFanAuto = - "assets/icons/functions_icons/ac_fan_auto.svg"; + 'assets/icons/functions_icons/ac_fan_auto.svg'; static const String assetsSceneChildLock = - "assets/icons/functions_icons/scene_child_lock.svg"; + 'assets/icons/functions_icons/scene_child_lock.svg'; static const String assetsSceneChildUnlock = - "assets/icons/functions_icons/scene_child_unlock.svg"; + 'assets/icons/functions_icons/scene_child_unlock.svg'; static const String assetsSceneRefresh = - "assets/icons/functions_icons/scene_refresh.svg"; + 'assets/icons/functions_icons/scene_refresh.svg'; static const String assetsLightCountdown = - "assets/icons/functions_icons/light_countdown.svg"; + 'assets/icons/functions_icons/light_countdown.svg'; static const String assetsFarDetection = - "assets/icons/functions_icons/far_detection.svg"; + 'assets/icons/functions_icons/far_detection.svg'; static const String assetsFarDetectionFunction = - "assets/icons/functions_icons/far_detection_function.svg"; + 'assets/icons/functions_icons/far_detection_function.svg'; static const String assetsIndicator = - "assets/icons/functions_icons/indicator.svg"; + 'assets/icons/functions_icons/indicator.svg'; static const String assetsMotionDetection = - "assets/icons/functions_icons/motion_detection.svg"; + 'assets/icons/functions_icons/motion_detection.svg'; static const String assetsMotionlessDetection = - "assets/icons/functions_icons/motionless_detection.svg"; + 'assets/icons/functions_icons/motionless_detection.svg'; static const String assetsNobodyTime = - "assets/icons/functions_icons/nobody_time.svg"; + 'assets/icons/functions_icons/nobody_time.svg'; static const String assetsFactoryReset = - "assets/icons/functions_icons/factory_reset.svg"; + 'assets/icons/functions_icons/factory_reset.svg'; static const String assetsMasterState = - "assets/icons/functions_icons/master_state.svg"; + 'assets/icons/functions_icons/master_state.svg'; static const String assetsSwitchAlarmSound = - "assets/icons/functions_icons/switch_alarm_sound.svg"; + 'assets/icons/functions_icons/switch_alarm_sound.svg'; static const String assetsResetOff = - "assets/icons/functions_icons/reset_off.svg"; + 'assets/icons/functions_icons/reset_off.svg'; // Assets for automation_functions static const String assetsCardUnlock = - "assets/icons/functions_icons/automation_functions/card_unlock.svg"; + 'assets/icons/functions_icons/automation_functions/card_unlock.svg'; static const String assetsDoorbell = - "assets/icons/functions_icons/automation_functions/doorbell.svg"; + 'assets/icons/functions_icons/automation_functions/doorbell.svg'; static const String assetsDoorlockNormalOpen = - "assets/icons/functions_icons/automation_functions/doorlock_normal_open.svg"; + 'assets/icons/functions_icons/automation_functions/doorlock_normal_open.svg'; static const String assetsDoubleLock = - "assets/icons/functions_icons/automation_functions/double_lock.svg"; + 'assets/icons/functions_icons/automation_functions/double_lock.svg'; static const String assetsFingerprintUnlock = - "assets/icons/functions_icons/automation_functions/fingerprint_unlock.svg"; + 'assets/icons/functions_icons/automation_functions/fingerprint_unlock.svg'; static const String assetsHijackAlarm = - "assets/icons/functions_icons/automation_functions/hijack_alarm.svg"; + 'assets/icons/functions_icons/automation_functions/hijack_alarm.svg'; static const String assetsLockAlarm = - "assets/icons/functions_icons/automation_functions/lock_alarm.svg"; + 'assets/icons/functions_icons/automation_functions/lock_alarm.svg'; static const String assetsPasswordUnlock = - "assets/icons/functions_icons/automation_functions/password_unlock.svg"; + 'assets/icons/functions_icons/automation_functions/password_unlock.svg'; static const String assetsRemoteUnlockReq = - "assets/icons/functions_icons/automation_functions/remote_unlock_req.svg"; + 'assets/icons/functions_icons/automation_functions/remote_unlock_req.svg'; static const String assetsRemoteUnlockViaApp = - "assets/icons/functions_icons/automation_functions/remote_unlock_via_app.svg"; + 'assets/icons/functions_icons/automation_functions/remote_unlock_via_app.svg'; static const String assetsResidualElectricity = - "assets/icons/functions_icons/automation_functions/residual_electricity.svg"; + 'assets/icons/functions_icons/automation_functions/residual_electricity.svg'; static const String assetsTempPasswordUnlock = - "assets/icons/functions_icons/automation_functions/temp_password_unlock.svg"; + 'assets/icons/functions_icons/automation_functions/temp_password_unlock.svg'; static const String assetsSelfTestResult = - "assets/icons/functions_icons/automation_functions/self_test_result.svg"; + 'assets/icons/functions_icons/automation_functions/self_test_result.svg'; static const String assetsPresence = - "assets/icons/functions_icons/automation_functions/presence.svg"; + 'assets/icons/functions_icons/automation_functions/presence.svg'; static const String assetsMotion = - "assets/icons/functions_icons/automation_functions/motion.svg"; + 'assets/icons/functions_icons/automation_functions/motion.svg'; static const String assetsCurrentTemp = - "assets/icons/functions_icons/automation_functions/current_temp.svg"; + 'assets/icons/functions_icons/automation_functions/current_temp.svg'; static const String assetsPresenceState = - "assets/icons/functions_icons/automation_functions/presence_state.svg"; + 'assets/icons/functions_icons/automation_functions/presence_state.svg'; //assets/icons/routine/automation.svg static const String automation = 'assets/icons/routine/automation.svg'; static const String searchIconUser = 'assets/icons/search_icon_user.svg'; diff --git a/lib/utils/constants/strings_manager.dart b/lib/utils/constants/strings_manager.dart index 2ea63fe4..3f70b347 100644 --- a/lib/utils/constants/strings_manager.dart +++ b/lib/utils/constants/strings_manager.dart @@ -22,13 +22,13 @@ class StringsManager { static const String on = 'ON'; static const String off = 'OFF'; static const String timer = 'Timer'; - static const String dimmerAndColor = "Dimmer & color"; - static const String recentlyUsed = "Recently used colors"; - static const String lightingModes = "Lighting modes"; - static const String doze = "Doze"; - static const String relax = "Relax"; - static const String reading = "Reading"; - static const String energizing = "Energizing"; + static const String dimmerAndColor = 'Dimmer & color'; + static const String recentlyUsed = 'Recently used colors'; + static const String lightingModes = 'Lighting modes'; + static const String doze = 'Doze'; + static const String relax = 'Relax'; + static const String reading = 'Reading'; + static const String energizing = 'Energizing'; static const String createScene = 'Create Scene'; static const String tapToRun = 'Launch: Tap - To - Run'; static const String turnOffAllLights = @@ -36,8 +36,8 @@ class StringsManager { static const String whenDeviceStatusChanges = 'When device status changes'; static const String whenUnusualActivityIsDetected = 'Example: when an unusual activity is detected.'; - static const String functions = "Functions"; - static const String firstLaunch = "firstLaunch"; + static const String functions = 'Functions'; + static const String firstLaunch = 'firstLaunch'; static const String deleteScene = 'Delete Scene'; static const String deleteAutomation = 'Delete Automation'; static const String projectKey = 'selected_project_uuid'; diff --git a/lib/utils/enum/device_types.dart b/lib/utils/enum/device_types.dart index 9bfd322f..0af5510b 100644 --- a/lib/utils/enum/device_types.dart +++ b/lib/utils/enum/device_types.dart @@ -43,20 +43,20 @@ enum DeviceType { */ Map devicesTypesMap = { - "AC": DeviceType.AC, - "GW": DeviceType.Gateway, - "CPS": DeviceType.CeilingSensor, - "DL": DeviceType.DoorLock, - "WPS": DeviceType.WallSensor, - "3G": DeviceType.ThreeGang, - "2G": DeviceType.TwoGang, - "1G": DeviceType.OneGang, - "CUR": DeviceType.Curtain, - "WH": DeviceType.WH, + 'AC': DeviceType.AC, + 'GW': DeviceType.Gateway, + 'CPS': DeviceType.CeilingSensor, + 'DL': DeviceType.DoorLock, + 'WPS': DeviceType.WallSensor, + '3G': DeviceType.ThreeGang, + '2G': DeviceType.TwoGang, + '1G': DeviceType.OneGang, + 'CUR': DeviceType.Curtain, + 'WH': DeviceType.WH, 'DS': DeviceType.DoorSensor, - "1GT": DeviceType.OneGang, - "2GT": DeviceType.TwoGang, - "3GT": DeviceType.ThreeGang, + '1GT': DeviceType.OneGang, + '2GT': DeviceType.TwoGang, + '3GT': DeviceType.ThreeGang, 'GD': DeviceType.GarageDoor, 'WL': DeviceType.WaterLeak, 'NCPS': DeviceType.NCPS, diff --git a/lib/utils/extension/build_context_x.dart b/lib/utils/extension/build_context_x.dart index 0abd16a1..1c3a5dbc 100644 --- a/lib/utils/extension/build_context_x.dart +++ b/lib/utils/extension/build_context_x.dart @@ -22,14 +22,14 @@ extension BuildContextExt on BuildContext { required VoidCallback onConfirm, VoidCallback? onDismiss, bool? hideConfirmButton, - final double? dialogWidth, + double? dialogWidth, TextStyle? titleStyle, String? onDismissText, String? onConfirmText, Color? onDismissColor, Color? onConfirmColor, }) { - showDialog( + showDialog( context: this, builder: (BuildContext context) { return AlertDialog( @@ -74,58 +74,59 @@ extension BuildContextExt on BuildContext { width: double.infinity, color: ColorsManager.greyColor, ), - hideConfirmButton != true - ? Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - GestureDetector( - onTap: onDismiss ?? - () { - Navigator.pop(context); - }, - child: Center( - child: Text( - onDismissText ?? 'Cancel', - style: context.textTheme.bodyMedium!.copyWith( - color: onDismissColor ?? - ColorsManager.greyColor), - ), - ), - ), - Container( - height: 50, - width: 1, - color: ColorsManager.greyColor, - ), - GestureDetector( - onTap: onConfirm, - child: Center( - child: Text( - onConfirmText ?? 'Confirm', - style: context.textTheme.bodyMedium!.copyWith( - color: onConfirmColor ?? - ColorsManager.primaryColorWithOpacity), - ), - ), - ), - ], - ) - : Padding( - padding: const EdgeInsets.symmetric(vertical: 16.0), - child: GestureDetector( - onTap: onDismiss ?? - () { - Navigator.pop(context); - }, - child: Center( - child: Text( - 'Cancel', - style: context.textTheme.bodyMedium! - .copyWith(color: ColorsManager.greyColor), - ), + if (hideConfirmButton != true) + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + GestureDetector( + onTap: onDismiss ?? + () { + Navigator.pop(context); + }, + child: Center( + child: Text( + onDismissText ?? 'Cancel', + style: context.textTheme.bodyMedium!.copyWith( + color: + onDismissColor ?? ColorsManager.greyColor), ), ), ), + Container( + height: 50, + width: 1, + color: ColorsManager.greyColor, + ), + GestureDetector( + onTap: onConfirm, + child: Center( + child: Text( + onConfirmText ?? 'Confirm', + style: context.textTheme.bodyMedium!.copyWith( + color: onConfirmColor ?? + ColorsManager.primaryColorWithOpacity), + ), + ), + ), + ], + ) + else + Padding( + padding: const EdgeInsets.symmetric(vertical: 16.0), + child: GestureDetector( + onTap: onDismiss ?? + () { + Navigator.pop(context); + }, + child: Center( + child: Text( + 'Cancel', + style: context.textTheme.bodyMedium! + .copyWith(color: ColorsManager.greyColor), + ), + ), + ), + ), ], ), ), diff --git a/lib/utils/format_date_time.dart b/lib/utils/format_date_time.dart index 98d0eb5e..2b63b1d4 100644 --- a/lib/utils/format_date_time.dart +++ b/lib/utils/format_date_time.dart @@ -5,8 +5,8 @@ String formatDateTime(DateTime? dateTime) { if (dateTime == null) { return '-'; } - final DateFormat dateFormatter = DateFormat('dd/MM/yyyy'); - final DateFormat timeFormatter = DateFormat('HH:mm'); + final dateFormatter = DateFormat('dd/MM/yyyy'); + final timeFormatter = DateFormat('HH:mm'); return '${dateFormatter.format(dateTime)} ${timeFormatter.format(dateTime)}'; } diff --git a/lib/utils/helpers/decodeBase64.dart b/lib/utils/helpers/decodeBase64.dart index e0473992..d94bd090 100644 --- a/lib/utils/helpers/decodeBase64.dart +++ b/lib/utils/helpers/decodeBase64.dart @@ -2,7 +2,7 @@ import 'dart:convert'; String decodeBase64(String str) { //'-', '+' 62nd char of encoding, '_', '/' 63rd char of encoding - String output = str.replaceAll('-', '+').replaceAll('_', '/'); + var output = str.replaceAll('-', '+').replaceAll('_', '/'); switch (output.length % 4) { // Pad with trailing '=' case 0: // No pad chars in this case diff --git a/lib/utils/helpers/shared_preferences_helper.dart b/lib/utils/helpers/shared_preferences_helper.dart index b9c7e0f4..97a504e0 100644 --- a/lib/utils/helpers/shared_preferences_helper.dart +++ b/lib/utils/helpers/shared_preferences_helper.dart @@ -1,52 +1,52 @@ import 'package:shared_preferences/shared_preferences.dart'; class SharedPreferencesHelper { - static saveStringToSP(String key, String value) async { + static Future saveStringToSP(String key, String value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(key, value); } - static saveBoolToSP(String key, bool value) async { + static Future saveBoolToSP(String key, bool value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(key, value); } - static saveIntToSP(String key, int value) async { + static Future saveIntToSP(String key, int value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt(key, value); } - static saveDoubleToSP(String key, double value) async { + static Future saveDoubleToSP(String key, double value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(key, value); } - static saveStringListToSP(String key, List value) async { + static Future saveStringListToSP(String key, List value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setStringList(key, value); } static Future readStringFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - String value = prefs.getString(key) ?? ''; + final value = prefs.getString(key) ?? ''; return value; } static Future readBoolFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - bool? value = prefs.getBool(key); + final value = prefs.getBool(key); return value; } static Future readIntFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - int value = prefs.getInt(key) ?? 0; + final value = prefs.getInt(key) ?? 0; return value; } static Future> readStringListFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - List? value = prefs.getStringList(key) ?? []; + final value = prefs.getStringList(key) ?? []; return value; } diff --git a/lib/utils/navigation_service.dart b/lib/utils/navigation_service.dart index c9d654e6..c0b12167 100644 --- a/lib/utils/navigation_service.dart +++ b/lib/utils/navigation_service.dart @@ -5,6 +5,3 @@ class NavigationService { static GlobalKey? snackbarKey = GlobalKey(); } - - - diff --git a/lib/utils/snack_bar.dart b/lib/utils/snack_bar.dart index 0a312e5a..ae65541d 100644 --- a/lib/utils/snack_bar.dart +++ b/lib/utils/snack_bar.dart @@ -3,7 +3,7 @@ import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/navigation_service.dart'; class CustomSnackBar { - static displaySnackBar(String message) { + static void displaySnackBar(String message) { final key = NavigationService.snackbarKey; if (key != null) { final snackBar = SnackBar(content: Text(message)); @@ -12,9 +12,9 @@ class CustomSnackBar { } } - static redSnackBar(String message) { + static void redSnackBar(String message) { final key = NavigationService.snackbarKey; - BuildContext? currentContext = key?.currentContext; + final currentContext = key?.currentContext; if (key != null && currentContext != null) { final snackBar = SnackBar( padding: const EdgeInsets.all(16), @@ -30,10 +30,8 @@ class CustomSnackBar { ), Text( message, - style: Theme.of(currentContext) - .textTheme - .bodySmall! - .copyWith(fontSize: 14, fontWeight: FontWeight.w500, color: Colors.green), + style: Theme.of(currentContext).textTheme.bodySmall!.copyWith( + fontSize: 14, fontWeight: FontWeight.w500, color: Colors.green), ) ]), ); @@ -41,9 +39,9 @@ class CustomSnackBar { } } - static greenSnackBar(String message) { + static void greenSnackBar(String message) { final key = NavigationService.snackbarKey; - BuildContext? currentContext = key?.currentContext; + final currentContext = key?.currentContext; if (key != null && currentContext != null) { final snackBar = SnackBar( padding: const EdgeInsets.all(16), @@ -59,10 +57,8 @@ class CustomSnackBar { ), Text( message, - style: Theme.of(currentContext) - .textTheme - .bodySmall! - .copyWith(fontSize: 14, fontWeight: FontWeight.w500, color: Colors.green), + style: Theme.of(currentContext).textTheme.bodySmall!.copyWith( + fontSize: 14, fontWeight: FontWeight.w500, color: Colors.green), ) ]), ); diff --git a/lib/utils/style.dart b/lib/utils/style.dart index 905bb7a8..9964cf41 100644 --- a/lib/utils/style.dart +++ b/lib/utils/style.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:syncrow_web/utils/color_manager.dart'; -import 'color_manager.dart'; - -InputDecoration? textBoxDecoration({bool suffixIcon = false, double radios = 8}) => +InputDecoration? textBoxDecoration( + {bool suffixIcon = false, double radios = 8}) => InputDecoration( focusColor: ColorsManager.grayColor, suffixIcon: suffixIcon ? const Icon(Icons.search) : null, @@ -34,7 +34,7 @@ InputDecoration? textBoxDecoration({bool suffixIcon = false, double radios = 8}) BoxDecoration containerDecoration = BoxDecoration( boxShadow: [ BoxShadow( - color: Colors.grey.withOpacity(0.3), + color: Colors.grey.withValues(alpha: 0.3), spreadRadius: 2, blurRadius: 4, offset: const Offset(0, 5), // changes position of shadow @@ -46,7 +46,7 @@ BoxDecoration containerDecoration = BoxDecoration( BoxDecoration containerWhiteDecoration = BoxDecoration( boxShadow: [ BoxShadow( - color: Colors.grey.withOpacity(0.3), + color: Colors.grey.withValues(alpha: 0.3), spreadRadius: 2, blurRadius: 4, offset: const Offset(0, 5), // changes position of shadow @@ -59,7 +59,7 @@ BoxDecoration subSectionContainerDecoration = BoxDecoration( color: ColorsManager.whiteColors, boxShadow: [ BoxShadow( - color: Colors.black.withOpacity(0.1), + color: Colors.black.withValues(alpha: 0.1), blurRadius: 10, spreadRadius: 1, offset: const Offset(0, 2), @@ -70,7 +70,7 @@ BoxDecoration subSectionContainerDecoration = BoxDecoration( final secondarySection = BoxDecoration( boxShadow: [ BoxShadow( - color: Colors.black.withOpacity(0.1), + color: Colors.black.withValues(alpha: 0.1), spreadRadius: 1, blurRadius: 7, offset: const Offset(0, 10), diff --git a/lib/utils/theme/theme.dart b/lib/utils/theme/theme.dart index 5ac61afa..27ddd487 100644 --- a/lib/utils/theme/theme.dart +++ b/lib/utils/theme/theme.dart @@ -34,7 +34,7 @@ final myTheme = ThemeData( }), trackColor: WidgetStateProperty.resolveWith((states) { if (states.contains(WidgetState.selected)) { - return ColorsManager.blueColor.withOpacity(0.5); + return ColorsManager.blueColor.withValues(alpha: 0.5); } return ColorsManager.whiteColors; }), diff --git a/lib/utils/user_drop_down_menu.dart b/lib/utils/user_drop_down_menu.dart index 15da1f3a..f70b90c1 100644 --- a/lib/utils/user_drop_down_menu.dart +++ b/lib/utils/user_drop_down_menu.dart @@ -1,10 +1,8 @@ import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart'; import 'package:syncrow_web/pages/auth/model/user_model.dart'; -import 'package:syncrow_web/pages/common/bloc/project_manager.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; @@ -66,9 +64,9 @@ class _UserDropdownMenuState extends State { } Future _showPopupMenu(BuildContext context) async { - final RenderBox overlay = - Overlay.of(context).context.findRenderObject() as RenderBox; - final RelativeRect position = RelativeRect.fromRect( + final overlay = + Overlay.of(context).context.findRenderObject()! as RenderBox; + final position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width, 75, @@ -106,7 +104,7 @@ class _UserDropdownMenuState extends State { child: ListTile( leading: SvgPicture.asset(Assets.userManagement), title: Text( - "User Management", + 'User Management', style: context.textTheme.bodyMedium, ), ), @@ -255,7 +253,7 @@ class _UserDropdownMenuState extends State { child: ListTile( leading: SvgPicture.asset(Assets.signOut), title: Text( - "Log Out", + 'Log Out', style: context.textTheme.bodyMedium, ), ), diff --git a/lib/web_layout/default_container.dart b/lib/web_layout/default_container.dart index e0a71b04..c156ecd5 100644 --- a/lib/web_layout/default_container.dart +++ b/lib/web_layout/default_container.dart @@ -21,7 +21,7 @@ class DefaultContainer extends StatelessWidget { final EdgeInsets? margin; final EdgeInsets? padding; final Color? color; - final Function()? onTap; + final void Function()? onTap; final BorderRadius? borderRadius; @override Widget build(BuildContext context) { diff --git a/lib/web_layout/web_app_bar.dart b/lib/web_layout/web_app_bar.dart index 3cfe171e..03e2e8a8 100644 --- a/lib/web_layout/web_app_bar.dart +++ b/lib/web_layout/web_app_bar.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; +import 'package:syncrow_web/pages/auth/model/user_model.dart'; import 'package:syncrow_web/pages/home/bloc/home_bloc.dart'; import 'package:syncrow_web/pages/home/bloc/home_state.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -49,7 +50,7 @@ class DesktopAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final dynamic user; + final UserModel? user; const DesktopAppBar({ super.key, @@ -75,7 +76,7 @@ class DesktopAppBar extends StatelessWidget { if (centerBody != null) Padding( padding: const EdgeInsets.only(left: 80), - child: centerBody!, + child: centerBody, ), ], ), @@ -102,7 +103,7 @@ class TabletAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final dynamic user; + final UserModel? user; const TabletAppBar({ super.key, @@ -149,7 +150,7 @@ class MobileAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final dynamic user; + final UserModel? user; const MobileAppBar({ super.key, @@ -182,12 +183,12 @@ class MobileAppBar extends StatelessWidget { if (centerBody != null) Padding( padding: const EdgeInsets.only(top: 8), - child: centerBody!, + child: centerBody, ), if (rightBody != null) Padding( padding: const EdgeInsets.only(top: 8), - child: rightBody!, + child: rightBody, ), ], ), diff --git a/lib/web_layout/web_scaffold.dart b/lib/web_layout/web_scaffold.dart index a37727db..812ea49e 100644 --- a/lib/web_layout/web_scaffold.dart +++ b/lib/web_layout/web_scaffold.dart @@ -1,10 +1,9 @@ import 'package:flutter/material.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; +import 'package:syncrow_web/web_layout/menu_sidebar.dart'; import 'package:syncrow_web/web_layout/web_app_bar.dart'; -import 'menu_sidebar.dart'; - class WebScaffold extends StatelessWidget with HelperResponsiveLayout { final bool enableMenuSidebar; final Widget? appBarTitle; diff --git a/test/widget_test.dart b/test/widget_test.dart index e69de29b..8b137891 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -0,0 +1 @@ +