diff --git a/lib/common/dialog_dropdown.dart b/lib/common/dialog_dropdown.dart index 2d1c3f43..7274b3c0 100644 --- a/lib/common/dialog_dropdown.dart +++ b/lib/common/dialog_dropdown.dart @@ -1,6 +1,5 @@ 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; @@ -8,14 +7,14 @@ class DialogDropdown extends StatefulWidget { final String? selectedValue; const DialogDropdown({ - super.key, + Key? key, required this.items, required this.onSelected, this.selectedValue, - }); + }) : super(key: key); @override - State createState() => _DialogDropdownState(); + _DialogDropdownState createState() => _DialogDropdownState(); } class _DialogDropdownState extends State { @@ -47,14 +46,16 @@ 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: [ @@ -86,9 +87,12 @@ class _DialogDropdownState extends State { child: ListTile( title: Text( item, - style: context.textTheme.bodyMedium?.copyWith( - color: ColorsManager.textPrimaryColor, - ), + style: Theme.of(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 ecda643e..1643b414 100644 --- a/lib/common/edit_chip.dart +++ b/lib/common/edit_chip.dart @@ -10,25 +10,24 @@ class EditChip extends StatelessWidget { final double borderRadius; const EditChip({ - super.key, + Key? 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 45d05614..9fa85284 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({ - super.key, + Key? 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 bbe6a074..74151ca2 100644 --- a/lib/common/widgets/custom_expansion_tile.dart +++ b/lib/common/widgets/custom_expansion_tile.dart @@ -10,8 +10,7 @@ class CustomExpansionTile extends StatefulWidget { final ValueChanged? onExpansionChanged; // Notify when expansion changes final VoidCallback? onItemSelected; // Callback for selecting the item - const CustomExpansionTile({ - super.key, + CustomExpansionTile({ 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 a706f155..a99ac510 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 void Function(String)? onSearchChanged; + final Function(String)? onSearchChanged; // Callback for search input changes const CustomSearchBar({ super.key, @@ -37,7 +37,7 @@ class _CustomSearchBarState extends State { color: ColorsManager.whiteColors, boxShadow: [ BoxShadow( - color: Colors.black.withValues(alpha: 0.2), + color: Colors.black.withOpacity(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, + onChanged: widget.onSearchChanged, // Call the callback on text change decoration: InputDecoration( filled: true, fillColor: ColorsManager.textFieldGreyColor, diff --git a/lib/firebase_options_prod.dart b/lib/firebase_options_prod.dart index 0d9ac673..485696b8 100644 --- a/lib/firebase_options_prod.dart +++ b/lib/firebase_options_prod.dart @@ -1,8 +1,7 @@ // 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 f875cc04..8eb6ce38 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 { - final checkToken = await AuthBloc.getTokenAndValidate(); + String 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 81c71a5f..578b2c30 100644 --- a/lib/main_dev.dart +++ b/lib/main_dev.dart @@ -21,8 +21,7 @@ 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( @@ -40,7 +39,7 @@ class MyApp extends StatelessWidget { initialLocation: RoutesConst.auth, routes: AppRoutes.getRoutes(), redirect: (context, state) async { - final checkToken = await AuthBloc.getTokenAndValidate(); + String checkToken = await AuthBloc.getTokenAndValidate(); final loggedIn = checkToken == 'Success'; final goingToLogin = state.uri.toString() == RoutesConst.auth; @@ -58,8 +57,7 @@ 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 afccae74..e7f95c57 100644 --- a/lib/main_staging.dart +++ b/lib/main_staging.dart @@ -21,8 +21,7 @@ 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( @@ -40,7 +39,7 @@ class MyApp extends StatelessWidget { initialLocation: RoutesConst.auth, routes: AppRoutes.getRoutes(), redirect: (context, state) async { - final checkToken = await AuthBloc.getTokenAndValidate(); + String checkToken = await AuthBloc.getTokenAndValidate(); final loggedIn = checkToken == 'Success'; final goingToLogin = state.uri.toString() == RoutesConst.auth; @@ -58,8 +57,7 @@ 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 8b216f04..dd82d739 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() { - final toBeEffectiveCount = data + int toBeEffectiveCount = data .where((item) => item.passwordStatus.value == 'To be effective') .length; - final effectiveCount = + int effectiveCount = data.where((item) => item.passwordStatus.value == 'Effective').length; - final expiredCount = + int 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 picked = await showDatePicker( + final DateTime? 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: const ColorScheme.light( + colorScheme: ColorScheme.light( primary: ColorsManager.blackColor, onPrimary: Colors.white, onSurface: ColorsManager.grayColor, @@ -105,20 +105,20 @@ class AccessBloc extends Bloc { }, ); if (picked != null) { - final timePicked = await showHourPicker( + final TimeOfDay? timePicked = await showHourPicker( context: event.context, initialTime: TimeOfDay.now(), ); if (timePicked != null) { - final selectedDateTime = DateTime( + final DateTime selectedDateTime = DateTime( picked.year, picked.month, picked.day, timePicked.hour, timePicked.minute, ); - final selectedTimestamp = + final int selectedTimestamp = selectedDateTime.millisecondsSinceEpoch ~/ 1000; if (event.isStart) { if (expirationTimeTimeStamp != null && @@ -152,35 +152,39 @@ class AccessBloc extends Bloc { final searchText = event.passwordName?.toLowerCase() ?? ''; final searchEmailText = event.emailAuthorizer?.toLowerCase() ?? ''; filteredData = data.where((item) { - var matchesCriteria = true; + bool matchesCriteria = true; // Convert timestamp to DateTime and extract date component - final effectiveDate = DateTime.fromMillisecondsSinceEpoch( + DateTime effectiveDate = DateTime.fromMillisecondsSinceEpoch( int.parse(item.effectiveTime.toString()) * 1000) .toUtc() .toLocal(); - final invalidDate = DateTime.fromMillisecondsSinceEpoch( + DateTime invalidDate = DateTime.fromMillisecondsSinceEpoch( int.parse(item.invalidTime.toString()) * 1000) .toUtc() .toLocal(); - final effectiveDateAndTime = DateTime( + DateTime effectiveDateAndTime = DateTime( effectiveDate.year, effectiveDate.month, effectiveDate.day, effectiveDate.hour, effectiveDate.minute); - final invalidDateAndTime = DateTime(invalidDate.year, invalidDate.month, - invalidDate.day, invalidDate.hour, invalidDate.minute); + DateTime 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 matchesName = + final bool matchesName = item.passwordName.toString().toLowerCase().contains(searchText); if (!matchesName) { matchesCriteria = false; } } if (searchEmailText.isNotEmpty) { - final matchesName = item.authorizerEmail + final bool matchesName = item.authorizerEmail .toString() .toLowerCase() .contains(searchEmailText); @@ -190,7 +194,7 @@ class AccessBloc extends Bloc { } // Filter by start date only if (event.startTime != null && event.endTime == null) { - var startDateTime = + DateTime startDateTime = DateTime.fromMillisecondsSinceEpoch(event.startTime! * 1000) .toUtc() .toLocal(); @@ -202,7 +206,7 @@ class AccessBloc extends Bloc { } // Filter by end date only if (event.endTime != null && event.startTime == null) { - var startDateTime = + DateTime startDateTime = DateTime.fromMillisecondsSinceEpoch(event.endTime! * 1000) .toUtc() .toLocal(); @@ -215,11 +219,11 @@ class AccessBloc extends Bloc { // Filter by both start date and end date if (event.startTime != null && event.endTime != null) { - var startDateTime = + DateTime startDateTime = DateTime.fromMillisecondsSinceEpoch(event.startTime! * 1000) .toUtc() .toLocal(); - var endDateTime = + DateTime endDateTime = DateTime.fromMillisecondsSinceEpoch(event.endTime! * 1000) .toUtc() .toLocal(); @@ -254,7 +258,7 @@ class AccessBloc extends Bloc { } } - Future resetSearch(ResetSearch event, Emitter emit) async { + resetSearch(ResetSearch event, Emitter emit) async { emit(AccessLoaded()); startTime = 'Start Time'; endTime = 'End Time'; @@ -268,7 +272,7 @@ class AccessBloc extends Bloc { } String timestampToDate(dynamic timestamp) { - final dateTime = + DateTime 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')}"; @@ -285,17 +289,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 122e16ad..0790a735 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; - const FailedState(this.message); + 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 ccff1cb8..0ce4426a 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 f32741fc..410cadfd 100644 --- a/lib/pages/analytics/helpers/dashed_border_painter.dart +++ b/lib/pages/analytics/helpers/dashed_border_painter.dart @@ -1,3 +1,5 @@ +import 'dart:ui'; + import 'package:flutter/material.dart'; class DashedBorderPainter extends CustomPainter { @@ -18,28 +20,27 @@ class DashedBorderPainter extends CustomPainter { ..strokeWidth = 0.5 ..style = PaintingStyle.stroke; - final topPath = Path() + final Path topPath = Path() ..moveTo(0, 0) ..lineTo(size.width, 0); - final bottomPath = Path() + final Path 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 dashedPath = Path(); - for (final pathMetric in source.computeMetrics()) { - var distance = 0.0; + final Path dashedPath = Path(); + for (PathMetric pathMetric in source.computeMetrics()) { + double distance = 0.0; while (distance < pathMetric.length) { - final nextDistance = distance + dashWidth; + final double 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 0ee35a38..54b0fa87 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 95de21c2..2eab2ddb 100644 --- a/lib/pages/analytics/models/air_quality_data_model.dart +++ b/lib/pages/analytics/models/air_quality_data_model.dart @@ -15,8 +15,7 @@ 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(), ); } @@ -47,7 +46,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 0a36362a..3340a41d 100644 --- a/lib/pages/analytics/models/analytics_device.dart +++ b/lib/pages/analytics/models/analytics_device.dart @@ -36,14 +36,11 @@ 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 1d158869..b4b8dac9 100644 --- a/lib/pages/analytics/models/occupacy.dart +++ b/lib/pages/analytics/models/occupacy.dart @@ -15,8 +15,7 @@ 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 a5fa3ba7..73e7d5d7 100644 --- a/lib/pages/analytics/models/occupancy_heat_map_model.dart +++ b/lib/pages/analytics/models/occupancy_heat_map_model.dart @@ -19,8 +19,7 @@ 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 6d9f1c52..fb7e2352 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,8 +33,7 @@ class AirQualityDistributionBloc state.copyWith( status: AirQualityDistributionStatus.success, chartData: result, - filteredChartData: - _arrangeChartDataByType(result, state.selectedAqiType), + filteredChartData: _arrangeChartDataByType(result, state.selectedAqiType), ), ); } catch (e) { @@ -62,8 +61,7 @@ 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 9bac8120..4f41eb0c 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,8 +7,7 @@ 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 cb959051..88c3715e 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,8 +53,7 @@ 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 889936c4..21cb2a9e 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,8 +105,7 @@ 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 634c86ab..ebe88614 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,8 +81,7 @@ 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 36346cb6..373e36ca 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,25 +36,23 @@ 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; - var isFirstElement = true; + bool 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), @@ -86,9 +84,9 @@ class AqiDistributionChart extends StatelessWidget { tooltipRoundedRadius: 16, tooltipPadding: const EdgeInsets.all(8), getTooltipItem: (group, groupIndex, rod, rodIndex) { - final data = chartData[group.x]; + final data = chartData[group.x.toInt()]; - final children = []; + final List children = []; final textStyle = context.textTheme.bodySmall?.copyWith( color: ColorsManager.blackColor, @@ -96,9 +94,8 @@ 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 6f2eb198..5a8e6e6c 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 (var i = 0; i < ranges.length; i++) { + for (int 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 242c5d4b..60a686ff 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,8 +29,7 @@ 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 a392dc2e..fc63e413 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: const [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], + stops: [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,8 +99,7 @@ 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 3885ffc2..6548c696 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,8 +32,7 @@ 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 723df1c3..fb61e73b 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,8 +8,7 @@ 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 20eddb43..0ae7d8c5 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 2614ea28..8b1802af 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,8 +8,7 @@ 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, @@ -26,8 +25,7 @@ final class AirQualityDataLoadingStrategy 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); @@ -36,7 +34,7 @@ final class AirQualityDataLoadingStrategy spaceTreeBloc ..add(const SpaceTreeClearSelectionEvent()) - ..add(OnSpaceSelected(community, space.uuid ?? '', const [])); + ..add(OnSpaceSelected(community, space.uuid ?? '', [])); 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 f48fd7f2..19b0aff2 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,8 +8,7 @@ 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 14e27515..757b2a9a 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,8 +7,7 @@ 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, @@ -32,8 +31,7 @@ class EnergyManagementDataLoadingStrategy 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 e7055b61..9bffe3b4 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,8 +24,7 @@ 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); @@ -34,7 +33,7 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy { spaceTreeBloc ..add(const SpaceTreeClearSelectionEvent()) - ..add(OnSpaceSelected(community, space.uuid ?? '', const [])); + ..add(OnSpaceSelected(community, space.uuid ?? '', [])); 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 a8b43943..ab07737a 100644 --- a/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart +++ b/lib/pages/analytics/modules/analytics/widgets/analytics_communities_sidebar.dart @@ -10,8 +10,7 @@ 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 ab41c7d7..af70cd86 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 _color = ColorsManager.blackColor.withValues(alpha: 0.8); + static final _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 abc688fc..9ff98ef2 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,9 +33,8 @@ 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 41dcd108..57133b02 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,19 +189,14 @@ 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 9521ab24..f900a040 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,8 +53,7 @@ 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; @@ -77,10 +76,9 @@ class _AnalyticsSpaceTreeViewState extends State { ), ), CustomSearchBar( - onSearchChanged: (query) => - context.read().add( - SearchQueryEvent(query), - ), + onSearchChanged: (query) => context.read().add( + SearchQueryEvent(query), + ), ), const SizedBox(height: 16), Expanded( @@ -115,8 +113,7 @@ class _AnalyticsSpaceTreeViewState extends State { isExpanded: state.expandedCommunities.contains( communities[index].uuid, ), - onItemSelected: () => - widget.onSelectCommunity?.call( + onItemSelected: () => widget.onSelectCommunity?.call( communities[index], communities[index].spaces, ), @@ -124,8 +121,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], @@ -156,8 +153,7 @@ 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 711d1ccd..22eb6646 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 List years = List.generate( + static final 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,12 +123,9 @@ 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 a3f21f44..1acf7df5 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,15 +8,13 @@ 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; @@ -27,8 +25,7 @@ class EnergyConsumptionByPhasesBloc extends Bloc _onClearEnergyConsumptionByPhasesEvent( + void _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 0c1248ae..87bcf447 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,8 +7,7 @@ sealed class EnergyConsumptionByPhasesEvent extends Equatable { List get props => []; } -class LoadEnergyConsumptionByPhasesEvent - extends EnergyConsumptionByPhasesEvent { +class LoadEnergyConsumptionByPhasesEvent extends EnergyConsumptionByPhasesEvent { const LoadEnergyConsumptionByPhasesEvent({ required this.param, }); @@ -19,7 +18,6 @@ class LoadEnergyConsumptionByPhasesEvent 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 3f0806a1..97d182c5 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,13 +8,12 @@ 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< - EnergyConsumptionPerDeviceEvent, EnergyConsumptionPerDeviceState> { +class EnergyConsumptionPerDeviceBloc + extends Bloc { EnergyConsumptionPerDeviceBloc( this._energyConsumptionPerDeviceService, ) : super(const EnergyConsumptionPerDeviceState()) { - on( - _onLoadEnergyConsumptionPerDeviceEvent); + on(_onLoadEnergyConsumptionPerDeviceEvent); on( _onClearEnergyConsumptionPerDeviceEvent); } @@ -27,8 +26,7 @@ class EnergyConsumptionPerDeviceBloc extends Bloc< ) 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, @@ -52,7 +50,7 @@ class EnergyConsumptionPerDeviceBloc extends Bloc< } } - Future _onClearEnergyConsumptionPerDeviceEvent( + void _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 aa37078b..2aefd798 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,8 +8,7 @@ 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()) { @@ -26,8 +25,7 @@ class PowerClampInfoBloc ) 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, @@ -51,7 +49,7 @@ class PowerClampInfoBloc } } - Future _onUpdatePowerClampStatusEvent( + void _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 dc20f6f7..b69a2556 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,6 +16,7 @@ final class LoadPowerClampInfoEvent extends PowerClampInfoEvent { List get props => [deviceId]; } + final class UpdatePowerClampStatusEvent extends PowerClampInfoEvent { const UpdatePowerClampStatusEvent(this.statusList); @@ -27,4 +28,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 c56588b8..1eba8f7e 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 578899f9..f51d20cf 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 } } - Future _onClearTotalEnergyConsumptionEvent( + void _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 7240b669..f9510737 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,8 +7,7 @@ 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; @@ -17,7 +16,6 @@ final class TotalEnergyConsumptionLoadEvent 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 6de1e278..2ed68e76 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,8 +69,7 @@ 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), @@ -86,8 +85,7 @@ 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 f2796671..8de92098 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,8 +122,7 @@ 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 797821a4..f88febcc 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,8 +51,7 @@ 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 5d7f37a9..f7b33309 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,8 +52,7 @@ 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 e169d660..52c6f591 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,6 +18,7 @@ class EnergyConsumptionByPhasesChart extends StatelessWidget { Widget build(BuildContext context) { return BarChart( BarChartData( + gridData: EnergyManagementChartsHelper.gridData().copyWith( checkToShowHorizontalLine: (value) => true, horizontalInterval: 250, @@ -99,11 +100,11 @@ class EnergyConsumptionByPhasesChart extends StatelessWidget { }) { final data = energyData; - 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; + 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; 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 0c4e972d..1bd1ed9e 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,8 +22,7 @@ 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 4bed5682..1e74ad31 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,6 +17,7 @@ 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 5fd6b8d6..be5faf57 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,8 +46,7 @@ class EnergyConsumptionPerDeviceChartBox extends StatelessWidget { flex: 2, child: EnergyConsumptionPerDeviceDevicesList( chartData: state.chartData, - devices: - context.watch().state.devices, + devices: context.watch().state.devices, ), ), ], @@ -56,8 +55,7 @@ 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 3feda916..f95ff7d1 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,14 +43,11 @@ 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, ); }, ), @@ -94,8 +91,7 @@ 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 e1cc4238..a96a7298 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 '--'; - var str = value; + String str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp('[^0-9]'), ''); + str = str.replaceAll(RegExp(r'[^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 '--'; - var str = value; + String str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp('[^0-9]'), ''); + str = str.replaceAll(RegExp(r'[^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 '--'; - var str = value; + String str = value; if (str.isEmpty || str == '--') return '--'; - str = str.replaceAll(RegExp('[^0-9]'), ''); + str = str.replaceAll(RegExp(r'[^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 9ce6295b..85b95c29 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,6 +29,7 @@ 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 7596c7d0..e197c297 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,8 +25,7 @@ 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 c6966c7e..110f3c60 100644 --- a/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart +++ b/lib/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart @@ -23,11 +23,9 @@ 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 a56c0c9f..0b01fda2 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,18 +25,15 @@ 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() @@ -67,8 +64,7 @@ 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 7db4f90c..679c9927 100644 --- a/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart +++ b/lib/pages/analytics/modules/occupancy/views/analytics_occupancy_view.dart @@ -20,12 +20,9 @@ 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 d328b972..70087c46 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart @@ -41,8 +41,7 @@ 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), @@ -89,8 +88,8 @@ class OccupancyChart extends StatelessWidget { }) { final data = chartData; - final occupancyValue = double.parse(data[group.x].occupancy); - final percentage = '${occupancyValue.toStringAsFixed(0)}%'; + final occupancyValue = double.parse(data[group.x.toInt()].occupancy); + final percentage = '${(occupancyValue).toStringAsFixed(0)}%'; return BarTooltipItem( percentage, @@ -117,7 +116,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 a950593d..08f7223f 100644 --- a/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart +++ b/lib/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart @@ -44,15 +44,13 @@ 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 846b9d30..c3b537e0 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,15 +44,13 @@ 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 b57a73e1..633b8c54 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 fillPaint = Paint(); - final borderPaint = Paint() + final Paint fillPaint = Paint(); + final Paint borderPaint = Paint() ..color = ColorsManager.grayBorder.withValues(alpha: 0.4) ..style = PaintingStyle.stroke; - final hoveredBorderPaint = Paint() + final Paint 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 dashWidth = 2.0; - const dashSpace = 4.0; - final totalLength = (end - start).distance; - final direction = (end - start) / (end - start).distance; + const double dashWidth = 2.0; + const double dashSpace = 4.0; + final double totalLength = (end - start).distance; + final Offset direction = (end - start) / (end - start).distance; - var currentLength = 0.0; + double currentLength = 0.0; while (currentLength < totalLength) { - final dashStart = start + direction * currentLength; - final nextLength = currentLength + dashWidth; - final dashEnd = start + - direction * (nextLength < totalLength ? nextLength : totalLength); + final Offset dashStart = start + direction * currentLength; + final double nextLength = currentLength + dashWidth; + final Offset 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 69189b60..e0023f53 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,8 +5,7 @@ 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 @@ -44,6 +43,7 @@ class FakeAirQualityDistributionService name: 'poor', percentage: nonNullValues[2], type: AqiType.hcho.code, + ), AirQualityPercentageData( name: 'unhealthy', @@ -71,7 +71,7 @@ class FakeAirQualityDistributionService List nullMask, ) { double nonNullSum = 0; - for (var i = 0; i < originalValues.length; i++) { + for (int 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 7054c97b..dcf00600 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,8 +3,7 @@ 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 ee4fb431..2d735df6 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,8 +16,7 @@ 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 62c0908b..9ef711e9 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,8 +14,7 @@ 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', @@ -38,8 +37,7 @@ 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 37b9663c..736b0804 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,8 +6,7 @@ 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; @@ -15,8 +14,7 @@ class RemoteOccupancyAnalyticsDevicesService 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) { @@ -36,18 +34,15 @@ class RemoteOccupancyAnalyticsDevicesService 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(); @@ -74,8 +69,7 @@ class RemoteOccupancyAnalyticsDevicesService 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 eb77fa5a..0239bcb7 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'); + throw Exception('Failed to load device location info: ${e.toString()}'); } } } 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 5546bf65..17f9baff 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,8 +11,7 @@ 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( @@ -37,8 +36,7 @@ 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 1845ac6e..82b21b1c 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,8 +13,7 @@ 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( @@ -32,8 +31,7 @@ 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(': '); @@ -61,8 +59,7 @@ 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 149ae31c..afd3f79e 100644 --- a/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart +++ b/lib/pages/analytics/services/occupacy/remote_occupancy_service.dart @@ -33,8 +33,7 @@ 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 38865981..0d7f6500 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,8 +13,7 @@ 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}', @@ -25,8 +24,7 @@ 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(); @@ -38,8 +36,7 @@ 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 3930c252..b4bc82c6 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,8 +28,7 @@ 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 3140cae3..01ad6fa1 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 Future.delayed(const Duration(milliseconds: 800), () { + return await Future.delayed(const Duration(milliseconds: 800), () { final random = DateTime.now().millisecondsSinceEpoch; return List.generate(30, (index) { @@ -19,20 +19,14 @@ 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 6f5f00b1..9e1657e3 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 92c152ca..7afece6a 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 42cdadbf..838cc5e7 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,8 +5,7 @@ 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; @@ -30,8 +29,7 @@ class RemoteTotalEnergyConsumptionService 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 33f59032..5ff1d042 100644 --- a/lib/pages/analytics/widgets/analytics_sidebar_header.dart +++ b/lib/pages/analytics/widgets/analytics_sidebar_header.dart @@ -75,8 +75,7 @@ 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 c2774263..58950089 100644 --- a/lib/pages/auth/bloc/auth_bloc.dart +++ b/lib/pages/auth/bloc/auth_bloc.dart @@ -36,8 +36,7 @@ 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(); @@ -54,8 +53,7 @@ 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( @@ -64,7 +62,7 @@ class AuthBloc extends Bloc { } on DioException catch (e) { if (e.response!.statusCode == 400) { final errorData = e.response!.data; - final String errorMessage = errorData['message']; + String errorMessage = errorData['message']; if (errorMessage == 'User not found') { validate = 'Invalid Credential'; emit(AuthInitialState()); @@ -92,8 +90,7 @@ 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)); } }); } @@ -103,11 +100,11 @@ class AuthBloc extends Bloc { emit(const TimerState(isButtonEnabled: true, remainingTime: 0)); } - Future changePassword( +Future changePassword( ChangePasswordEvent event, Emitter emit) async { emit(LoadingForgetState()); try { - final response = await AuthenticationAPI.verifyOtp( + var response = await AuthenticationAPI.verifyOtp( email: forgetEmailController.text, otpCode: forgetOtp.text); if (response == true) { await AuthenticationAPI.forgetPassword( @@ -125,6 +122,7 @@ class AuthBloc extends Bloc { } } + String? validateCode(String? value) { if (value == null || value.isEmpty) { return 'Code is required'; @@ -133,9 +131,7 @@ class AuthBloc extends Bloc { } void _onUpdateTimer(UpdateTimerEvent event, Emitter emit) { - emit(TimerState( - isButtonEnabled: event.isButtonEnabled, - remainingTime: event.remainingTime)); + emit(TimerState(isButtonEnabled: event.isButtonEnabled, remainingTime: event.remainingTime)); } ///////////////////////////////////// login ///////////////////////////////////// @@ -155,7 +151,8 @@ class AuthBloc extends Bloc { static UserModel? user; bool showValidationMessage = false; - Future _login(LoginButtonPressed event, Emitter emit) async { + + void _login(LoginButtonPressed event, Emitter emit) async { emit(AuthLoading()); if (isChecked) { try { @@ -182,7 +179,7 @@ class AuthBloc extends Bloc { } if (token.accessTokenIsNotEmpty) { - const storage = FlutterSecureStorage(); + FlutterSecureStorage storage = const FlutterSecureStorage(); await storage.write( key: Token.loginAccessTokenKey, value: token.accessToken); const FlutterSecureStorage().write( @@ -200,7 +197,8 @@ class AuthBloc extends Bloc { } } - void checkBoxToggle( + + checkBoxToggle( CheckBoxEvent event, Emitter emit, ) { @@ -279,12 +277,12 @@ class AuthBloc extends Bloc { if (value == null || value.isEmpty) { return 'Please enter your password'; } - final validationErrors = []; + List validationErrors = []; - if (!RegExp('^(?=.*[a-z])').hasMatch(value)) { + if (!RegExp(r'^(?=.*[a-z])').hasMatch(value)) { validationErrors.add(' - one lowercase letter'); } - if (!RegExp('^(?=.*[A-Z])').hasMatch(value)) { + if (!RegExp(r'^(?=.*[A-Z])').hasMatch(value)) { validationErrors.add(' - one uppercase letter'); } if (!RegExp(r'^(?=.*\d)').hasMatch(value)) { @@ -306,7 +304,7 @@ class AuthBloc extends Bloc { 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'; } @@ -341,14 +339,12 @@ class AuthBloc extends Bloc { 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'; @@ -370,8 +366,7 @@ class AuthBloc extends Bloc { } } - Future _fetchRegion( - RegionInitialEvent event, Emitter emit) async { + void _fetchRegion(RegionInitialEvent event, Emitter emit) async { try { emit(AuthLoading()); regionList = await AuthenticationAPI.fetchRegion(); @@ -394,17 +389,15 @@ class AuthBloc extends Bloc { } String formattedTime(int time) { - 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 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 formattedTime = [ + final String 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(':'); @@ -424,7 +417,7 @@ class AuthBloc extends Bloc { return checkValidate; } - void changeValidate( + changeValidate( ChangeValidateEvent event, Emitter emit, ) { @@ -433,7 +426,7 @@ class AuthBloc extends Bloc { emit(LoginInitial()); } - void changeForgetValidate( + changeForgetValidate( ChangeValidateEvent event, Emitter emit, ) { diff --git a/lib/pages/auth/bloc/auth_event.dart b/lib/pages/auth/bloc/auth_event.dart index 392270e3..2b6a4eef 100644 --- a/lib/pages/auth/bloc/auth_event.dart +++ b/lib/pages/auth/bloc/auth_event.dart @@ -46,8 +46,7 @@ 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 05790a7b..f3a95157 100644 --- a/lib/pages/auth/bloc/auth_state.dart +++ b/lib/pages/auth/bloc/auth_state.dart @@ -56,8 +56,7 @@ 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]; @@ -81,7 +80,7 @@ class TimerUpdated extends AuthState { final String formattedTime; final bool isButtonEnabled; - const TimerUpdated({ + 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 fcde9f17..dca3f8f9 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 +//tst@tst.com \ No newline at end of file diff --git a/lib/pages/auth/model/token.dart b/lib/pages/auth/model/token.dart index 24ee46f2..53c6f401 100644 --- a/lib/pages/auth/model/token.dart +++ b/lib/pages/auth/model/token.dart @@ -11,14 +11,6 @@ class Token { final int iat; final int exp; - Token( - this.accessToken, - this.refreshToken, - this.sessionId, - this.iat, - this.exp, - ); - Token.emptyConstructor() : accessToken = '', refreshToken = '', @@ -32,6 +24,14 @@ 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 - const storage = FlutterSecureStorage(); + var storage = const 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 98da8bd3..267d0b3e 100644 --- a/lib/pages/auth/model/user_model.dart +++ b/lib/pages/auth/model/user_model.dart @@ -55,21 +55,22 @@ class UserModel { //from token factory UserModel.fromToken(Token token) { - final tempJson = Token.decodeToken(token.accessToken); + Map 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 b32644db..7686ea8f 100644 --- a/lib/pages/auth/view/forget_password_web_page.dart +++ b/lib/pages/auth/view/forget_password_web_page.dart @@ -36,18 +36,20 @@ class ForgetPasswordWebPage extends StatelessWidget { ); } }, - builder: _buildForm, + builder: (context, state) { + return _buildForm(context, state); + }, ), ), ); } Widget _buildForm(BuildContext context, AuthState state) { - late ScrollController scrollController; - scrollController = ScrollController(); - void scrollToCenter() { - final middlePosition = scrollController.position.maxScrollExtent / 2; - scrollController.animateTo( + late ScrollController _scrollController; + _scrollController = ScrollController(); + void _scrollToCenter() { + final double middlePosition = _scrollController.position.maxScrollExtent / 2; + _scrollController.animateTo( middlePosition, duration: const Duration(seconds: 1), curve: Curves.easeInOut, @@ -55,25 +57,24 @@ class ForgetPasswordWebPage extends StatelessWidget { } WidgetsBinding.instance.addPostFrameCallback((_) { - scrollToCenter(); + _scrollToCenter(); }); final forgetBloc = BlocProvider.of(context); - final size = MediaQuery.of(context).size; + Size 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.withValues(alpha: 0.3), + color: Colors.black.withOpacity(0.3), borderRadius: const BorderRadius.all(Radius.circular(20)), ), child: Center( @@ -93,22 +94,17 @@ class ForgetPasswordWebPage extends StatelessWidget { flex: 3, child: Container( decoration: BoxDecoration( - color: Colors.white.withValues(alpha: 0.1), - borderRadius: - const BorderRadius.all(Radius.circular(30)), - border: Border.all( - color: ColorsManager.graysColor - .withValues(alpha: 0.2)), + color: Colors.white.withOpacity(0.1), + borderRadius: const BorderRadius.all(Radius.circular(30)), + border: Border.all(color: ColorsManager.graysColor.withOpacity(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), @@ -125,9 +121,7 @@ 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( @@ -146,90 +140,69 @@ 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! @@ -238,31 +211,27 @@ 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( @@ -275,44 +244,34 @@ 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, ), @@ -323,13 +282,10 @@ 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), ), ), ], @@ -339,31 +295,23 @@ 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()); } } }, @@ -377,8 +325,7 @@ class ForgetPasswordWebPage extends StatelessWidget { child: Text( forgetBloc.validate, style: const TextStyle( - fontWeight: FontWeight.w700, - color: ColorsManager.red), + fontWeight: FontWeight.w700, color: ColorsManager.red), ), ), ), @@ -390,9 +337,8 @@ 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: () { @@ -400,7 +346,7 @@ class ForgetPasswordWebPage extends StatelessWidget { Navigator.pop(context); }, child: const Text( - 'Sign in', + "Sign in", ), ), ], @@ -426,15 +372,14 @@ class ForgetPasswordWebPage extends StatelessWidget { )); } - Widget _buildDropdownField( - BuildContext context, AuthBloc loginBloc, Size size) { - final textEditingController = TextEditingController(); + Widget _buildDropdownField(BuildContext context, AuthBloc loginBloc, Size size) { + final TextEditingController 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, @@ -453,13 +398,10 @@ 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( @@ -470,16 +412,14 @@ 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, ), ), @@ -506,11 +446,10 @@ 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, @@ -523,8 +462,7 @@ 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( @@ -548,8 +486,7 @@ 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, @@ -563,8 +500,7 @@ 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 a32944dc..4f001bc6 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.withValues(alpha: 0.3), + color: Colors.black.withOpacity(0.3), borderRadius: const BorderRadius.all(Radius.circular(20))), child: Column( mainAxisSize: MainAxisSize.min, @@ -93,15 +93,12 @@ class LoginMobilePage extends StatelessWidget { ), ), Container( - margin: const EdgeInsets.all(30), - padding: const EdgeInsets.all(20), + margin: EdgeInsets.all(30), + padding: EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white.withValues(alpha: 0.1), - borderRadius: - const BorderRadius.all(Radius.circular(30)), - border: Border.all( - color: ColorsManager.graysColor - .withValues(alpha: 0.2))), + color: Colors.white.withOpacity(0.1), + borderRadius: const BorderRadius.all(Radius.circular(30)), + border: Border.all(color: ColorsManager.graysColor.withOpacity(0.2))), child: Form( key: loginBloc.loginFormKey, child: Column( @@ -112,9 +109,7 @@ 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( @@ -160,15 +155,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), ), ), @@ -180,7 +175,7 @@ class LoginMobilePage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - 'Password', + "Password", style: Theme.of(context).textTheme.bodySmall, ), SizedBox( @@ -188,8 +183,7 @@ 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', ), @@ -207,19 +201,16 @@ 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), ), ), ], @@ -230,15 +221,13 @@ class LoginMobilePage extends StatelessWidget { Transform.scale( scale: 1.2, // Adjust the scale as needed child: Checkbox( - fillColor: WidgetStateProperty.all( - Colors.white), + fillColor: MaterialStateProperty.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)); }, ), ), @@ -247,37 +236,30 @@ 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'); }, ), ], @@ -294,14 +276,11 @@ 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, ), ); } @@ -316,11 +295,10 @@ 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 d7416b67..a6de87cf 100644 --- a/lib/pages/auth/view/login_web_page.dart +++ b/lib/pages/auth/view/login_web_page.dart @@ -24,8 +24,7 @@ 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( @@ -43,7 +42,9 @@ class _LoginWebPageState extends State ); } }, - builder: _buildLoginForm, + builder: (context, state) { + return _buildLoginForm(context, state); + }, ), ), ); @@ -53,12 +54,12 @@ class _LoginWebPageState extends State final loginBloc = BlocProvider.of(context); final isSmallScreen = isSmallScreenSize(context); final isMediumScreen = isMediumScreenSize(context); - final size = MediaQuery.of(context).size; + Size size = MediaQuery.of(context).size; late ScrollController scrollController; scrollController = ScrollController(); void scrollToCenter() { - final middlePosition = scrollController.position.maxScrollExtent / 2; + final double middlePosition = scrollController.position.maxScrollExtent / 2; scrollController.animateTo( middlePosition, duration: const Duration(seconds: 1), @@ -83,7 +84,7 @@ class _LoginWebPageState extends State padding: EdgeInsets.all(size.width * 0.02), margin: EdgeInsets.all(size.width * 0.05), decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.3), + color: Colors.black.withOpacity(0.3), borderRadius: const BorderRadius.all(Radius.circular(20)), ), child: Center( @@ -120,8 +121,7 @@ class _LoginWebPageState extends State const Spacer(), Expanded( flex: 2, - child: _buildLoginFormFields( - context, loginBloc, size), + child: _buildLoginFormFields(context, loginBloc, size), ), const Spacer(), ], @@ -132,26 +132,23 @@ class _LoginWebPageState extends State ), ), ), - 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.withValues(alpha: 0.1), + color: Colors.white.withOpacity(0.1), borderRadius: const BorderRadius.all(Radius.circular(30)), - border: - Border.all(color: ColorsManager.graysColor.withValues(alpha: 0.2)), + border: Border.all(color: ColorsManager.graysColor.withOpacity(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, @@ -179,15 +176,14 @@ class _LoginWebPageState extends State ); } - Widget _buildDropdownField( - BuildContext context, AuthBloc loginBloc, Size size) { - final textEditingController = TextEditingController(); + Widget _buildDropdownField(BuildContext context, AuthBloc loginBloc, Size size) { + final TextEditingController 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, @@ -250,8 +246,7 @@ class _LoginWebPageState extends State 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, @@ -266,8 +261,7 @@ class _LoginWebPageState extends State ), 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. @@ -292,7 +286,7 @@ class _LoginWebPageState extends State mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - 'Email', + "Email", style: Theme.of(context) .textTheme .bodySmall! @@ -309,9 +303,10 @@ class _LoginWebPageState extends State 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), ), ), @@ -325,7 +320,7 @@ class _LoginWebPageState extends State mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - 'Password', + "Password", style: Theme.of(context) .textTheme .bodySmall! @@ -343,7 +338,7 @@ class _LoginWebPageState extends State controller: loginBloc.loginPasswordController, onFieldSubmitted: (value) { if (loginBloc.loginFormKey.currentState!.validate()) { - loginBloc.add(LoginButtonPressed( + loginBloc.add(LoginButtonPressed( username: loginBloc.loginEmailController.text, password: value, )); @@ -353,18 +348,17 @@ class _LoginWebPageState extends State }, 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, ), @@ -391,11 +385,11 @@ class _LoginWebPageState extends State )); }, 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), ), ), ], @@ -459,8 +453,7 @@ class _LoginWebPageState extends State ); } - Widget _buildSignInButton( - BuildContext context, AuthBloc loginBloc, Size size) { + Widget _buildSignInButton(BuildContext context, AuthBloc loginBloc, Size size) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, @@ -474,7 +467,7 @@ class _LoginWebPageState extends State fontSize: 14, color: loginBloc.checkValidate ? ColorsManager.whiteColors - : ColorsManager.whiteColors.withValues(alpha: 0.2), + : ColorsManager.whiteColors.withOpacity(0.2), )), onPressed: () { if (loginBloc.loginFormKey.currentState!.validate()) { @@ -501,8 +494,7 @@ class _LoginWebPageState extends State 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 01aed542..86d4a6b3 100644 --- a/lib/pages/common/access_device_table.dart +++ b/lib/pages/common/access_device_table.dart @@ -108,64 +108,66 @@ class _DynamicTableState extends State { child: Row( children: [ if (widget.withCheckBox) _buildSelectAllCheckbox(), - ...widget.headers.map(_buildTableHeaderCell), + ...widget.headers + .map((header) => _buildTableHeaderCell(header)), ], ), ), - if (widget.isEmpty) - Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, + widget.isEmpty + ? Expanded( + child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Column( + Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ - SvgPicture.asset(Assets.emptyTable), - const SizedBox( - height: 15, + 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), + ) + ], ), - Text( - // no password - widget.tableName == 'AccessManagement' - ? 'No Password ' - : 'No Devices', - style: Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: ColorsManager.grayColor), - ) ], ), ], ), - ], - ), - ) - 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)), - ], - ); - }, + ) + : 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)), + ], + ); + }, + ), + ), ), - ), - ), ], ), ), @@ -243,7 +245,7 @@ class _DynamicTableState extends State { } Widget _buildTableCell(String content, double size) { - final isBatteryLevel = content.endsWith('%'); + bool 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 2147760e..da6dcdc7 100644 --- a/lib/pages/common/buttons/cancel_button.dart +++ b/lib/pages/common/buttons/cancel_button.dart @@ -22,21 +22,17 @@ 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 61012434..ecca6138 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.withValues(alpha: 0.2); + : Colors.black.withOpacity(0.2); }), shape: WidgetStateProperty.all( RoundedRectangleBorder( diff --git a/lib/pages/common/curtain_toggle.dart b/lib/pages/common/curtain_toggle.dart index a1c99355..7b1551c5 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: ColoredBox( + child: Container( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.curtainIcon, @@ -52,7 +52,7 @@ class CurtainToggle extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: ColorsManager.dialogBlueTitle, onChanged: onChanged, ), ), diff --git a/lib/pages/common/custom_dialog.dart b/lib/pages/common/custom_dialog.dart index 78c4a43e..9899bda4 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,20 +40,14 @@ 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 de6da949..f23daa45 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 void Function(dynamic selectedRows)? onSelectionChanged; - final void Function(int rowIndex)? onSettingsPressed; + final Function(dynamic selectedRows)? onSelectionChanged; + final 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 (var i = 0; i < oldList.length; i++) { + for (int i = 0; i < oldList.length; i++) { if (oldList[i].length != newList[i].length) return false; - for (var j = 0; j < oldList[i].length; j++) { + for (int 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: ColoredBox( + child: Container( 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, }) { - final isBatteryLevel = content.endsWith('%'); + bool isBatteryLevel = content.endsWith('%'); double? batteryLevel; if (isBatteryLevel) { batteryLevel = double.tryParse(content.replaceAll('%', '').trim()); } - final isSettingsColumn = widget.headers[columnIndex] == 'Settings'; + bool 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.withValues(alpha: 0.17), + color: Colors.black.withOpacity(0.17), blurRadius: 14, offset: const Offset(0, 4), ), @@ -416,10 +416,11 @@ 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 afd98eef..1af23045 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.withValues(alpha: 0.8) + ? ColorsManager.blueColor.withOpacity(0.8) : Colors.transparent, width: 2.0, ), @@ -48,7 +48,7 @@ class FilterWidget extends StatelessWidget { tabs[index], style: TextStyle( color: isSelected - ? ColorsManager.blueColor.withValues(alpha: 0.8) + ? ColorsManager.blueColor.withOpacity(0.8) : Colors.black, ), ), diff --git a/lib/pages/common/hour_picker_dialog.dart b/lib/pages/common/hour_picker_dialog.dart index 2c5be850..01a87720 100644 --- a/lib/pages/common/hour_picker_dialog.dart +++ b/lib/pages/common/hour_picker_dialog.dart @@ -1,3 +1,5 @@ + + import 'package:flutter/material.dart'; class HourPickerDialog extends StatefulWidget { @@ -16,7 +18,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 @@ -26,7 +28,7 @@ class _HourPickerDialogState extends State { content: DropdownButton( value: selectedHour, // Show the currently selected hour items: List.generate(24, (index) { - final hour = index.toString().padLeft(2, '0'); + String hour = index.toString().padLeft(2, '0'); return DropdownMenuItem( value: '$hour:00', child: Text('$hour:00'), @@ -35,16 +37,14 @@ 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 f2062319..97656418 100644 --- a/lib/pages/common/info_dialog.dart +++ b/lib/pages/common/info_dialog.dart @@ -9,8 +9,7 @@ class InfoDialog extends StatelessWidget { final Size? size; final List? actions; - const InfoDialog({ - super.key, + InfoDialog({ 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 d96a4714..af5a7b0a 100644 --- a/lib/pages/device_managment/ac/bloc/ac_bloc.dart +++ b/lib/pages/device_managment/ac/bloc/ac_bloc.dart @@ -45,8 +45,7 @@ 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; @@ -72,20 +71,21 @@ class AcBloc extends Bloc { void _listenToChanges(deviceId) { try { final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - ref.onValue.listen((DatabaseEvent event) async { + final stream = ref.onValue; + + stream.listen((DatabaseEvent event) async { if (event.snapshot.value == null) return; - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List 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,10 +129,8 @@ 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())); @@ -192,8 +190,8 @@ class AcBloc extends Bloc { void _handleIncreaseTime(IncreaseTimeEvent event, Emitter emit) { if (state is! ACStatusLoaded) return; final currentState = state as ACStatusLoaded; - var newHours = scheduledHours; - var newMinutes = scheduledMinutes + 30; + int newHours = scheduledHours; + int newMinutes = scheduledMinutes + 30; newHours += newMinutes ~/ 60; newMinutes = newMinutes % 60; if (newHours > 23) { @@ -215,7 +213,7 @@ class AcBloc extends Bloc { ) { if (state is! ACStatusLoaded) return; final currentState = state as ACStatusLoaded; - var totalMinutes = (scheduledHours * 60) + scheduledMinutes; + int totalMinutes = (scheduledHours * 60) + scheduledMinutes; totalMinutes = (totalMinutes - 30).clamp(0, 1440); scheduledHours = totalMinutes ~/ 60; scheduledMinutes = totalMinutes % 60; @@ -288,7 +286,7 @@ class AcBloc extends Bloc { void _startCountdownTimer(Emitter emit) { _countdownTimer?.cancel(); - var totalSeconds = (scheduledHours * 3600) + (scheduledMinutes * 60); + int totalSeconds = (scheduledHours * 3600) + (scheduledMinutes * 60); _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) { if (totalSeconds > 0) { @@ -338,26 +336,32 @@ 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 217199ea..9764f3ed 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; - const AcStatusUpdated(this.deviceStatus); + AcStatusUpdated(this.deviceStatus); } class AcFetchBatchStatusEvent extends AcsEvent { @@ -77,6 +77,8 @@ class AcFactoryResetEvent extends AcsEvent { List get props => [deviceId, factoryResetModel]; } + + class OnClose extends AcsEvent {} class IncreaseTimeEvent extends AcsEvent { @@ -93,7 +95,8 @@ 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 a8985957..3e1e2c68 100644 --- a/lib/pages/device_managment/ac/bloc/ac_state.dart +++ b/lib/pages/device_managment/ac/bloc/ac_state.dart @@ -18,7 +18,6 @@ class ACStatusLoaded extends AcsState { final DateTime timestamp; final int scheduledHours; final int scheduledMinutes; - @override final bool isTimerActive; ACStatusLoaded({ @@ -73,3 +72,5 @@ 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 32a7de0c..6afc778d 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 var countdown1 = 0; + late int _countdown1 = 0; - for (final status in jsonList) { + for (var 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 5b03ae3d..aad0669b 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,8 +15,7 @@ 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; @@ -101,8 +100,8 @@ class AcDeviceBatchControlView extends StatelessWidget ), Text( 'h', - style: context.textTheme.bodySmall! - .copyWith(color: ColorsManager.blackColor), + style: + context.textTheme.bodySmall!.copyWith(color: ColorsManager.blackColor), ), Text( '30', @@ -149,8 +148,7 @@ class AcDeviceBatchControlView extends StatelessWidget 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 b779a5ca..a882e6d5 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 11724f1d..be7441df 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) { - final double doubleValue = value.toDouble(); + double doubleValue = value.toDouble(); return doubleValue > 99 ? doubleValue / 10 : doubleValue; } else { throw ArgumentError('Invalid value type: Expected int or double'); @@ -75,48 +75,35 @@ class _CurrentTempState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - 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( + widget.isBatch == true + ? Text( + 'Set Temperature', + style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey), + ) + : Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - (widget.currentTemp > 99 - ? widget.currentTemp / 10 - : widget.currentTemp) - .toString(), - style: Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: Colors.grey), + '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, + ) + ], ), - 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 8e592d48..4e81ec09 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( - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: 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 7c5f9494..fdd51164 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) { - final double doubleValue = value.toDouble(); + double doubleValue = value.toDouble(); return doubleValue > 99 ? doubleValue / 10 : doubleValue; } else { throw ArgumentError('Invalid value type: Expected int or double'); @@ -60,7 +60,6 @@ class _CurrentTempState extends State { ); }); } - @override void didUpdateWidget(CurrentTemp oldWidget) { super.didUpdateWidget(oldWidget); @@ -70,7 +69,6 @@ class _CurrentTempState extends State { }); } } - @override void dispose() { _debounce?.cancel(); @@ -89,10 +87,7 @@ 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, @@ -100,14 +95,8 @@ 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 0cf13036..05e82f1f 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; - final List _selectedDevices = []; + List _selectedDevices = []; List _filteredDevices = []; String currentProductName = ''; String? currentCommunity; @@ -37,21 +37,20 @@ class DeviceManagementBloc FetchDevices event, Emitter emit) async { emit(DeviceManagementLoading()); try { - var devices = []; + List devices = []; _devices.clear(); - final spaceBloc = event.context.read(); - final projectUuid = await ProjectManager.getProjectUUID() ?? ''; + var 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 (final community in spaceBloc.state.selectedCommunities) { - final spacesList = + for (var community in spaceBloc.state.selectedCommunities) { + List spacesList = spaceBloc.state.selectedCommunityAndSpaces[community] ?? []; - for (final space in spacesList) { - devices.addAll(await DevicesManagementApi() - .fetchDevices(community, space, projectUuid)); + for (var space in spacesList) { + devices.addAll(await DevicesManagementApi().fetchDevices( + community, space, projectUuid)); } } } @@ -74,7 +73,7 @@ class DeviceManagementBloc } } - Future _onFilterDevices( + void _onFilterDevices( FilterDevices event, Emitter emit) async { if (_devices.isNotEmpty) { _filteredDevices = List.from(_devices.where((device) { @@ -166,9 +165,9 @@ class DeviceManagementBloc _selectedDevices.add(event.selectedDevice); } - final clonedSelectedDevices = List.from(_selectedDevices); + List clonedSelectedDevices = List.from(_selectedDevices); - final isControlButtonEnabled = + bool isControlButtonEnabled = _checkIfControlButtonEnabled(clonedSelectedDevices); if (state is DeviceManagementLoaded) { @@ -198,8 +197,8 @@ class DeviceManagementBloc void _onUpdateSelection( UpdateSelection event, Emitter emit) { - final selectedDevices = []; - var devicesToSelectFrom = []; + List selectedDevices = []; + List devicesToSelectFrom = []; if (state is DeviceManagementLoaded) { devicesToSelectFrom = (state as DeviceManagementLoaded).devices; @@ -207,7 +206,7 @@ class DeviceManagementBloc devicesToSelectFrom = (state as DeviceManagementFiltered).filteredDevices; } - for (var i = 0; i < event.selectedRows.length; i++) { + for (int i = 0; i < event.selectedRows.length; i++) { if (event.selectedRows[i]) { selectedDevices.add(devicesToSelectFrom[i]); } @@ -295,7 +294,7 @@ class DeviceManagementBloc currentCommunity = event.community; currentUnitName = event.unitName; - final devicesToSearch = _filteredDevices; + List 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 25a8342b..5586a310 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,7 +18,6 @@ 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'; @@ -40,6 +39,8 @@ 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) { @@ -106,7 +107,7 @@ mixin RouteControlsBasedCode { case 'SOS': return SosDeviceControlsView(device: device); - case 'NCPS': + case 'NCPS': return FlushMountedPresenceSensorControlView(device: device); default: return const SizedBox(); @@ -131,133 +132,76 @@ 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 bf94524b..96195f76 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,12 +5,7 @@ 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 a14b14d3..808a683f 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 */ - final type = devicesTypesMap[productType] ?? DeviceType.Other; - var tempIcon = ''; + DeviceType type = devicesTypesMap[productType] ?? DeviceType.Other; + String tempIcon = ''; if (type == DeviceType.LightBulb) { tempIcon = Assets.lightBulb; } else if (type == DeviceType.CeilingSensor || @@ -441,9 +441,13 @@ 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: @@ -561,23 +565,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 decfa05f..1b5685a1 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,3 +58,4 @@ 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 abd06cd0..f4baad0c 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) { - var devicesToShow = []; - var selectedIndex = 0; - var onlineCount = 0; - var offlineCount = 0; - var lowBatteryCount = 0; - var isControlButtonEnabled = false; - var selectedDevices = []; + List devicesToShow = []; + int selectedIndex = 0; + int onlineCount = 0; + int offlineCount = 0; + int lowBatteryCount = 0; + bool isControlButtonEnabled = false; + List selectedDevices = []; if (state is DeviceManagementLoaded) { devicesToShow = state.devices; @@ -194,23 +194,18 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout { device.name ?? '', device.productName ?? '', device.uuid ?? '', - if (device.spaces != null && - device.spaces!.isNotEmpty) - device.spaces![0].spaceName - else - '', + (device.spaces != null && + device.spaces!.isNotEmpty) + ? device.spaces![0].spaceName + : '', combinedSpaceNames, - if (device.batteryLevel != null) - '${device.batteryLevel}%' - else - '-', + device.batteryLevel != null + ? '${device.batteryLevel}%' + : '-', formatDateTime( DateTime.fromMillisecondsSinceEpoch( (device.createTime ?? 0) * 1000)), - if (device.online == true) - 'Online' - else - 'Offline', + device.online == true ? 'Online' : 'Offline', formatDateTime( DateTime.fromMillisecondsSinceEpoch( (device.updateTime ?? 0) * 1000)), @@ -248,7 +243,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 99378a86..6440d18f 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 0d5e59b2..42387e57 100644 --- a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart +++ b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_bloc.dart @@ -37,8 +37,7 @@ 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); @@ -55,12 +54,11 @@ 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); @@ -180,8 +178,7 @@ 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 e296e1b9..1dc7d8d7 100644 --- a/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart +++ b/lib/pages/device_managment/ceiling_sensor/bloc/ceiling_event.dart @@ -85,6 +85,8 @@ 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 c05b4e09..08a65a11 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,53 +26,48 @@ class CeilingSensorModel { }); factory CeilingSensorModel.fromJson(List jsonList) { - 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; + 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; try { - for (final status in jsonList) { + for (var 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; } } @@ -81,15 +76,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 3f57e7a1..9b5ab360 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,8 +12,7 @@ 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; @@ -29,12 +28,11 @@ class CeilingSensorBatchControlView extends StatelessWidget )..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')); }, @@ -42,8 +40,8 @@ class CeilingSensorBatchControlView extends StatelessWidget ); } - 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, @@ -118,8 +116,7 @@ class CeilingSensorBatchControlView extends StatelessWidget 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 f75ff8b4..749a7729 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_bloc.dart @@ -34,8 +34,7 @@ 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)); @@ -55,7 +54,7 @@ class CurtainBloc extends Bloc { final statusList = []; if (data['status'] != null) { - for (final element in data['status']) { + for (var element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -122,8 +121,7 @@ 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 d8c85ccd..dd6700f9 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_event.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_event.dart @@ -60,8 +60,7 @@ 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 72d974f1..dfe11c2a 100644 --- a/lib/pages/device_managment/curtain/bloc/curtain_state.dart +++ b/lib/pages/device_managment/curtain/bloc/curtain_state.dart @@ -1,6 +1,7 @@ + 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 0a400c38..908415d5 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) { - final statusList = json['status'] as List; - final status = statusList.map((i) => Status.fromJson(i)).toList(); + var statusList = json['status'] as List; + List 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 ccb9613d..41dcaf9e 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,8 +10,7 @@ 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; @@ -19,8 +18,8 @@ class CurtainBatchStatusView extends StatelessWidget @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 73e31f89..c996cf72 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,13 +2,12 @@ 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/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/bloc/setting_bloc_state.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 { @@ -38,7 +37,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'; } @@ -67,8 +66,8 @@ class SettingDeviceBloc extends Bloc { DeviceSettingInitialInfo event, Emitter emit) async { try { emit(DeviceSettingsLoading()); - final response = await DevicesManagementApi.getDeviceInfo(deviceId); - final deviceInfo = DeviceInfoModel.fromJson(response); + var response = await DevicesManagementApi.getDeviceInfo(deviceId); + DeviceInfoModel deviceInfo = DeviceInfoModel.fromJson(response); nameController.text = deviceInfo.name; emit(DeviceSettingsUpdate( deviceName: nameController.text, @@ -93,7 +92,9 @@ 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(); @@ -105,7 +106,7 @@ class SettingDeviceBloc extends Bloc { )); } - Future _deleteDevice( + void _deleteDevice( SettingBlocDeleteDevice event, Emitter emit) async { try { emit(DeviceSettingsLoading()); @@ -122,7 +123,7 @@ class SettingDeviceBloc extends Bloc { } } - Future _onAssignDevice( + void _onAssignDevice( SettingBlocAssignRoom event, Emitter emit) async { try { emit(DeviceSettingsLoading()); @@ -142,7 +143,7 @@ class SettingDeviceBloc extends Bloc { } } - Future _fetchRooms( + void _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 cea5bea6..48458b3b 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 - .withValues(alpha: 0.7), + .withOpacity(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 - .withValues(alpha: 0.5), + backgroundColor: + ColorsManager.grayBorder.withOpacity(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: const InputDecoration( + decoration: 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: ColoredBox( - color: Colors.black.withValues(alpha: 0.1), + child: Container( + color: Colors.black.withOpacity(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 f4ab1cd0..9d3f4036 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) { - final devices = []; + List devices = []; if (json['devices'] != null) { - for (final device in json['devices']) { + for (var 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 2b909a85..28350d4d 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({ - super.key, + Key? 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: const Color(0xFF2962FF), + activeColor: 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 a42f4352..f83ced1a 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,15 +22,17 @@ class DoorLockBloc extends Bloc { on(_onStatusUpdated); } - void _listenToChanges(deviceId) { + _listenToChanges(deviceId) { try { - final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; stream.listen((DatabaseEvent event) { - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List 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 8bbb3c03..39c4ca16 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,3 +1,4 @@ + 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 9dca688b..cda512c5 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 (final status in jsonList) { + for (var 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 e2d85df9..b28737fc 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,8 +7,7 @@ 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 6bf8acf6..e8e3066e 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.withValues(alpha: 0.5), + color: Colors.grey.withOpacity(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 f4b933ae..aea800dd 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< - FlushMountedPresenceSensorEvent, FlushMountedPresenceSensorState> { +class FlushMountedPresenceSensorBloc + extends Bloc { final String deviceId; final ControlDeviceService controlDeviceService; final BatchControlDevicesService batchControlDevicesService; @@ -54,7 +54,7 @@ class FlushMountedPresenceSensorBloc extends Bloc< ); } - Future _onFlushMountedPresenceSensorFetchStatusEvent( + void _onFlushMountedPresenceSensorFetchStatusEvent( FlushMountedPresenceSensorFetchStatusEvent event, Emitter emit, ) async { @@ -76,8 +76,7 @@ class FlushMountedPresenceSensorBloc extends Bloc< ) 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) { @@ -92,9 +91,9 @@ class FlushMountedPresenceSensorBloc extends Bloc< ); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value! as Map; + final eventsMap = event.snapshot.value as Map; - final statusList = []; + List statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -114,7 +113,7 @@ class FlushMountedPresenceSensorBloc extends Bloc< } } - Future _onFlushMountedPresenceSensorChangeValueEvent( + void _onFlushMountedPresenceSensorChangeValueEvent( FlushMountedPresenceSensorChangeValueEvent event, Emitter emit, ) async { @@ -197,8 +196,7 @@ class FlushMountedPresenceSensorBloc extends Bloc< 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 e7fe8156..08a01615 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,8 +59,7 @@ 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 e88a9ad8..0fef07f2 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,8 +13,7 @@ class FlushMountedPresenceSensorInitialState class FlushMountedPresenceSensorLoadingInitialState extends FlushMountedPresenceSensorState {} -class FlushMountedPresenceSensorUpdateState - extends FlushMountedPresenceSensorState { +class FlushMountedPresenceSensorUpdateState extends FlushMountedPresenceSensorState { final FlushMountedPresenceSensorModel model; const FlushMountedPresenceSensorUpdateState({required this.model}); @@ -31,8 +30,7 @@ class FlushMountedPresenceSensorLoadingNewSate List get props => [model]; } -class FlushMountedPresenceSensorFailedState - extends FlushMountedPresenceSensorState { +class FlushMountedPresenceSensorFailedState extends FlushMountedPresenceSensorState { final String error; const FlushMountedPresenceSensorFailedState({required this.error}); @@ -60,8 +58,7 @@ class FlushMountedPresenceSensorDeviceReportsState class FlushMountedPresenceSensorDeviceReportsFailedState extends FlushMountedPresenceSensorState { - const FlushMountedPresenceSensorDeviceReportsFailedState( - {required this.error}); + const FlushMountedPresenceSensorDeviceReportsFailedState({required this.error}); final String error; @@ -71,8 +68,7 @@ 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 e1458dc9..e842f36b 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,10 +9,8 @@ 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 106a9942..bf97005d 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) { - 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; + 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; - for (final status in jsonList) { + for (var status in jsonList) { switch (status.code) { case codePresenceState: presenceState = status.value ?? 'presence'; @@ -97,3 +97,7 @@ 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 589b6b0e..2860e5cc 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,14 +66,13 @@ 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), @@ -115,14 +114,13 @@ 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(), @@ -130,17 +128,16 @@ 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, + value: (model.presenceDelay / 10).toDouble(), title: 'Target Confirm Time:', description: 's', minValue: 0.0, @@ -157,7 +154,7 @@ class FlushMountedPresenceSensorBatchControlView extends StatelessWidget ), ), PresenceUpdateData( - value: model.noneDelay / 10, + value: ((model.noneDelay / 10).toDouble()), 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 098dbb61..08ad809d 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,8 +15,7 @@ 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; @@ -38,9 +37,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 @@ -57,8 +56,7 @@ 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); @@ -107,13 +105,12 @@ 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), @@ -153,13 +150,12 @@ 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(), @@ -167,16 +163,15 @@ 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, + value: (model.presenceDelay / 10).toDouble(), valuesPercision: 1, title: 'Target Confirm Time:', description: 's', @@ -192,7 +187,7 @@ class FlushMountedPresenceSensorControlView extends StatelessWidget ), ), PresenceUpdateData( - value: model.noneDelay / 10, + value: (model.noneDelay / 10).toDouble(), 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 48fd146b..28a7e33b 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,6 +2,7 @@ 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'; @@ -41,15 +42,17 @@ class GarageDoorBloc extends Bloc { on(_onEditSchedule); on(_onStatusUpdated); } - void _listenToChanges(deviceId) { + _listenToChanges(deviceId) { try { - final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; stream.listen((DatabaseEvent event) { - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); @@ -69,11 +72,11 @@ class GarageDoorBloc extends Bloc { emit(GarageDoorLoadedState(status: deviceStatus)); } - Future _fetchGarageDoorStatus( + void _fetchGarageDoorStatus( GarageDoorInitialEvent event, Emitter emit) async { emit(GarageDoorLoadingState()); try { - final response = + var response = await DevicesManagementApi().getDeviceStatus(event.deviceId); deviceStatus = GarageDoorStatusModel.fromJson(deviceId, response.status); _listenToChanges(deviceId); @@ -100,13 +103,13 @@ class GarageDoorBloc extends Bloc { Future _addSchedule( AddGarageDoorScheduleEvent event, Emitter emit) async { try { - final newSchedule = ScheduleEntry( + ScheduleEntry newSchedule = ScheduleEntry( category: event.category, time: formatTimeOfDayToISO(event.time), function: Status(code: 'doorcontact_state', value: event.functionOn), days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - final success = + bool success = await DevicesManagementApi().addScheduleRecord(newSchedule, deviceId); if (success) { add(FetchGarageDoorSchedulesEvent( @@ -153,7 +156,7 @@ class GarageDoorBloc extends Bloc { } return schedule; }).toList(); - final success = await DevicesManagementApi().updateScheduleRecord( + bool success = await DevicesManagementApi().updateScheduleRecord( enable: event.enable, uuid: deviceStatus.uuid, scheduleId: event.scheduleId, @@ -172,7 +175,7 @@ class GarageDoorBloc extends Bloc { Future _deleteSchedule(DeleteGarageDoorScheduleEvent event, Emitter emit) async { try { - final success = await DevicesManagementApi() + bool success = await DevicesManagementApi() .deleteScheduleRecord(deviceStatus.uuid, event.scheduleId); if (success) { final updatedSchedules = deviceStatus.schedules @@ -192,7 +195,7 @@ class GarageDoorBloc extends Bloc { Emitter emit) async { emit(ScheduleGarageLoadingState()); try { - final schedules = await DevicesManagementApi() + List schedules = await DevicesManagementApi() .getDeviceSchedules(deviceStatus.uuid, event.category); deviceStatus = deviceStatus.copyWith(schedules: schedules); emit( @@ -223,7 +226,7 @@ class GarageDoorBloc extends Bloc { UpdateSelectedDayEvent event, Emitter emit) async { final currentState = state; if (currentState is GarageDoorLoadedState) { - final updatedDays = List.from(currentState.selectedDays); + List updatedDays = List.from(currentState.selectedDays); updatedDays[event.dayIndex] = event.isSelected; emit(currentState.copyWith( selectedDays: updatedDays, selectedTime: currentState.selectedTime)); @@ -261,8 +264,9 @@ class GarageDoorBloc extends Bloc { .subtract(const Duration(days: 30)) .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final records = await DevicesManagementApi.getDeviceReportsByDate( - event.deviceId, 'switch_1', from.toString(), to.toString()); + final DeviceReport records = + await DevicesManagementApi.getDeviceReportsByDate( + event.deviceId, 'switch_1', from.toString(), to.toString()); emit(GarageDoorReportsState(deviceReport: records)); } catch (e) { emit(GarageDoorReportsFailedState(error: e.toString())); @@ -348,12 +352,12 @@ class GarageDoorBloc extends Bloc { } } - Future _increaseDelay( + void _increaseDelay( IncreaseGarageDoorDelayEvent event, Emitter emit) async { // if (deviceStatus.countdown1 != 0) { try { deviceStatus = deviceStatus.copyWith( - delay: deviceStatus.delay + const Duration(minutes: 10)); + delay: deviceStatus.delay + Duration(minutes: 10)); emit(GarageDoorLoadedState(status: deviceStatus)); add(GarageDoorControlEvent( deviceId: deviceId, @@ -365,13 +369,13 @@ class GarageDoorBloc extends Bloc { // } } - Future _decreaseDelay( + void _decreaseDelay( DecreaseGarageDoorDelayEvent event, Emitter emit) async { // if (deviceStatus.countdown1 != 0) { try { if (deviceStatus.delay.inMinutes > 10) { deviceStatus = deviceStatus.copyWith( - delay: deviceStatus.delay - const Duration(minutes: 10)); + delay: deviceStatus.delay - Duration(minutes: 10)); } emit(GarageDoorLoadedState(status: deviceStatus)); add(GarageDoorControlEvent( @@ -384,7 +388,7 @@ class GarageDoorBloc extends Bloc { //} } - Future _garageDoorControlEvent( + void _garageDoorControlEvent( GarageDoorControlEvent event, Emitter emit) async { final oldValue = event.code == 'countdown_1' ? deviceStatus.countdown1 @@ -485,14 +489,14 @@ class GarageDoorBloc extends Bloc { FutureOr _onEditSchedule( EditGarageDoorScheduleEvent event, Emitter emit) async { try { - final newSchedule = ScheduleEntry( + ScheduleEntry 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), ); - final success = await DevicesManagementApi() + bool 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 4600a685..7b133d45 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,10 +77,9 @@ class GarageDoorDialogHelper { backgroundColor: ColorsManager.boxColor, borderRadius: 15, onPressed: () async { - final time = await showTimePicker( + TimeOfDay? 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( @@ -100,9 +99,7 @@ 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, ), @@ -117,8 +114,7 @@ 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), ], @@ -192,9 +188,9 @@ class GarageDoorDialogHelper { static List _convertDaysStringToBooleans(List selectedDays) { final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - final daysBoolean = List.filled(7, false); + List daysBoolean = List.filled(7, false); - for (var i = 0; i < daysOfWeek.length; i++) { + for (int i = 0; i < daysOfWeek.length; i++) { if (selectedDays.contains(daysOfWeek[i])) { daysBoolean[i] = true; } @@ -203,9 +199,7 @@ 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( @@ -215,9 +209,7 @@ class GarageDoorDialogHelper { Checkbox( value: selectedDays[index], onChanged: (bool? value) { - context - .read() - .add(UpdateSelectedDayEvent(index, value!)); + context.read().add(UpdateSelectedDayEvent(index, value!)); }, ), Text(dayLabels[index]), @@ -227,23 +219,19 @@ 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'), @@ -252,9 +240,7 @@ 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'), @@ -311,17 +297,13 @@ 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); @@ -329,11 +311,8 @@ 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', @@ -342,10 +321,9 @@ 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", ), ); }), @@ -370,17 +348,13 @@ 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 4c991a9f..60d37d9f 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; - final schedules = []; // Initialize schedules + List schedules = []; // Initialize schedules - for (final status in jsonList) { + for (var 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 d21db9db..9b3159bb 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,11 +11,10 @@ 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({super.key, required this.deviceIds}); + const GarageDoorBatchControlView({Key? key, required this.deviceIds}) : super(key: key); @override Widget build(BuildContext context) { @@ -38,8 +37,7 @@ class GarageDoorBatchControlView extends StatelessWidget ); } - 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 403beb85..843bac9b 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,3 +1,4 @@ +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'; @@ -7,8 +8,7 @@ class OpeningAndClosingTimeDialogBody extends StatefulWidget { final ValueChanged onDurationChanged; final GarageDoorBloc bloc; - const OpeningAndClosingTimeDialogBody({ - super.key, + OpeningAndClosingTimeDialogBody({ 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 238b7ad7..07cd9c7a 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,8 +26,7 @@ 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( @@ -51,21 +50,17 @@ 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)); } @@ -83,8 +78,7 @@ 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( @@ -118,8 +112,7 @@ 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), ], ), ), @@ -141,8 +134,7 @@ 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( @@ -160,8 +152,7 @@ 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, @@ -169,9 +160,7 @@ 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( @@ -181,24 +170,18 @@ 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, @@ -206,8 +189,7 @@ class ScheduleGarageTableWidget extends StatelessWidget { }, child: Text( 'Delete', - style: context.textTheme.bodySmall! - .copyWith(color: ColorsManager.blueColor), + style: context.textTheme.bodySmall!.copyWith(color: ColorsManager.blueColor), ), ), ], @@ -219,8 +201,8 @@ class ScheduleGarageTableWidget extends StatelessWidget { String _getSelectedDays(List selectedDays) { final days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - final selectedDaysStr = []; - for (var i = 0; i < selectedDays.length; i++) { + List selectedDaysStr = []; + for (int 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 786b3fa6..e5819e89 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 3f8939dd..7b6e4690 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,8 +35,7 @@ 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 f2805d39..491be37b 100644 --- a/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart +++ b/lib/pages/device_managment/garage_door/widgets/seconds_picker.dart @@ -4,8 +4,7 @@ class SecondsPicker extends StatefulWidget { final int initialSeconds; final ValueChanged onSecondsChanged; - const SecondsPicker({ - super.key, + SecondsPicker({ 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 2eff275d..541ab9e4 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 { - const TimeOutAlarmDialogBody(this.bloc, {super.key}); + TimeOutAlarmDialogBody(this.bloc); 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 66c33fbe..e14672ae 100644 --- a/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart +++ b/lib/pages/device_managment/gateway/bloc/gate_way_bloc.dart @@ -16,12 +16,10 @@ class GateWayBloc extends Bloc { on(_onFactoryReset); } - FutureOr _getGatWayById( - GatWayById event, Emitter emit) async { + FutureOr _getGatWayById(GatWayById event, Emitter emit) async { emit(GatewayLoadingState()); try { - final devicesList = - await DevicesManagementApi.getDevicesByGatewayId(event.getWayId); + List devicesList = await DevicesManagementApi.getDevicesByGatewayId(event.getWayId); emit(UpdateGatewayState(list: devicesList)); } catch (e) { @@ -30,8 +28,7 @@ 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 a9fe13ba..f3a08a18 100644 --- a/lib/pages/device_managment/gateway/view/gateway_batch_control.dart +++ b/lib/pages/device_managment/gateway/view/gateway_batch_control.dart @@ -6,8 +6,7 @@ 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; @@ -39,8 +38,7 @@ class GatewayBatchControlView extends StatelessWidget 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 8f5d0674..d674e4d8 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 1a2d0ab1..493e3037 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,15 +159,17 @@ class MainDoorSensorBloc } } - void _listenToChanges(deviceId) { + _listenToChanges(deviceId) { try { - final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; stream.listen((DatabaseEvent event) { - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List 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 8dcc221a..569cfa11 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,7 +1,8 @@ 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 => []; @@ -74,7 +75,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 65518938..52dda7a3 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 var doorContactState = false; - late var batteryPercentage = 0; + late bool doorContactState = false; + late int batteryPercentage = 0; - for (final status in jsonList) { + for (var 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 723cb2f0..ecdb367a 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,8 +12,7 @@ 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; @@ -21,12 +20,10 @@ class MainDoorSensorControlView extends StatelessWidget @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); @@ -35,15 +32,12 @@ class MainDoorSensorControlView extends StatelessWidget 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()); @@ -52,8 +46,7 @@ class MainDoorSensorControlView extends StatelessWidget )); } - Widget _buildStatusControls( - BuildContext context, MainDoorSensorStatusModel status) { + Widget _buildStatusControls(BuildContext context, MainDoorSensorStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -78,9 +71,7 @@ class MainDoorSensorControlView extends StatelessWidget icon: Assets.openCloseDoor, onTap: () {}, status: status.doorContactState, - textColor: status.doorContactState - ? ColorsManager.red - : ColorsManager.blackColor, + textColor: status.doorContactState ? ColorsManager.red : ColorsManager.blackColor, paddingAmount: 8, ), IconNameStatusContainer( @@ -88,9 +79,7 @@ class MainDoorSensorControlView extends StatelessWidget 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 e14321dd..bbebabaa 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,8 +27,7 @@ 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 8e9cc8cd..ac66b315 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: const EdgeInsets.all(1), + padding: 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 8de84264..c1e976ab 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,11 +39,9 @@ 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())); @@ -64,7 +62,7 @@ class OneGangGlassSwitchBloc final statusList = []; if (data['status'] != null) { - for (final element in data['status']) { + for (var element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -74,8 +72,7 @@ class OneGangGlassSwitchBloc } } if (statusList.isNotEmpty) { - final newStatus = - OneGangGlassStatusModel.fromJson(deviceId, statusList); + final newStatus = OneGangGlassStatusModel.fromJson(deviceId, statusList); if (newStatus != deviceStatus) { deviceStatus = newStatus; if (!isClosed) { @@ -143,10 +140,9 @@ 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 dd8a1140..39c96dd0 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 (final status in jsonList) { + for (var status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; @@ -46,6 +46,5 @@ 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 5f88768a..307e61da 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,19 +8,16 @@ 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) { @@ -37,8 +34,7 @@ class OneGangGlassSwitchBatchControlView extends StatelessWidget ); } - 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 2c376ad6..997be513 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,8 +7,7 @@ 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}); @@ -17,8 +16,7 @@ class OneGangGlassSwitchControlView extends StatelessWidget 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) { @@ -35,8 +33,7 @@ class OneGangGlassSwitchControlView extends StatelessWidget ); } - Widget _buildStatusControls( - BuildContext context, OneGangGlassStatusModel status) { + Widget _buildStatusControls(BuildContext context, OneGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -59,7 +56,7 @@ class OneGangGlassSwitchControlView extends StatelessWidget 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 cf22faba..59eccfe9 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,8 +10,7 @@ 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; @@ -36,11 +35,9 @@ class WallLightSwitchBloc ) async { emit(WallLightSwitchLoading()); try { - final status = - await DevicesManagementApi().getDeviceStatus(event.deviceId); + final status = await DevicesManagementApi().getDeviceStatus(event.deviceId); _listenToChanges(event.deviceId, emit); - deviceStatus = - WallLightStatusModel.fromJson(event.deviceId, status.status); + deviceStatus = WallLightStatusModel.fromJson(event.deviceId, status.status); emit(WallLightSwitchStatusLoaded(deviceStatus)); } catch (e) { emit(WallLightSwitchError(e.toString())); @@ -61,7 +58,7 @@ class WallLightSwitchBloc final statusList = []; if (data['status'] != null) { - for (final element in data['status']) { + for (var element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -139,8 +136,7 @@ class WallLightSwitchBloc ) async { emit(WallLightSwitchLoading()); try { - final status = - await DevicesManagementApi().getBatchStatus(event.devicesIds); + final status = await DevicesManagementApi().getBatchStatus(event.devicesIds); deviceStatus = WallLightStatusModel.fromJson(event.devicesIds.first, status.status); emit(WallLightSwitchStatusLoaded(deviceStatus)); diff --git a/lib/pages/device_managment/one_gang_switch/models/wall_light_status_model.dart b/lib/pages/device_managment/one_gang_switch/models/wall_light_status_model.dart index caf961f7..b479c71d 100644 --- a/lib/pages/device_managment/one_gang_switch/models/wall_light_status_model.dart +++ b/lib/pages/device_managment/one_gang_switch/models/wall_light_status_model.dart @@ -15,7 +15,7 @@ class WallLightStatusModel { late bool switch1; late int countDown; - for (final status in jsonList) { + for (var status in jsonList) { switch (status.code) { case 'switch_1': switch1 = status.value ?? false; diff --git a/lib/pages/device_managment/one_gang_switch/view/wall_light_batch_control.dart b/lib/pages/device_managment/one_gang_switch/view/wall_light_batch_control.dart index e7a188c2..7fe57429 100644 --- a/lib/pages/device_managment/one_gang_switch/view/wall_light_batch_control.dart +++ b/lib/pages/device_managment/one_gang_switch/view/wall_light_batch_control.dart @@ -10,8 +10,7 @@ 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 WallLightBatchControlView extends StatelessWidget - with HelperResponsiveLayout { +class WallLightBatchControlView extends StatelessWidget with HelperResponsiveLayout { const WallLightBatchControlView({super.key, required this.deviceIds}); final List deviceIds; @@ -19,17 +18,15 @@ class WallLightBatchControlView extends StatelessWidget @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()); @@ -39,8 +36,7 @@ class WallLightBatchControlView extends StatelessWidget ); } - Widget _buildStatusControls( - BuildContext context, WallLightStatusModel status) { + Widget _buildStatusControls(BuildContext context, WallLightStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -82,8 +78,7 @@ class WallLightBatchControlView extends StatelessWidget 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 4cc0dbf3..24c5138f 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,46 +215,33 @@ class SmartPowerBloc extends Bloc { SmartPowerFetchDeviceEvent event, Emitter emit) async { emit(SmartPowerLoading()); try { - final status = + var 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()); @@ -318,7 +305,8 @@ class SmartPowerBloc extends Bloc { try { final response = await DevicesManagementApi().getPowerStatus(event.devicesIds); - final deviceStatus = PowerClampBatchModel.fromJson(response); + PowerClampBatchModel deviceStatus = + PowerClampBatchModel.fromJson(response); emit(SmartPowerLoadBatchControll(deviceStatus)); } catch (e) { @@ -429,15 +417,15 @@ class SmartPowerBloc extends Bloc { } Future selectMonthAndYear(BuildContext context) async { - var selectedYear = DateTime.now().year; - var selectedMonth = DateTime.now().month; + int selectedYear = DateTime.now().year; + int selectedMonth = DateTime.now().month; - final yearController = + FixedExtentScrollController yearController = FixedExtentScrollController(initialItem: selectedYear - 1905); - final monthController = + FixedExtentScrollController monthController = FixedExtentScrollController(initialItem: selectedMonth - 1); - return showDialog( + return await showDialog( context: context, builder: (BuildContext context) { return Column( @@ -549,11 +537,11 @@ class SmartPowerBloc extends Bloc { } Future selectYear(BuildContext context) async { - var selectedYear = DateTime.now().year; - final yearController = + int selectedYear = DateTime.now().year; + FixedExtentScrollController yearController = FixedExtentScrollController(initialItem: selectedYear - 1905); - return showDialog( + return await showDialog( context: context, builder: (BuildContext context) { return Column( @@ -634,9 +622,9 @@ class SmartPowerBloc extends Bloc { Future dayMonthYearPicker({ required BuildContext context, }) async { - var selectedDate = DateTime.now(); + DateTime selectedDate = DateTime.now(); - return showDialog( + return await showDialog( context: context, builder: (BuildContext context) { return Column( @@ -698,7 +686,7 @@ class SmartPowerBloc extends Bloc { String formattedDate = DateFormat('yyyy/MM/dd').format(DateTime.now()); - Future checkDayMonthYearSelected( + void checkDayMonthYearSelected( SelectDateEvent event, Emitter emit) async { Future Function(BuildContext context)? dateSelector; String dateFormat; @@ -710,11 +698,15 @@ class SmartPowerBloc extends Bloc { dateFormat = 'yyyy/MM/dd'; break; case 1: - dateSelector = selectMonthAndYear; + dateSelector = (context) { + return selectMonthAndYear(context); + }; dateFormat = 'yyyy-MM'; break; case 2: - dateSelector = selectYear; + dateSelector = (context) { + return selectYear(context); + }; dateFormat = 'yyyy'; break; default: @@ -751,7 +743,7 @@ class SmartPowerBloc extends Bloc { .toList(); } else if (event.viewType == 'Month') { formattedDate = - '${event.selectedDate.year}-${getMonthShortName(event.selectedDate.month)}'; + "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}"; filteredRecords = record .where((record) => @@ -760,7 +752,7 @@ class SmartPowerBloc extends Bloc { .toList(); } else if (event.viewType == 'Day') { formattedDate = - '${event.selectedDate.year}-${getMonthShortName(event.selectedDate.month)}-${event.selectedDate.day}'; + "${event.selectedDate.year.toString()}-${getMonthShortName(event.selectedDate.month)}-${event.selectedDate.day}"; filteredRecords = record .where((record) => @@ -792,11 +784,11 @@ class SmartPowerBloc extends Bloc { String endChartDate = ''; - Future selectDateRange() async { - final startDate = dateTime!; - final endDate = DateTime(startDate.year, startDate.month + 1, 1) + void selectDateRange() async { + DateTime startDate = dateTime!; + DateTime endDate = DateTime(startDate.year, startDate.month + 1, 1) .subtract(const Duration(days: 1)); - final formattedEndDate = DateFormat('dd/MM/yyyy').format(endDate); + String 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 c6cca576..1985c67c 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,18 +95,16 @@ 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, @@ -114,4 +112,4 @@ class PowerBatchControlEvent 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 8ef43961..09f7b46e 100644 --- a/lib/pages/device_managment/power_clamp/models/device_event.dart +++ b/lib/pages/device_managment/power_clamp/models/device_event.dart @@ -1,3 +1,4 @@ + class EventDevice { final String? code; final DateTime? eventTime; @@ -11,7 +12,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 10ea3a11..1812d1c9 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) { - final String productUuid = json['productUuid'] ?? ''; - final String productType = json['productType'] ?? ''; + String productUuid = json['productUuid'] ?? ''; + String productType = json['productType'] ?? ''; - var statusList = []; + List 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 424c940f..b6592f4d 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,8 +16,7 @@ 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 ab70237e..223acd95 100644 --- a/lib/pages/device_managment/power_clamp/view/phase_widget.dart +++ b/lib/pages/device_managment/power_clamp/view/phase_widget.dart @@ -5,8 +5,7 @@ import 'package:syncrow_web/utils/constants/assets.dart'; class PhaseWidget extends StatefulWidget { final List> phaseData; - const PhaseWidget({ - super.key, + PhaseWidget({ required this.phaseData, }); @override @@ -20,7 +19,7 @@ class _PhaseWidgetState extends State { Widget build(BuildContext context) { return Column( children: [ - const SizedBox(height: 10), + SizedBox(height: 10), Row( children: List.generate(widget.phaseData.length, (index) { return InkWell( @@ -44,28 +43,27 @@ class _PhaseWidgetState extends State { ); }), ), - 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', - ), + 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', + ), ], ); } 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 bbdcd87d..7d6371f4 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 ColoredBox( + return Container( color: ColorsManager.whiteColors, child: Column( children: [ @@ -146,7 +146,7 @@ class _EnergyConsumptionPageState extends State { showTitles: false, reservedSize: 70, getTitlesWidget: (value, meta) { - final index = value.toInt(); + int 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.withValues(alpha: 0.2), + color: Colors.grey.withOpacity(0.2), dashArray: [8, 8], strokeWidth: 1, ); }, getDrawingHorizontalLine: (value) { return FlLine( - color: Colors.grey.withValues(alpha: 0.2), + color: Colors.grey.withOpacity(0.2), dashArray: [5, 5], strokeWidth: 1, ); @@ -192,21 +192,19 @@ 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.withValues(alpha: 0.6), + color: ColorsManager.primaryColor.withOpacity(0.6), show: true, shadow: const Shadow(color: Colors.black12), belowBarData: BarAreaData( show: true, gradient: LinearGradient( colors: [ - ColorsManager.primaryColor - .withValues(alpha: 0.5), - Colors.blue.withValues(alpha: 0.1), + ColorsManager.primaryColor.withOpacity(0.5), + Colors.blue.withOpacity(0.1), ], begin: Alignment.center, end: Alignment.bottomCenter, @@ -222,7 +220,7 @@ class _EnergyConsumptionPageState extends State { borderData: FlBorderData( show: false, border: Border.all( - color: const Color(0xff023DFE).withValues(alpha: 0.7), + color: const Color(0xff023DFE).withOpacity(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 2032cd90..7f6a4b64 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,17 +9,16 @@ 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({super.key, required this.deviceIds}); + const PowerClampBatchControlView({Key? key, required this.deviceIds}) : super(key: key); @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) { @@ -36,8 +35,7 @@ class PowerClampBatchControlView extends StatelessWidget ); } - 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 b06bd1c3..601b6346 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({ - super.key, + Key? 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 3f67a027..67313802 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,8 +12,7 @@ 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}); @@ -60,7 +59,7 @@ class SmartPowerDeviceControl extends StatelessWidget required SmartPowerBloc blocProvider, required int currentPage, }) { - final pageController = PageController(initialPage: currentPage); + PageController pageController = PageController(initialPage: currentPage); return Container( padding: const EdgeInsets.symmetric(horizontal: 50), child: DeviceControlsContainer( @@ -196,8 +195,8 @@ class SmartPowerDeviceControl extends StatelessWidget 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 c99b0028..f2dc68f5 100644 --- a/lib/pages/device_managment/shared/device_batch_control_dialog.dart +++ b/lib/pages/device_managment/shared/device_batch_control_dialog.dart @@ -4,8 +4,7 @@ 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}); @@ -44,7 +43,7 @@ class DeviceBatchControlDialog extends StatelessWidget height: 8, ), Text( - 'Batch Control', + "Batch Control", style: context.textTheme.bodySmall!.copyWith( color: ColorsManager.dialogBlueTitle, ), @@ -105,39 +104,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 0c9c4398..beb3b52c 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: const EdgeInsets.all(1), + padding: 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 5ee8a978..888563da 100644 --- a/lib/pages/device_managment/shared/device_controls_container.dart +++ b/lib/pages/device_managment/shared/device_controls_container.dart @@ -18,9 +18,8 @@ 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 ba84bd87..aac34b77 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,10 +4,7 @@ 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; @@ -35,9 +32,7 @@ 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), ), ), ], @@ -45,9 +40,7 @@ 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 c33ac15c..e1ca0586 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/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/utils/constants/assets.dart'; import 'package:syncrow_web/utils/extension/build_context_x.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'; class PresenceSpaceType extends StatelessWidget { const PresenceSpaceType({ @@ -20,7 +20,7 @@ class PresenceSpaceType extends StatelessWidget { @override Widget build(BuildContext context) { - final spaceTypeIcons = { + final Map 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 b46bbcc5..d2d48b78 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,8 +4,7 @@ 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; @@ -24,9 +23,7 @@ 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 4ec7737a..26e47c8b 100644 --- a/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart +++ b/lib/pages/device_managment/shared/sensors_widgets/presence_status.dart @@ -25,9 +25,7 @@ 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), ), ], ), @@ -43,9 +41,7 @@ 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 cda019ea..9cc23505 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('[a-zA-Z]'), '').trim(); + return value.replaceAll(RegExp(r'[a-zA-Z]'), '').trim(); } String _extractUnit(String value) { @@ -69,17 +69,17 @@ class _PresenceUpdateDataState extends State { } void _incrementValue() { - final currentIndex = nobodyTimeRange.indexOf(_currentValue); + int currentIndex = nobodyTimeRange.indexOf(_currentValue); if (currentIndex < nobodyTimeRange.length - 1) { - final newValue = nobodyTimeRange[currentIndex + 1]; + String newValue = nobodyTimeRange[currentIndex + 1]; _onValueChanged(newValue); } } void _decrementValue() { - final currentIndex = nobodyTimeRange.indexOf(_currentValue); + int currentIndex = nobodyTimeRange.indexOf(_currentValue); if (currentIndex > 0) { - final newValue = nobodyTimeRange[currentIndex - 1]; + String 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 72a98f56..11385080 100644 --- a/lib/pages/device_managment/shared/table/report_table.dart +++ b/lib/pages/device_managment/shared/table/report_table.dart @@ -41,8 +41,7 @@ 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( @@ -50,8 +49,7 @@ 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(), @@ -68,36 +66,28 @@ class ReportsTable extends StatelessWidget { ), if (report.data != null) ...report.data!.asMap().entries.map((entry) { - final index = entry.key; - final data = entry.value; + int index = entry.key; + DeviceEvent data = entry.value; // Parse eventTime into Date and Time - final eventDateTime = - DateTime.fromMillisecondsSinceEpoch( - data.eventTime!); - final date = - DateFormat('dd/MM/yyyy').format(eventDateTime); - final time = DateFormat('HH:mm').format(eventDateTime); + DateTime eventDateTime = + DateTime.fromMillisecondsSinceEpoch(data.eventTime!); + String date = DateFormat('dd/MM/yyyy').format(eventDateTime); + String 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 0e8cff37..4888572f 100644 --- a/lib/pages/device_managment/shared/toggle_widget.dart +++ b/lib/pages/device_managment/shared/toggle_widget.dart @@ -42,30 +42,29 @@ class ToggleWidget extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - 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, - ), - )), + 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 (showToggle) Container( child: CupertinoSwitch( value: value, - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: 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 9334a039..14fdf61c 100644 --- a/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart +++ b/lib/pages/device_managment/sos/bloc/sos_device_bloc.dart @@ -22,8 +22,7 @@ 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); @@ -34,8 +33,7 @@ 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); @@ -46,31 +44,25 @@ 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 records = await DevicesManagementApi.getDeviceReportsByDate( - event.uuid, 'sos', from.toString(), to.toString()); + final DeviceReport 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 records = await DevicesManagementApi.getDeviceReportsByDate( + final DeviceReport records = await DevicesManagementApi.getDeviceReportsByDate( event.uuid, 'sos_automation', from.toString(), to.toString()); emit(SosAutomationReportLoadedState(records)); } catch (e) { @@ -78,17 +70,14 @@ 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 4a9f2114..ac0de3b0 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 (final status in statuses) { + for (var 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 631a7424..dde4512b 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,12 +6,13 @@ 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({ @@ -55,9 +56,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}')); + return Center(child: Text('Error: ${state.message.toString()}')); } else if (state is SosReportErrorState) { - return Center(child: Text('Error: ${state.message}')); + return Center(child: Text('Error: ${state.message.toString()}')); } 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 bbdeaa3d..55428107 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: const EdgeInsets.all(1), + padding: 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 7ab5567d..766c3163 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,8 +40,7 @@ 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); @@ -65,7 +64,7 @@ class ThreeGangGlassSwitchBloc final statusList = []; if (data['status'] != null) { - for (final element in data['status']) { + for (var element in data['status']) { statusList.add( Status( code: element['code'].toString(), @@ -75,8 +74,7 @@ class ThreeGangGlassSwitchBloc } } if (statusList.isNotEmpty) { - final newStatus = - ThreeGangGlassStatusModel.fromJson(deviceId, statusList); + final newStatus = ThreeGangGlassStatusModel.fromJson(deviceId, statusList); if (newStatus != deviceStatus) { deviceStatus = newStatus; if (!isClosed) { @@ -144,10 +142,9 @@ 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 e439a434..cec12b7f 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 (final status in jsonList) { + for (var 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 22b5ff53..93fbe53e 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,19 +9,16 @@ 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) { @@ -38,8 +35,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget ); } - Widget _buildStatusControls( - BuildContext context, ThreeGangGlassStatusModel status) { + Widget _buildStatusControls(BuildContext context, ThreeGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -62,7 +58,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget value: status.switch1, code: 'switch_1', deviceId: deviceIds.first, - label: 'Wall Light', + label: "Wall Light", onChange: (value) { context.read().add( ThreeGangGlassSwitchBatchControl( @@ -77,7 +73,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget value: status.switch2, code: 'switch_2', deviceId: deviceIds.first, - label: 'Ceiling Light', + label: "Ceiling Light", onChange: (value) { context.read().add( ThreeGangGlassSwitchBatchControl( @@ -92,7 +88,7 @@ class ThreeGangGlassSwitchBatchControlView extends StatelessWidget 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 019f17f2..21a81df0 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'; -class ThreeGangGlassSwitchControlView extends StatelessWidget - with HelperResponsiveLayout { +import '../models/three_gang_glass_switch.dart'; + +class ThreeGangGlassSwitchControlView extends StatelessWidget with HelperResponsiveLayout { final String deviceId; const ThreeGangGlassSwitchControlView({required this.deviceId, super.key}); @@ -17,8 +17,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget 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) { @@ -35,8 +34,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget ); } - Widget _buildStatusControls( - BuildContext context, ThreeGangGlassStatusModel status) { + Widget _buildStatusControls(BuildContext context, ThreeGangGlassStatusModel status) { final isExtraLarge = isExtraLargeScreenSize(context); final isLarge = isLargeScreenSize(context); final isMedium = isMediumScreenSize(context); @@ -59,7 +57,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget value: status.switch1, code: 'switch_1', deviceId: deviceId, - label: 'Wall Light', + label: "Wall Light", onChange: (value) { context.read().add( ThreeGangGlassSwitchControl( @@ -74,7 +72,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget value: status.switch2, code: 'switch_2', deviceId: deviceId, - label: 'Ceiling Light', + label: "Ceiling Light", onChange: (value) { context.read().add( ThreeGangGlassSwitchControl( @@ -89,7 +87,7 @@ class ThreeGangGlassSwitchControlView extends StatelessWidget 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 be51b1d2..bec1314c 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,11 +39,9 @@ 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())); @@ -54,9 +52,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; - final statusList = []; + List statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -124,8 +122,7 @@ 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 60ea3d12..4bb5eada 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 (final status in jsonList) { + for (var 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 77647078..0b1a2f06 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,15 +2,14 @@ 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; @@ -19,16 +18,14 @@ class LivingRoomBatchControlsView extends StatelessWidget 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()); @@ -38,8 +35,7 @@ class LivingRoomBatchControlsView extends StatelessWidget ); } - 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 7d0faf7f..731b354c 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 ed0896fa..629c131b 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,4 +1,5 @@ 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'; @@ -6,11 +7,7 @@ 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; @@ -26,7 +23,7 @@ class CeilingLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: ColoredBox( + child: Container( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -40,7 +37,7 @@ class CeilingLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: 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 ea635247..6ac71a38 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,4 +1,5 @@ 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'; @@ -6,11 +7,7 @@ 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; @@ -26,7 +23,7 @@ class SpotLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: ColoredBox( + child: Container( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -40,7 +37,7 @@ class SpotLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: 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 8844cb1e..12c814ac 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,4 +1,5 @@ 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'; @@ -6,11 +7,7 @@ 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; @@ -26,7 +23,7 @@ class WallLight extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipOval( - child: ColoredBox( + child: Container( color: ColorsManager.whiteColors, child: SvgPicture.asset( Assets.lightPulp, @@ -40,7 +37,7 @@ class WallLight extends StatelessWidget { width: 35, child: CupertinoSwitch( value: value, - activeTrackColor: ColorsManager.dialogBlueTitle, + activeColor: 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 2a71f477..8f82c198 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,10 +42,8 @@ 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) { @@ -60,12 +58,11 @@ class TwoGangGlassSwitchBloc ); ref.onValue.listen((event) { - final eventsMap = event.snapshot.value! as Map; + final eventsMap = event.snapshot.value as Map; - final statusList = []; + List 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); @@ -124,8 +121,7 @@ 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 1d407ab6..54d99d74 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 (final status in jsonList) { + for (var 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 a70f1dfe..9d120ad6 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,19 +9,16 @@ 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) { @@ -38,8 +35,7 @@ class TwoGangGlassSwitchBatchControlView extends StatelessWidget ); } - 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 34e96c2b..575deeac 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,9 +16,8 @@ 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 1d959ffb..2e3a8633 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,8 +37,7 @@ 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)); @@ -52,9 +51,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; - final statusList = []; + List statusList = []; eventsMap['status'].forEach((element) { statusList.add( Status(code: element['code'], value: element['value']), @@ -117,8 +116,7 @@ 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 f4596d8c..b9208211 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 78794d72..58094a71 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 (final status in jsonList) { + for (var 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 1284a93b..e8346cb2 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,8 +10,7 @@ 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; @@ -19,17 +18,15 @@ class TwoGangBatchControlView extends StatelessWidget @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 4db3798e..630a132b 100644 --- a/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart +++ b/lib/pages/device_managment/wall_sensor/bloc/wall_bloc.dart @@ -55,8 +55,7 @@ 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) { @@ -69,9 +68,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; - final statusList = []; + List 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 d193df93..92b1842e 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 (var i = 0; i < jsonList.length; i++) { + for (int 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 6d15ba37..61108387 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,8 +11,7 @@ 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; @@ -23,21 +22,17 @@ class WallSensorBatchControlView extends StatelessWidget 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')); }, @@ -45,8 +40,8 @@ class WallSensorBatchControlView extends StatelessWidget ); } - 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, @@ -99,12 +94,11 @@ class WallSensorBatchControlView extends StatelessWidget 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 b6279b07..def8ed93 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,22 +1,21 @@ 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; @@ -27,23 +26,19 @@ class WallSensorControlsView extends StatelessWidget 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()); @@ -58,8 +53,7 @@ class WallSensorControlsView extends StatelessWidget ); } 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')); }, @@ -67,8 +61,8 @@ class WallSensorControlsView extends StatelessWidget ); } - 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, @@ -137,11 +131,10 @@ class WallSensorControlsView extends StatelessWidget 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:', @@ -158,8 +151,9 @@ class WallSensorControlsView extends StatelessWidget ), 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, @@ -168,8 +162,9 @@ class WallSensorControlsView extends StatelessWidget ), 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 69b49e4c..560a61e1 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,13 +123,11 @@ 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( @@ -167,7 +165,7 @@ class WaterHeaterBloc extends Bloc { ); if (success) { - if (event.code == 'countdown_1') { + if (event.code == "countdown_1") { final countdownDuration = Duration(seconds: event.value); emit( @@ -192,7 +190,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( @@ -238,8 +236,7 @@ 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.')); @@ -257,10 +254,8 @@ 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( @@ -331,20 +326,21 @@ class WaterHeaterBloc extends Bloc { void _listenToChanges(deviceId) { try { - final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; stream.listen((DatabaseEvent event) { - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List 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)); } @@ -479,14 +475,14 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - final newSchedule = ScheduleEntry( + ScheduleEntry newSchedule = ScheduleEntry( category: event.category, time: formatTimeOfDayToISO(event.time), function: Status(code: 'switch_1', value: event.functionOn), days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - final success = await DevicesManagementApi() + bool success = await DevicesManagementApi() .addScheduleRecord(newSchedule, currentState.status.uuid); if (success) { @@ -504,7 +500,7 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - final newSchedule = ScheduleEntry( + ScheduleEntry newSchedule = ScheduleEntry( scheduleId: event.scheduleId, category: event.category, time: formatTimeOfDayToISO(event.time), @@ -512,7 +508,7 @@ class WaterHeaterBloc extends Bloc { days: ScheduleModel.convertSelectedDaysToStrings(event.selectedDays), ); - final success = await DevicesManagementApi().editScheduleRecord( + bool success = await DevicesManagementApi().editScheduleRecord( currentState.status.uuid, newSchedule, ); @@ -542,7 +538,7 @@ class WaterHeaterBloc extends Bloc { return schedule; }).toList(); - final success = await DevicesManagementApi().updateScheduleRecord( + bool success = await DevicesManagementApi().updateScheduleRecord( enable: event.enable, uuid: currentState.status.uuid, scheduleId: event.scheduleId, @@ -563,7 +559,7 @@ class WaterHeaterBloc extends Bloc { if (state is WaterHeaterDeviceStatusLoaded) { final currentState = state as WaterHeaterDeviceStatusLoaded; - final success = await DevicesManagementApi() + bool success = await DevicesManagementApi() .deleteScheduleRecord(currentState.status.uuid, event.scheduleId); if (success) { @@ -588,8 +584,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) { @@ -597,8 +593,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; @@ -617,7 +613,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 92c5c293..e4cc8474 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,6 +54,7 @@ final class WaterHeaterFetchStatusEvent extends WaterHeaterEvent { final class DecrementCountdownEvent extends WaterHeaterEvent {} + class StatusUpdated extends WaterHeaterEvent { final WaterHeaterStatusModel deviceStatus; const StatusUpdated(this.deviceStatus); @@ -61,6 +62,7 @@ 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 27df3a9e..9278e396 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,12 +7,11 @@ 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), @@ -71,10 +70,9 @@ class ScheduleDialogHelper { backgroundColor: ColorsManager.boxColor, borderRadius: 15, onPressed: () async { - final time = await showTimePicker( + TimeOfDay? 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( @@ -94,9 +92,7 @@ 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, ), @@ -111,8 +107,7 @@ 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), ], @@ -186,9 +181,9 @@ class ScheduleDialogHelper { static List _convertDaysStringToBooleans(List selectedDays) { final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - final daysBoolean = List.filled(7, false); + List daysBoolean = List.filled(7, false); - for (var i = 0; i < daysOfWeek.length; i++) { + for (int i = 0; i < daysOfWeek.length; i++) { if (selectedDays.contains(daysOfWeek[i])) { daysBoolean[i] = true; } @@ -197,9 +192,7 @@ 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( @@ -209,9 +202,7 @@ class ScheduleDialogHelper { Checkbox( value: selectedDays[index], onChanged: (bool? value) { - context - .read() - .add(UpdateSelectedDayEvent(index, value!)); + context.read().add(UpdateSelectedDayEvent(index, value!)); }, ), Text(dayLabels[index]), @@ -221,23 +212,19 @@ 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'), @@ -246,9 +233,7 @@ 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 4a379009..a2a109af 100644 --- a/lib/pages/device_managment/water_heater/models/schedule_entry.dart +++ b/lib/pages/device_managment/water_heater/models/schedule_entry.dart @@ -58,8 +58,7 @@ 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) { @@ -74,9 +73,6 @@ 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 b90cf921..3d05a3e0 100644 --- a/lib/pages/device_managment/water_heater/models/schedule_model.dart +++ b/lib/pages/device_managment/water_heater/models/schedule_model.dart @@ -1,8 +1,7 @@ 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; @@ -94,8 +93,8 @@ class ScheduleModel { static List convertSelectedDaysToStrings(List selectedDays) { const allDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - final result = []; - for (var i = 0; i < selectedDays.length; i++) { + List result = []; + for (int 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 e4b48b5d..c535bda2 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 var heaterSwitch = false; - late var countdownInSeconds = 0; - late var relayStatus = ''; - late var cycleTiming = ''; - late var scheduleMode = ScheduleModes.countdown; + late bool heaterSwitch = false; + late int countdownInSeconds = 0; + late String relayStatus = ''; + late String cycleTiming = ''; + late ScheduleModes scheduleMode = ScheduleModes.countdown; - for (final status in jsonList) { + for (var 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 97ef6302..3c8a3858 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,8 +37,7 @@ 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 f654e62c..f1e56136 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,8 +35,7 @@ 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 4107b6ce..e60c7def 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 5257dddc..8eec5cca 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({ - super.key, + Key? 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 0b2657c5..1710c439 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 fb73eaf4..bb9ddc8f 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 576ebc2b..18cbbe5a 100644 --- a/lib/pages/device_managment/water_heater/widgets/schedule_table.dart +++ b/lib/pages/device_managment/water_heater/widgets/schedule_table.dart @@ -2,13 +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/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; @@ -210,8 +211,8 @@ class ScheduleTableWidget extends StatelessWidget { String _getSelectedDays(List selectedDays) { final days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - final selectedDaysStr = []; - for (var i = 0; i < selectedDays.length; i++) { + List selectedDaysStr = []; + for (int 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 ee1390a7..6d3ca9a6 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,11 +1,13 @@ -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 { @@ -37,15 +39,17 @@ class WaterLeakBloc extends Bloc { } } - void _listenToChanges() { + _listenToChanges() { try { - final ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); - final stream = ref.onValue; + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; stream.listen((DatabaseEvent event) { - final usersMap = event.snapshot.value! as Map; + Map usersMap = + event.snapshot.value as Map; - final statusList = []; + List statusList = []; usersMap['status'].forEach((element) { statusList .add(Status(code: element['code'], value: element['value'])); @@ -191,8 +195,9 @@ class WaterLeakBloc extends Bloc { .subtract(const Duration(days: 30)) .millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; - final records = await DevicesManagementApi.getDeviceReportsByDate( - event.deviceId, event.code, from.toString(), to.toString()); + final DeviceReport 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 30b077bf..1eb795e5 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,17 +10,16 @@ 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({super.key, required this.deviceIds}); + const WaterLeakBatchControlView({Key? key, required this.deviceIds}) : super(key: key); @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) { @@ -37,8 +36,7 @@ class WaterLeakBatchControlView extends StatelessWidget ); } - 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 51fd5880..6b9dc564 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({super.key, required this.deviceId}); + const WaterLeakView({Key? key, required this.deviceId}) : super(key: key); @override Widget build(BuildContext context) { @@ -21,8 +21,7 @@ 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) { @@ -45,31 +44,21 @@ 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, )); }, @@ -109,9 +98,7 @@ 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 924973c5..0e3e325f 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,8 +6,7 @@ class WaterLeakNotificationDialog extends StatefulWidget { const WaterLeakNotificationDialog({super.key}); @override - State createState() => - _NotificationDialogState(); + State createState() => _NotificationDialogState(); } class _NotificationDialogState extends State { @@ -54,7 +53,7 @@ class _NotificationDialogState extends State { ), ), child: IconButton( - padding: const EdgeInsets.all(1), + padding: 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 d422f318..ad6ed4d8 100644 --- a/lib/pages/home/bloc/home_bloc.dart +++ b/lib/pages/home/bloc/home_bloc.dart @@ -13,13 +13,14 @@ 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); @@ -29,12 +30,13 @@ class HomeBloc extends Bloc { Future _fetchUserInfo(FetchUserInfo event, Emitter emit) async { try { - final uuid = + var 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()); @@ -61,7 +63,7 @@ class HomeBloc extends Bloc { policy = await HomeApi().fetchPolicy(); emit(HomeInitial()); } catch (e) { - debugPrint('Error fetching policy: $e'); + debugPrint("Error fetching policy: $e"); return; } } @@ -70,7 +72,7 @@ class HomeBloc extends Bloc { ConfirmUserAgreementEvent event, Emitter emit) async { try { emit(LoadingHome()); - final uuid = + var uuid = await const FlutterSecureStorage().read(key: UserModel.userUuidKey); policy = await HomeApi().confirmUserAgreements(uuid); emit(PolicyAgreement()); @@ -144,21 +146,21 @@ class HomeBloc extends Bloc { // icon: Assets.energyIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), + // color: ColorsManager.slidingBlueColor.withOpacity(0.2), // ), // HomeItemModel( // title: 'Integrations', // icon: Assets.integrationsIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), + // color: ColorsManager.slidingBlueColor.withOpacity(0.2), // ), // HomeItemModel( // title: 'Asset', // icon: Assets.assetIcon, // active: false, // onPress: (context) {}, - // color: ColorsManager.slidingBlueColor.withValues(alpha:0.2), + // color: ColorsManager.slidingBlueColor.withOpacity(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 61e8a150..6b72c300 100644 --- a/lib/pages/home/view/agreement_and_privacy_dialog.dart +++ b/lib/pages/home/view/agreement_and_privacy_dialog.dart @@ -1,7 +1,9 @@ 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'; @@ -87,7 +89,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); @@ -95,10 +97,10 @@ class _AgreementAndPrivacyDialogState extends State { } }, style: { - 'body': Style( + "body": Style( fontSize: FontSize(14), color: Colors.black87, - lineHeight: const LineHeight(1.5), + lineHeight: LineHeight(1.5), ), }, ), @@ -108,7 +110,7 @@ class _AgreementAndPrivacyDialogState extends State { } Widget _buildActionButton() { - final buttonText = _currentPage == 2 ? 'I Agree' : 'Next'; + final String buttonText = _currentPage == 2 ? "I Agree" : "Next"; return InkWell( onTap: _isAtEnd @@ -165,7 +167,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 9652f0b6..9159011f 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 - ? const HomeMobilePage() + ? HomeMobilePage() : const HomeWebPage(); } } diff --git a/lib/pages/home/view/home_page_mobile.dart b/lib/pages/home/view/home_page_mobile.dart index 2b1d502b..ad019ea8 100644 --- a/lib/pages/home/view/home_page_mobile.dart +++ b/lib/pages/home/view/home_page_mobile.dart @@ -4,15 +4,16 @@ 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 { - const HomeMobilePage({super.key}); + HomeMobilePage({super.key}); @override Widget build(BuildContext context) { - final size = MediaQuery.of(context).size; + Size size = MediaQuery.of(context).size; return PopScope( canPop: false, onPopInvoked: (didPop) => false, @@ -40,8 +41,7 @@ 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 5adb5a12..53a994f6 100644 --- a/lib/pages/home/view/home_page_web.dart +++ b/lib/pages/home/view/home_page_web.dart @@ -20,9 +20,11 @@ class _HomeWebPageState extends State { // Flag to track whether the dialog is already shown. bool _dialogShown = false; + + @override Widget build(BuildContext context) { - final size = MediaQuery.of(context).size; + Size 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 f8dc9c33..9458e361 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.withValues(alpha:0.5), +// color: Colors.grey.withOpacity(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 15787fd7..4f4988b3 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; - void changeTapSelected( + 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 61a52f9d..16b24ec5 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 98049bcb..e502370a 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 00e8605d..54187152 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,3 +1,4 @@ +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'; @@ -10,6 +11,7 @@ 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'; @@ -64,7 +66,7 @@ class UsersBloc extends Bloc { void isCompleteSpacesFun( CheckSpacesStepStatus event, Emitter emit) { emit(UsersLoadingState()); - final spaceBloc = + var spaceBloc = NavigationService.navigatorKey.currentContext!.read(); isCompleteSpaces = spaceBloc.state.selectedCommunities.isNotEmpty; @@ -81,25 +83,26 @@ class UsersBloc extends Bloc { String communityUuid) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - return CommunitySpaceManagementApi() + return await CommunitySpaceManagementApi() .getSpaceHierarchy(communityUuid, projectUuid); } List updatedCommunities = []; List spacesNodes = []; List communityIds = []; - Future _onLoadCommunityAndSpaces( + _onLoadCommunityAndSpaces( LoadCommunityAndSpacesEvent event, Emitter emit) async { try { emit(UsersLoadingState()); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final communities = + List communities = await CommunitySpaceManagementApi().fetchCommunities(projectUuid); communityIds = communities.map((community) => community.uuid).toList(); updatedCommunities = await Future.wait( communities.map((community) async { - final spaces = await _fetchSpacesForCommunity(community.uuid); + List spaces = + await _fetchSpacesForCommunity(community.uuid); spacesNodes = _buildTreeNodes(spaces); return TreeNode( uuid: community.uuid, @@ -126,7 +129,7 @@ class UsersBloc extends Bloc { // Build tree nodes from your data model. List _buildTreeNodes(List spaces) { return spaces.map((space) { - final childNodes = + List childNodes = space.children.isNotEmpty ? _buildTreeNodes(space.children) : []; return TreeNode( uuid: space.uuid!, @@ -167,7 +170,7 @@ class UsersBloc extends Bloc { _clearHighlights(updatedCommunities); } else { // Start with a fresh clone of the original tree. - final freshClone = _cloneNodes(originalCommunities); + List freshClone = _cloneNodes(originalCommunities); _searchAndHighlightNodes(freshClone, event.searchTerm!); @@ -177,7 +180,7 @@ class UsersBloc extends Bloc { } void _clearHighlights(List nodes) { - for (final node in nodes) { + for (var node in nodes) { node.isHighlighted = false; if (node.children.isNotEmpty) { _clearHighlights(node.children); @@ -186,11 +189,11 @@ class UsersBloc extends Bloc { } bool _searchAndHighlightNodes(List nodes, String searchTerm) { - var anyMatch = false; - for (final node in nodes) { - final isMatch = + bool anyMatch = false; + for (var node in nodes) { + bool isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - final childMatch = _searchAndHighlightNodes(node.children, searchTerm); + bool childMatch = _searchAndHighlightNodes(node.children, searchTerm); node.isHighlighted = isMatch || childMatch; anyMatch = anyMatch || node.isHighlighted; @@ -199,11 +202,11 @@ class UsersBloc extends Bloc { } List _filterNodes(List nodes, String searchTerm) { - final filteredNodes = []; - for (final node in nodes) { - final isMatch = + List filteredNodes = []; + for (var node in nodes) { + bool isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - final filteredChildren = _filterNodes(node.children, searchTerm); + List filteredChildren = _filterNodes(node.children, searchTerm); if (isMatch || filteredChildren.isNotEmpty) { node.isHighlighted = isMatch; node.children = filteredChildren; @@ -286,8 +289,8 @@ class UsersBloc extends Bloc { List selectedIds = []; List getSelectedIds(List nodes) { - final selectedIds = []; - for (final node in nodes) { + List selectedIds = []; + for (var node in nodes) { if (node.isChecked) { selectedIds.add(node.uuid); } @@ -301,8 +304,7 @@ class UsersBloc extends Bloc { List roles = []; List permissions = []; - Future _getRolePermission( - RoleEvent event, Emitter emit) async { + _getRolePermission(RoleEvent event, Emitter emit) async { try { emit(UsersLoadingState()); roles = await UserPermissionApi().fetchRoles(); @@ -312,12 +314,11 @@ class UsersBloc extends Bloc { } } - Future _getPermissions( - PermissionEvent event, Emitter emit) async { + _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) { @@ -326,19 +327,18 @@ class UsersBloc extends Bloc { } bool _searchRolePermission(List nodes, String searchTerm) { - var anyMatch = false; - for (final node in nodes) { - final isMatch = + bool anyMatch = false; + for (var node in nodes) { + bool isMatch = node.title.toLowerCase().contains(searchTerm.toLowerCase()); - final childMatch = _searchRolePermission(node.subOptions, searchTerm); + bool childMatch = _searchRolePermission(node.subOptions, searchTerm); node.isHighlighted = isMatch || childMatch; anyMatch = anyMatch || node.isHighlighted; } return anyMatch; } - Future _sendInvitUser( - SendInviteUsers event, Emitter emit) async { + void _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(); - final selectedSpacesId = getSelectedSpacesIds(); + List selectedSpacesId = getSelectedSpacesIds(); // List selectedIds = getSelectedIds(updatedCommunities); - final res = await UserPermissionApi().sendInviteUser( + bool 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,28 +382,27 @@ class UsersBloc extends Bloc { } emit(SaveState()); } catch (e) { - emit(ErrorState('Failed to send invite: $e')); + emit(ErrorState('Failed to send invite: ${e.toString()}')); } } List getSelectedSpacesIds() { - final selectedSpacesId = []; - final spaceBloc = + List selectedSpacesId = []; + var spaceBloc = NavigationService.navigatorKey.currentContext!.read(); - for (final community in spaceBloc.state.selectedCommunities) { + for (var community in spaceBloc.state.selectedCommunities) { selectedSpacesId .addAll(spaceBloc.state.selectedCommunityAndSpaces[community] ?? []); } return selectedSpacesId; } - Future _editInviteUser( - EditInviteUsers event, Emitter emit) async { + _editInviteUser(EditInviteUsers event, Emitter emit) async { try { emit(UsersLoadingState()); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final res = await UserPermissionApi().editInviteUser( + bool res = await UserPermissionApi().editInviteUser( userId: event.userId, firstName: firstNameController.text, jobTitle: jobTitleController.text, @@ -416,9 +415,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( @@ -437,7 +436,7 @@ class UsersBloc extends Bloc { } emit(SaveState()); } catch (e) { - emit(ErrorState('Failed to send invite: $e')); + emit(ErrorState('Failed to send invite: ${e.toString()}')); } } @@ -456,7 +455,7 @@ class UsersBloc extends Bloc { Future checkEmail( CheckEmailEvent event, Emitter emit) async { emit(UsersLoadingState()); - final res = await UserPermissionApi().checkEmail( + String? res = await UserPermissionApi().checkEmail( emailController.text, ); checkEmailValid = res!; @@ -470,8 +469,8 @@ class UsersBloc extends Bloc { final emailRegex = RegExp( r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', ); - final isEmailValid = emailRegex.hasMatch(emailController.text); - final isEmailServerValid = checkEmailValid == 'Valid email'; + bool isEmailValid = emailRegex.hasMatch(emailController.text); + bool isEmailServerValid = checkEmailValid == 'Valid email'; isCompleteBasics = firstNameController.text.isNotEmpty && lastNameController.text.isNotEmpty && emailController.text.isNotEmpty && @@ -487,7 +486,7 @@ class UsersBloc extends Bloc { } void _clearHighlightsRolePermission(List nodes) { - for (final node in nodes) { + for (var node in nodes) { node.isHighlighted = false; if (node.subOptions.isNotEmpty) { _clearHighlightsRolePermission(node.subOptions); @@ -516,7 +515,7 @@ class UsersBloc extends Bloc { emit(UsersLoadingState()); try { - final spaceBloc = + var spaceBloc = NavigationService.navigatorKey.currentContext!.read(); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -534,9 +533,9 @@ class UsersBloc extends Bloc { res.roleType; res.spaces.map((space) { selectedIds.add(space.uuid); - final community = spaceBloc.state.communityList + CommunityModel community = spaceBloc.state.communityList .firstWhere((item) => item.uuid == space.communityUuid); - spaceBloc.add(OnSpaceSelected(community, space.uuid, const [])); + spaceBloc.add(OnSpaceSelected(community, space.uuid, [])); }).toList(); // if (updatedCommunities.isNotEmpty) { @@ -549,7 +548,7 @@ class UsersBloc extends Bloc { final roleId = roles .firstWhere((element) => element.type == - res.roleType.toLowerCase().replaceAll('_', ' ')) + res.roleType.toString().toLowerCase().replaceAll("_", " ")) .uuid; debugPrint('Role ID: $roleId'); roleSelected = roleId; @@ -605,14 +604,14 @@ class UsersBloc extends Bloc { } void _updateChildrenCheckStatus(TreeNode node, bool isChecked) { - for (final child in node.children) { + for (var child in node.children) { child.isChecked = isChecked; _updateChildrenCheckStatus(child, isChecked); } } void _updateParentCheckStatus(TreeNode node) { - final parent = _findParent(updatedCommunities, node); + TreeNode? parent = _findParent(updatedCommunities, node); if (parent != null) { parent.isChecked = _areAllChildrenChecked(parent); _updateParentCheckStatus(parent); @@ -627,7 +626,7 @@ class UsersBloc extends Bloc { } TreeNode? _findParent(List nodes, TreeNode target) { - for (final node in nodes) { + for (var 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 b7dbebd6..2e82168c 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 2769fc09..4141ccdd 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 6f715b5b..a5e622dc 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 7d39858c..44ba81ff 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,13 +29,12 @@ 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: [ @@ -44,7 +43,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, @@ -62,10 +61,9 @@ 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), ], ), ), @@ -103,35 +101,31 @@ 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), @@ -202,12 +196,8 @@ 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, ), ), ], @@ -270,12 +260,8 @@ 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, ), ), ], @@ -305,7 +291,7 @@ class _AddNewUserDialogState extends State { currentStep = step; step3 = step; bloc.add(const CheckSpacesStepStatus()); - bloc.add(const CheckStepStatus(isEditUser: false)); + bloc.add(CheckStepStatus(isEditUser: false)); }); }, child: Column( @@ -332,12 +318,8 @@ 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 e5933995..fa04c051 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,10 +218,9 @@ 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; }, ), @@ -255,7 +254,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, @@ -265,32 +264,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, ) ], ), @@ -315,11 +314,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 789e88e2..cbe15ecd 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,6 +1,7 @@ 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'; @@ -18,7 +19,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()), @@ -33,7 +34,7 @@ class TreeView extends StatelessWidget { return const Center(child: CircularProgressIndicator()); } return SingleChildScrollView( - child: _buildTree(blocRole.updatedCommunities, blocRole), + child: _buildTree(_blocRole.updatedCommunities, _blocRole), ); }, ), @@ -47,7 +48,7 @@ class TreeView extends StatelessWidget { }) { return Column( children: nodes.map((node) { - return ColoredBox( + return Container( 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 fd6666c5..10e8c273 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,9 +1,10 @@ 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; - const DeleteUserDialog({super.key, this.onTapDelete}); + DeleteUserDialog({super.key, this.onTapDelete}); @override _DeleteUserDialogState createState() => _DeleteUserDialogState(); @@ -34,7 +35,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, @@ -53,7 +54,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 50ae1d7c..071de067 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,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/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'; @@ -30,17 +31,15 @@ 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: [ @@ -49,7 +48,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, @@ -67,10 +66,9 @@ 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), ], ), ), @@ -108,7 +106,7 @@ class _EditUserDialogState extends State { onTap: () { Navigator.of(context).pop(); }, - child: const Text('Cancel'), + child: const Text("Cancel"), ), InkWell( onTap: () { @@ -118,24 +116,22 @@ class _EditUserDialogState extends State { if (currentStep < 3) { currentStep++; if (currentStep == 2) { - blocRole.add( - const CheckStepStatus(isEditUser: true)); + _blocRole.add(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), @@ -176,7 +172,7 @@ class _EditUserDialogState extends State { bloc.add(const CheckSpacesStepStatus()); currentStep = step; Future.delayed(const Duration(milliseconds: 500), () { - bloc.add(const ValidateBasicsStep()); + bloc.add(ValidateBasicsStep()); }); }); @@ -208,12 +204,8 @@ 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, ), ), ], @@ -241,7 +233,7 @@ class _EditUserDialogState extends State { onTap: () { setState(() { currentStep = step; - bloc.add(const CheckStepStatus(isEditUser: true)); + bloc.add(CheckStepStatus(isEditUser: true)); if (step3 == 3) { bloc.add(const CheckRoleStepStatus()); } @@ -271,12 +263,8 @@ 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, ), ), ], @@ -306,7 +294,7 @@ class _EditUserDialogState extends State { currentStep = step; step3 = step; bloc.add(const CheckSpacesStepStatus()); - bloc.add(const CheckStepStatus(isEditUser: true)); + bloc.add(CheckStepStatus(isEditUser: true)); }); }, child: Column( @@ -333,12 +321,8 @@ 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 76bacad9..aee84ed4 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({super.key, this.bloc}); + const PermissionManagement({Key? key, this.bloc}) : super(key: key); @override _PermissionManagementState createState() => _PermissionManagementState(); @@ -16,25 +16,25 @@ class PermissionManagement extends StatefulWidget { class _PermissionManagementState extends State { void toggleOptionById(String id) { setState(() { - for (final mainOption in widget.bloc!.permissions) { + for (var mainOption in widget.bloc!.permissions) { if (mainOption.id == id) { final isChecked = checkifOneOfthemChecked(mainOption) == CheckState.all; mainOption.isChecked = !isChecked; - for (final subOption in mainOption.subOptions) { + for (var subOption in mainOption.subOptions) { subOption.isChecked = !isChecked; - for (final child in subOption.subOptions) { + for (var child in subOption.subOptions) { child.isChecked = !isChecked; } } return; } - for (final subOption in mainOption.subOptions) { + for (var subOption in mainOption.subOptions) { if (subOption.id == id) { subOption.isChecked = !subOption.isChecked; - for (final child in subOption.subOptions) { + for (var child in subOption.subOptions) { child.isChecked = subOption.isChecked; } mainOption.isChecked = @@ -42,7 +42,7 @@ class _PermissionManagementState extends State { return; } - for (final child in subOption.subOptions) { + for (var 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) { - var allSelected = true; - var someSelected = false; + bool allSelected = true; + bool someSelected = false; - for (final subOption in mainOption.subOptions) { + for (var subOption in mainOption.subOptions) { if (subOption.isChecked) { someSelected = true; } else { allSelected = false; } - for (final child in subOption.subOptions) { + for (var child in subOption.subOptions) { if (child.isChecked) { someSelected = true; } else { @@ -143,7 +143,7 @@ class _PermissionManagementState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - ColoredBox( + Container( 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 ColoredBox( + return Container( color: option.isHighlighted ? Colors.blue.shade50 : Colors.white, @@ -260,7 +260,7 @@ class _PermissionManagementState extends State { ) ], ); - }), + }).toList(), ], ); }, @@ -268,27 +268,28 @@ 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, -// ), -// ), + + // 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 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 e79249d7..a7f6c2b5 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,8 +113,7 @@ Future showPopUpFilterMenu({ ), Text( item, - style: const TextStyle( - color: ColorsManager.grayColor), + style: TextStyle(color: ColorsManager.grayColor), ), ], ); @@ -137,12 +136,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 80ea8677..3a5ac65c 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 a5e140b4..f4b91747 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 ColoredBox( + final _blocRole = BlocProvider.of(context); + return Container( 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,10 +69,11 @@ 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)! @@ -106,10 +107,10 @@ class RolesAndPermission extends StatelessWidget { child: Container( color: ColorsManager.circleRolesBackground, padding: const EdgeInsets.all(8.0), - child: ColoredBox( + child: Container( 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 dfd59ae8..63f870e6 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,21 +11,19 @@ class SpacesAccessView extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder(builder: (context, state) { - final blocRole = BlocProvider.of(context); - return ColoredBox( + final _blocRole = BlocProvider.of(context); + return Container( 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 e032f6e4..e7eda606 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,6 +6,8 @@ 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()) { @@ -58,20 +60,20 @@ class UserTableBloc extends Bloc { final dateB = _parseDateTime(b.createdDate); return dateB.compareTo(dateA); }); - for (final user in users) { + for (var user in users) { roleTypes.add(user.roleType.toString()); } - for (final user in users) { + for (var user in users) { jobTitle.add(user.jobTitle.toString()); } - for (final user in users) { - createdBy.add(user.invitedBy); + for (var user in users) { + createdBy.add(user.invitedBy.toString()); } initialUsers = List.from(users); roleTypes = roleTypes.toSet().toList(); jobTitle = jobTitle.toSet().toList(); createdBy = createdBy.toSet().toList(); - _handlePageChange(const ChangePage(1), emit); + _handlePageChange(ChangePage(1), emit); totalUsersCount = initialUsers; add(ChangePage(currentPage)); emit(UsersLoadedState(users: users)); @@ -84,7 +86,7 @@ class UserTableBloc extends Bloc { DeleteUserEvent event, Emitter emit) async { emit(UsersLoadingState()); try { - final res = await UserPermissionApi().deleteUserById(event.userId); + bool res = await UserPermissionApi().deleteUserById(event.userId); if (res == true) { Navigator.of(event.context).pop(true); } else { @@ -102,8 +104,8 @@ class UserTableBloc extends Bloc { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; emit(UsersLoadingState()); - final res = await UserPermissionApi().changeUserStatusById(event.userId, - event.newStatus == 'disabled' ? false : true, projectUuid); + bool res = await UserPermissionApi().changeUserStatusById(event.userId, + event.newStatus == "disabled" ? false : true, projectUuid); if (res == true) { add(const GetUsers()); } @@ -119,13 +121,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() @@ -144,13 +146,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 = ''; @@ -166,15 +168,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); @@ -190,10 +192,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 { @@ -203,7 +205,7 @@ class UserTableBloc extends Bloc { final dateB = _parseDateTime(b.createdDate); return dateA.compareTo(dateB); }); - currentSortOrder = 'OldestToNewest'; + currentSortOrder = "OldestToNewest"; emit(UsersLoadedState(users: users)); } } @@ -226,7 +228,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(); @@ -281,22 +283,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; @@ -311,22 +313,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; @@ -342,21 +344,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; @@ -384,14 +386,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 {} @@ -399,7 +401,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 aea65950..1d9567cf 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; - const SearchUsers(this.query); + SearchUsers(this.query); @override List get props => []; } @@ -72,7 +72,7 @@ class SearchUsers extends UserTableEvent { class ChangePage extends UserTableEvent { final int pageNumber; - const ChangePage(this.pageNumber); + ChangePage(this.pageNumber); @override List get props => [pageNumber]; @@ -93,7 +93,6 @@ class FilterUsersByRoleEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByRoleEvent({this.selectedRoles, this.sortOrder}); - @override List get props => [selectedRoles, sortOrder]; } @@ -102,7 +101,6 @@ class FilterUsersByJobEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByJobEvent({this.selectedJob, this.sortOrder}); - @override List get props => [selectedJob, sortOrder]; } @@ -112,7 +110,6 @@ class FilterUsersByCreatedEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByCreatedEvent({this.selectedCreatedBy, this.sortOrder}); - @override List get props => [selectedCreatedBy, sortOrder]; } @@ -121,7 +118,6 @@ class FilterUsersByDeActevateEvent extends UserTableEvent { final String? sortOrder; const FilterUsersByDeActevateEvent({this.selectedActivate, this.sortOrder}); - @override List get props => [selectedActivate, sortOrder]; } @@ -129,14 +125,14 @@ class FilterOptionsEvent extends UserTableEvent { final String query; final List fullOptions; - const FilterOptionsEvent({required this.query, required this.fullOptions}); + FilterOptionsEvent({required this.query, required this.fullOptions}); @override List get props => [query, fullOptions]; } class FilterClearEvent extends UserTableEvent { - const FilterClearEvent(); + 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 9d71602b..ae99af3a 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,12 +9,10 @@ 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 198049f0..7b7da0bd 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,8 +8,9 @@ Future showDateFilterMenu({ Function()? zToaTap, String? isSelected, }) async { - final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; - final position = RelativeRect.fromRect( + final RenderBox overlay = + Overlay.of(context).context.findRenderObject() as RenderBox; + final RelativeRect position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 3, 240, @@ -38,9 +39,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), ), @@ -54,9 +55,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 166e1ca9..c8742ea5 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,8 +8,9 @@ Future showDeActivateFilterMenu({ Function()? zToaTap, String? isSelected, }) async { - final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; - final position = RelativeRect.fromRect( + final RenderBox overlay = + Overlay.of(context).context.findRenderObject() as RenderBox; + final RelativeRect position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 2, 240, @@ -38,9 +39,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), ), @@ -54,9 +55,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 a047fe97..f551cf3c 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,8 +8,9 @@ Future showNameMenu({ Function()? zToATap, String? isSelected, }) async { - final overlay = Overlay.of(context).context.findRenderObject()! as RenderBox; - final position = RelativeRect.fromRect( + final RenderBox overlay = + Overlay.of(context).context.findRenderObject() as RenderBox; + final RelativeRect position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width / 35, 240, @@ -38,9 +39,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), ), ), ), @@ -52,9 +53,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 624a57f7..9b10b5d4 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,7 +17,8 @@ class _HeaderColumn extends StatelessWidget { required this.showFilter, required this.onResize, this.onFilter, - }); + Key? key, + }) : super(key: key); @override Widget build(BuildContext context) { @@ -70,7 +71,8 @@ class _TableRow extends StatelessWidget { required this.cells, required this.columnWidths, required this.isLast, - }); + Key? key, + }) : super(key: key); @override Widget build(BuildContext context) { @@ -114,9 +116,9 @@ class DynamicTableScreen extends StatefulWidget { required this.titles, required this.rows, required this.onFilter, - super.key, + Key? key, required this.tableSize, - }); + }) : super(key: key); @override _DynamicTableScreenState createState() => _DynamicTableScreenState(); @@ -137,12 +139,12 @@ class _DynamicTableScreenState extends State { void _handleColumnResize(int index, double delta) { setState(() { - var newWidth = columnWidths[index] + delta; + double newWidth = columnWidths[index] + delta; newWidth = newWidth.clamp(_minColumnWidth, _maxColumnWidth); - final actualDelta = newWidth - columnWidths[index]; + double actualDelta = newWidth - columnWidths[index]; if (actualDelta == 0) return; - final nextIndex = (index + 1) % columnWidths.length; + int nextIndex = (index + 1) % columnWidths.length; columnWidths[index] = newWidth; columnWidths[nextIndex] = (columnWidths[nextIndex] - actualDelta) .clamp(_minColumnWidth, _maxColumnWidth); @@ -254,7 +256,7 @@ class _DynamicTableScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildHeader(), - SizedBox(height: widget.tableSize - 37, child: _buildBody()), + Container(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 d007baf2..735ce839 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 { - const UsersPage({super.key}); + UsersPage({super.key}); @override Widget build(BuildContext context) { - final searchController = TextEditingController(); + final TextEditingController 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.withValues(alpha: 0.5) - : status == 'active' - ? ColorsManager.activeGreen.withValues(alpha: 0.5) - : ColorsManager.disabledPink.withValues(alpha: 0.5), + color: status == "invited" + ? ColorsManager.invitedOrange.withOpacity(0.5) + : status == "active" + ? ColorsManager.activeGreen.withOpacity(0.5) + : ColorsManager.disabledPink.withOpacity(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(const FilterClearEvent()); + bloc.add(FilterClearEvent()); bloc.add(SearchUsers(value)); if (value == '') { - bloc.add(const ChangePage(1)); + bloc.add(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), - SizedBox( + Container( 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 checkboxStates = { - for (final item in blocRole.jobTitle) - item: blocRole.selectedJobTitles.contains(item), + final Map checkboxStates = { + for (var item in _blocRole.jobTitle) + item: _blocRole.selectedJobTitles.contains(item), }; - final overlay = Overlay.of(context) + final RenderBox 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(const FilterClearEvent()); + _blocRole.add(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 checkboxStates = { - for (final item in blocRole.roleTypes) - item: blocRole.selectedRoles.contains(item), + final Map checkboxStates = { + for (var item in _blocRole.roleTypes) + item: _blocRole.selectedRoles.contains(item), }; - final overlay = Overlay.of(context) + final RenderBox 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(const FilterClearEvent()); + _blocRole.add(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 checkboxStates = { - for (final item in blocRole.createdBy) - item: blocRole.selectedCreatedBy.contains(item), + final Map checkboxStates = { + for (var item in _blocRole.createdBy) + item: _blocRole.selectedCreatedBy.contains(item), }; - final overlay = Overlay.of(context) + final RenderBox 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(const FilterClearEvent()); + _blocRole.add(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 checkboxStates = { - for (final item in blocRole.status) - item: blocRole.selectedStatuses.contains(item), + final Map checkboxStates = { + for (var item in _blocRole.status) + item: _blocRole.selectedStatuses.contains(item), }; - final overlay = Overlay.of(context) + final RenderBox 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(const FilterClearEvent()); + _blocRole.add(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,36 +452,35 @@ class UsersPage extends StatelessWidget { ), Row( children: [ - 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); + 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()); + } + } + }); }, - ).then((v) { - if (v != null) { - if (v != null) { - blocRole.add(const GetUsers()); - } - } - }); - }, - ) - else - actionButton( - title: 'Edit', - ), + ) + : actionButton( + title: "Edit", + ), actionButton( - title: 'Delete', + title: "Delete", onTap: () { showDialog( context: context, @@ -490,7 +489,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)); @@ -502,7 +501,7 @@ class UsersPage extends StatelessWidget { }, ).then((v) { if (v != null) { - blocRole.add(const GetUsers()); + _blocRole.add(const GetUsers()); } }); }, @@ -530,10 +529,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 8b137891..e69de29b 100644 --- a/lib/pages/roles_and_permission/view/create_role_card.dart +++ b/lib/pages/roles_and_permission/view/create_role_card.dart @@ -1 +0,0 @@ - diff --git a/lib/pages/roles_and_permission/view/role_card.dart b/lib/pages/roles_and_permission/view/role_card.dart index 866b0345..b08b14ea 100644 --- a/lib/pages/roles_and_permission/view/role_card.dart +++ b/lib/pages/roles_and_permission/view/role_card.dart @@ -13,8 +13,7 @@ class RoleCard extends StatelessWidget { borderRadius: BorderRadius.circular(20), // Rounded corners boxShadow: [ BoxShadow( - color: - ColorsManager.blackColor.withValues(alpha: 0.2), // Shadow color + color: ColorsManager.blackColor.withOpacity(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 @@ -24,7 +23,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 b7a510d0..4ba83cc1 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,5 +1,6 @@ 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'; @@ -21,7 +22,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()) @@ -64,10 +65,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, ), @@ -77,7 +78,7 @@ class RolesAndPermissionPage extends StatelessWidget { ), scaffoldBody: BlocProvider( create: (context) => UserTableBloc()..add(const GetUsers()), - child: const UsersPage(), + child: 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 b8c977e3..9c8ef0cd 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 searchController = TextEditingController(); - final screenWidth = MediaQuery.of(context).size.width; + final TextEditingController searchController = TextEditingController(); + double screenWidth = MediaQuery.of(context).size.width; - final crossAxisCount = (screenWidth ~/ 200).clamp(1, 6); + int crossAxisCount = (screenWidth ~/ 200).clamp(1, 6); return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -54,6 +54,9 @@ 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 b5326a40..c664c2c4 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,3 +1,4 @@ + import 'dart:convert'; class AutomationStatusUpdate { @@ -16,23 +17,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 ab154342..b472d034 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 { } } - void saveSpaceIdCommunityId( + saveSpaceIdCommunityId( SaveCommunityIdAndSpaceIdEvent event, Emitter emit) { emit(const SpaceWithDeviceLoadingState()); selectedSpaceId = event.spaceID!; @@ -44,8 +44,7 @@ class CreateRoutineBloc extends Bloc { emit(const SelectedState()); } - void resetSelected( - ResetSelectedEvent event, Emitter emit) { + 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 4b39fe62..ba901497 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,9 +42,10 @@ 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 208b5e02..5ebc20f7 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,3 +1,4 @@ + import 'package:equatable/equatable.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; @@ -38,6 +39,7 @@ class SelectedState extends CreateRoutineState { const SelectedState(); } + class ResetSelectedState extends CreateRoutineState { const ResetSelectedState(); } @@ -48,4 +50,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 af429f7d..fd56d232 100644 --- a/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart +++ b/lib/pages/routines/bloc/effective_period/effect_period_bloc.dart @@ -25,8 +25,7 @@ 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, @@ -36,8 +35,8 @@ class EffectPeriodBloc extends Bloc { } void _onSetPeriod(SetPeriod event, Emitter emit) { - var startTime = ''; - var endTime = ''; + String startTime = ''; + String endTime = ''; switch (event.period) { case EnumEffectivePeriodOptions.allDay: @@ -61,9 +60,7 @@ 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) { @@ -79,8 +76,8 @@ class EffectPeriodBloc extends Bloc { } void _onSetCustomTime(SetCustomTime event, Emitter emit) { - final startTime = event.startTime; - final endTime = event.endTime; + String startTime = event.startTime; + String endTime = event.endTime; EnumEffectivePeriodOptions period; // Determine the period based on start and end times @@ -94,14 +91,11 @@ 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 4ecb83b9..2f8b66c8 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,6 +50,5 @@ 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 b58b953d..ca8aac06 100644 --- a/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart +++ b/lib/pages/routines/bloc/routine_bloc/routine_bloc.dart @@ -1,9 +1,11 @@ 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:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/common/bloc/project_manager.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/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart'; import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart'; @@ -73,7 +75,7 @@ class RoutineBloc extends Bloc { } } - void _resetErrorMessage( + _resetErrorMessage( ResetErrorMessage event, Emitter emit, ) { @@ -91,7 +93,7 @@ class RoutineBloc extends Bloc { final updatedIfItems = List>.from(state.ifItems); // Find the index of the item in teh current itemsList - final index = updatedIfItems.indexWhere( + int index = updatedIfItems.indexWhere( (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); // Replace the map if the index is valid if (index != -1) { @@ -114,7 +116,7 @@ class RoutineBloc extends Bloc { final currentItems = List>.from(state.thenItems); // Find the index of the item in teh current itemsList - final index = currentItems.indexWhere( + int index = currentItems.indexWhere( (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); // Replace the map if the index is valid if (index != -1) { @@ -133,7 +135,7 @@ class RoutineBloc extends Bloc { // List selectedFunction = List.from(event.functions); - final currentSelectedFunctions = + Map> currentSelectedFunctions = Map>.from(state.selectedFunctions); // if (currentSelectedFunctions.containsKey(event.uniqueCustomId)) { @@ -174,18 +176,18 @@ class RoutineBloc extends Bloc { Future _onLoadScenes( LoadScenes event, Emitter emit) async { emit(state.copyWith(isLoading: true, errorMessage: null)); - final scenes = []; + List scenes = []; try { - final context = NavigationService.navigatorKey.currentContext!; - final createRoutineBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var createRoutineBloc = context.read(); final projectUuid = await ProjectManager.getProjectUUID() ?? ''; if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - final spaceBloc = context.read(); - for (final communityId in spaceBloc.state.selectedCommunities) { - final spacesList = + var spaceBloc = context.read(); + for (var communityId in spaceBloc.state.selectedCommunities) { + List spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (final spaceId in spacesList) { + for (var spaceId in spacesList) { scenes.addAll( await SceneApi.getScenes(spaceId, communityId, projectUuid)); } @@ -214,19 +216,19 @@ class RoutineBloc extends Bloc { Future _onLoadAutomation( LoadAutomation event, Emitter emit) async { emit(state.copyWith(isLoading: true, errorMessage: null)); - final automations = []; + List automations = []; final projectId = await ProjectManager.getProjectUUID() ?? ''; - final context = NavigationService.navigatorKey.currentContext!; - final createRoutineBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var createRoutineBloc = context.read(); try { if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - final spaceBloc = context.read(); - for (final communityId in spaceBloc.state.selectedCommunities) { - final spacesList = + var spaceBloc = context.read(); + for (var communityId in spaceBloc.state.selectedCommunities) { + List spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (final spaceId in spacesList) { + for (var spaceId in spacesList) { automations.addAll( await SceneApi.getAutomation(spaceId, communityId, projectId)); } @@ -334,8 +336,8 @@ class RoutineBloc extends Bloc { }); }).toList(); - final context = NavigationService.navigatorKey.currentContext!; - final createRoutineBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var createRoutineBloc = context.read(); final createSceneModel = CreateSceneModel( spaceUuid: createRoutineBloc.selectedSpaceId, @@ -359,7 +361,7 @@ class RoutineBloc extends Bloc { } } on APIException catch (e) { final errorData = e.message; - final errorMessage = errorData; + String errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -398,7 +400,7 @@ class RoutineBloc extends Bloc { return; } emit(state.copyWith(isLoading: true, errorMessage: null)); - var i = 0; + int i = 0; final conditions = state.ifItems.expand((item) { final functions = state.selectedFunctions[item['uniqueCustomId']] ?? []; return functions.map((function) { @@ -466,8 +468,8 @@ class RoutineBloc extends Bloc { ); }); }).toList(); - final context = NavigationService.navigatorKey.currentContext!; - final createRoutineBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var createRoutineBloc = context.read(); final createAutomationModel = CreateAutomationModel( spaceUuid: createRoutineBloc.selectedSpaceId, @@ -497,7 +499,7 @@ class RoutineBloc extends Bloc { } } on APIException catch (e) { final errorData = e.message; - final errorMessage = errorData; + String errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -703,14 +705,14 @@ class RoutineBloc extends Bloc { final List> thenItems; final List> ifItems; - final updatedFunctions = + final Map> updatedFunctions = Map>.from(state.selectedFunctions); - final deviceCards = >{}; + final Map> deviceCards = {}; - for (final action in sceneDetails.actions) { + for (var action in sceneDetails.actions) { AllDevicesModel? matchingDevice; - for (final device in state.devices) { + for (var device in state.devices) { if (device.uuid == action.entityId) { matchingDevice = device; break; @@ -775,7 +777,7 @@ class RoutineBloc extends Bloc { action.actionExecutor != 'delay') { final functions = matchingDevice?.functions ?? []; final functionCode = action.executorProperty?.functionCode; - for (final function in functions) { + for (DeviceFunction function in functions) { if (function.code == functionCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -869,8 +871,8 @@ class RoutineBloc extends Bloc { final projectId = await ProjectManager.getProjectUUID() ?? ''; emit(state.copyWith(isLoading: true)); - final context = NavigationService.navigatorKey.currentContext!; - final spaceBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var spaceBloc = context.read(); if (state.isTabToRun) { await SceneApi.deleteScene( unitUuid: spaceBloc.state.selectedSpaces[0], @@ -899,7 +901,7 @@ class RoutineBloc extends Bloc { emit(state.copyWith(isLoading: false, createRoutineView: false)); } on APIException catch (e) { final errorData = e.message; - final errorMessage = errorData; + String errorMessage = errorData; emit(state.copyWith( isLoading: false, errorMessage: errorMessage, @@ -927,17 +929,17 @@ class RoutineBloc extends Bloc { emit(state.copyWith(isLoading: true)); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final devices = []; - final context = NavigationService.navigatorKey.currentContext!; - final createRoutineBloc = context.read(); - final spaceBloc = context.read(); + List devices = []; + BuildContext context = NavigationService.navigatorKey.currentContext!; + var createRoutineBloc = context.read(); + var spaceBloc = context.read(); if (createRoutineBloc.selectedSpaceId == '' && createRoutineBloc.selectedCommunityId == '') { - for (final communityId in spaceBloc.state.selectedCommunities) { - final spacesList = + for (var communityId in spaceBloc.state.selectedCommunities) { + List spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - for (final spaceId in spacesList) { + for (var spaceId in spacesList) { devices.addAll(await DevicesManagementApi() .fetchDevices(communityId, spaceId, projectUuid)); } @@ -1069,7 +1071,7 @@ class RoutineBloc extends Bloc { return; } emit(state.copyWith(isLoading: true, errorMessage: null)); - var i = 0; + int i = 0; final conditions = state.ifItems.expand((item) { final functions = state.selectedFunctions[item['uniqueCustomId']] ?? []; return functions.map((function) { @@ -1140,8 +1142,8 @@ class RoutineBloc extends Bloc { }); }).toList(); - final context = NavigationService.navigatorKey.currentContext!; - final spaceBloc = context.read(); + BuildContext context = NavigationService.navigatorKey.currentContext!; + var spaceBloc = context.read(); final createAutomationModel = CreateAutomationModel( spaceUuid: spaceBloc.selectedSpaceId, @@ -1161,8 +1163,8 @@ class RoutineBloc extends Bloc { if (result['success']) { add(ResetRoutineState()); - add(const LoadAutomation()); - add(const LoadScenes()); + add(LoadAutomation()); + add(LoadScenes()); } else { emit(state.copyWith( isLoading: false, @@ -1195,14 +1197,14 @@ class RoutineBloc extends Bloc { final automationDetails = await SceneApi.getAutomationDetails(event.automationId, projectUuid); - final deviceIfCards = >{}; - final deviceThenCards = >{}; + final Map> deviceIfCards = {}; + final Map> deviceThenCards = {}; - final updatedFunctions = + final Map> updatedFunctions = Map>.from(state.selectedFunctions); - for (final condition in automationDetails.conditions ?? []) { - final matchingDevice = state.devices.firstWhere( + for (RoutineCondition condition in automationDetails.conditions ?? []) { + AllDevicesModel? matchingDevice = state.devices.firstWhere( (device) => device.uuid == condition.entityId, orElse: () => AllDevicesModel( uuid: condition.entityId, @@ -1239,7 +1241,7 @@ class RoutineBloc extends Bloc { } final functions = matchingDevice.functions; - for (final function in functions) { + for (var function in functions) { if (function.code == condition.expr.statusCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -1255,8 +1257,8 @@ class RoutineBloc extends Bloc { } // Process actions (thenItems) - for (final action in automationDetails.actions) { - final matchingDevice = state.devices.firstWhere( + for (var action in automationDetails.actions) { + AllDevicesModel? matchingDevice = state.devices.firstWhere( (device) => device.uuid == action.entityId, orElse: () => AllDevicesModel( uuid: action.entityId, @@ -1310,7 +1312,7 @@ class RoutineBloc extends Bloc { action.actionExecutor != 'delay') { final functions = matchingDevice.functions; final functionCode = action.executorProperty!.functionCode; - for (final function in functions) { + for (var function in functions) { if (function.code == functionCode) { updatedFunctions[uniqueCustomId]!.add( DeviceFunctionData( @@ -1401,7 +1403,7 @@ class RoutineBloc extends Bloc { } catch (e) { emit(state.copyWith( loadingSceneId: null, - errorMessage: 'Trigger error: $e', + errorMessage: 'Trigger error: ${e.toString()}', )); } } @@ -1446,7 +1448,7 @@ class RoutineBloc extends Bloc { ..remove(event.automationId); emit(state.copyWith( loadingAutomationIds: updatedLoadingIds, - errorMessage: 'Update error: $e', + errorMessage: 'Update error: ${e.toString()}', )); } } diff --git a/lib/pages/routines/bloc/routine_bloc/routine_event.dart b/lib/pages/routines/bloc/routine_bloc/routine_event.dart index dd7adf71..b532235d 100644 --- a/lib/pages/routines/bloc/routine_bloc/routine_event.dart +++ b/lib/pages/routines/bloc/routine_bloc/routine_event.dart @@ -86,8 +86,7 @@ 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]; } @@ -212,6 +211,9 @@ class ClearFunctions extends RoutineEvent {} class ResetErrorMessage extends RoutineEvent {} + + + class SceneTrigger extends RoutineEvent { final String? sceneId; final String? name; @@ -219,7 +221,7 @@ class SceneTrigger extends RoutineEvent { const SceneTrigger({this.sceneId, this.name}); @override - List get props => [sceneId!, name!]; + List get props => [sceneId!,name!]; } //updateAutomationStatus @@ -228,10 +230,7 @@ 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 b35e3b21..843b35df 100644 --- a/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart +++ b/lib/pages/routines/bloc/setting_bloc/setting_bloc.dart @@ -15,44 +15,37 @@ class SettingBloc extends Bloc { on(_selectIcon); } - Future _initialSetting( - InitialEvent event, Emitter emit) async { + void _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')); } } - Future _fetchIcons(FetchIcons event, Emitter emit) async { + void _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')); } } - Future _selectIcon(SelectIcon event, Emitter emit) async { + void _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 a3424013..6fd562b0 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 adaff718..fe207910 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; - var spaceHint = 'Please Select'; + String 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 1ae5be86..70c88087 100644 --- a/lib/pages/routines/create_new_routines/dropdown_menu_content.dart +++ b/lib/pages/routines/create_new_routines/dropdown_menu_content.dart @@ -1,3 +1,7 @@ + + + + import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; @@ -10,7 +14,6 @@ class DropdownMenuContent extends StatefulWidget { final VoidCallback onClose; const DropdownMenuContent({ - super.key, required this.selectedSpaceId, required this.onChanged, required this.onClose, @@ -42,7 +45,7 @@ class _DropdownMenuContentState extends State { final state = bloc.state; if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 30) { - if (!state.paginationIsLoading) { + if (state is SpaceTreeState && !state.paginationIsLoading) { bloc.add(PaginationEvent(state.paginationModel, state.communityList)); } } @@ -123,7 +126,7 @@ class _DropdownMenuContentState extends State { _searchController.text.isEmpty ? context .read() - .add(const SearchQueryEvent('')) + .add(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 5af30f28..1d11b02d 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({ - super.key, + Key? 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: const TextStyle(color: Colors.black), + style: 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 da835e4b..be2a7e9b 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 69cf3d3f..dec701dc 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 c815da17..dd22d095 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 2b506620..f8b52dab 100644 --- a/lib/pages/routines/helper/save_routine_helper.dart +++ b/lib/pages/routines/helper/save_routine_helper.dart @@ -17,10 +17,9 @@ 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, @@ -38,11 +37,10 @@ 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(), @@ -60,8 +58,7 @@ 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), ], @@ -100,8 +97,7 @@ 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)), ], ), @@ -113,7 +109,7 @@ class SaveRoutineHelper { spacing: 16, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - DialogFooterButton( + DialogFooterButton( text: 'Back', onTap: () => Navigator.pop(context), ), @@ -147,8 +143,7 @@ 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(), ), @@ -208,20 +203,19 @@ 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 e92b6dee..edc377dd 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,23 +90,22 @@ class TempSetFunction extends ACFunction { min: 200, max: 300, step: 1, - unit: '°C', + unit: "°C", ); @override List getOperationalValues() { - final values = []; - for (var temp = min!.toInt(); temp <= max!; temp += step!.toInt()) { + List values = []; + for (int 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}) @@ -121,22 +120,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, ), ]; @@ -156,26 +155,22 @@ 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; - @override - final String unit = '°C'; + final String unit = "°C"; CurrentTempFunction( {required super.deviceId, required super.deviceName, required type}) @@ -191,11 +186,11 @@ class CurrentTempFunction extends ACFunction { @override List getOperationalValues() { - final values = []; - for (var temp = min.toInt(); temp <= max; temp += step.toInt()) { + List values = []; + for (int 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 f364abdb..122d8ea1 100644 --- a/lib/pages/routines/models/ceiling_presence_sensor_functions.dart +++ b/lib/pages/routines/models/ceiling_presence_sensor_functions.dart @@ -6,10 +6,12 @@ class CpsOperationalValue { final String description; final dynamic value; + CpsOperationalValue({ required this.icon, required this.description, required this.value, + }); } @@ -43,12 +45,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, ), ]; @@ -69,12 +71,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, ), ]; @@ -94,11 +96,8 @@ final class CpsSensitivityFunction extends CpsFunctions { icon: Assets.sensitivity, ); - @override final double min; - @override final double max; - @override final double step; static const _images = [ @@ -145,11 +144,8 @@ final class CpsMovingSpeedFunction extends CpsFunctions { icon: Assets.speedoMeter, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -179,11 +175,8 @@ final class CpsSpatialStaticValueFunction extends CpsFunctions { icon: Assets.spatialStaticValue, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -213,11 +206,8 @@ final class CpsSpatialMotionValueFunction extends CpsFunctions { icon: Assets.spatialMotionValue, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -247,11 +237,8 @@ final class CpsMaxDistanceOfDetectionFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -260,7 +247,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', @@ -285,11 +272,8 @@ final class CpsMaxDistanceOfStaticDetectionFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -298,7 +282,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', @@ -323,11 +307,8 @@ final class CpsDetectionRangeFunction extends CpsFunctions { icon: Assets.farDetection, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -336,7 +317,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', @@ -361,11 +342,8 @@ final class CpsDistanceOfMovingObjectsFunction extends CpsFunctions { icon: Assets.currentDistanceIcon, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -374,7 +352,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', @@ -399,11 +377,8 @@ final class CpsPresenceJudgementThrsholdFunction extends CpsFunctions { icon: Assets.presenceJudgementThrshold, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -433,11 +408,8 @@ final class CpsMotionAmplitudeTriggerThresholdFunction extends CpsFunctions { icon: Assets.presenceJudgementThrshold, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -467,11 +439,8 @@ final class CpsPerpetualBoundaryFunction extends CpsFunctions { icon: Assets.boundary, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -480,7 +449,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', @@ -505,11 +474,8 @@ final class CpsMotionTriggerBoundaryFunction extends CpsFunctions { icon: Assets.motionMeter, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -518,7 +484,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', @@ -543,11 +509,8 @@ final class CpsMotionTriggerTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -556,7 +519,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', @@ -581,11 +544,8 @@ final class CpsMotionToStaticTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -594,7 +554,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', @@ -619,11 +579,8 @@ final class CpsEnteringNoBodyStateTimeFunction extends CpsFunctions { icon: Assets.motionMeter, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -632,7 +589,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', @@ -912,11 +869,8 @@ final class CpsSportsParaFunction extends CpsFunctions { icon: Assets.sportsPara, ); - @override final double min; - @override final double max; - @override final double step; @override @@ -925,7 +879,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 835d8886..81ee1096 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 ?? actionType, + actionType: actionType ?? this.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 28c87a25..428825f4 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 6f4b01a6..a8f6ccd4 100644 --- a/lib/pages/routines/models/flush/flush_functions.dart +++ b/lib/pages/routines/models/flush/flush_functions.dart @@ -24,7 +24,8 @@ class FlushPresenceDelayFunction extends FlushFunctions { required super.deviceId, required super.deviceName, required super.type, - }) : super( + }) : + super( code: FlushMountedPresenceSensorModel.codePresenceState, operationName: 'Presence State', icon: Assets.presenceStateIcon, @@ -36,7 +37,7 @@ class FlushPresenceDelayFunction extends FlushFunctions { FlushOperationalValue( icon: Assets.nobodyTime, description: 'None', - value: 'none', + value: "none", ), FlushOperationalValue( icon: Assets.presenceStateIcon, @@ -48,11 +49,8 @@ class FlushPresenceDelayFunction extends FlushFunctions { } class FlushSensiReduceFunction extends FlushFunctions { - @override final double min; - @override final double max; - @override final double step; FlushSensiReduceFunction({ @@ -81,11 +79,8 @@ class FlushSensiReduceFunction extends FlushFunctions { } class FlushNoneDelayFunction extends FlushFunctions { - @override final double min; - @override final double max; - @override final String unit; FlushNoneDelayFunction({ @@ -114,11 +109,8 @@ class FlushNoneDelayFunction extends FlushFunctions { } class FlushIlluminanceFunction extends FlushFunctions { - @override final double min; - @override final double max; - @override final double step; FlushIlluminanceFunction({ @@ -136,11 +128,11 @@ class FlushIlluminanceFunction extends FlushFunctions { @override List getOperationalValues() { - final values = []; - for (var lux = min.toInt(); lux <= max; lux += step.toInt()) { + List values = []; + for (int lux = min.toInt(); lux <= max; lux += step.toInt()) { values.add(FlushOperationalValue( icon: Assets.IlluminanceIcon, - description: '$lux Lux', + description: "$lux Lux", value: lux, )); } @@ -149,11 +141,8 @@ class FlushIlluminanceFunction extends FlushFunctions { } class FlushOccurDistReduceFunction extends FlushFunctions { - @override final double min; - @override final double max; - @override final double step; FlushOccurDistReduceFunction({ @@ -183,11 +172,8 @@ class FlushOccurDistReduceFunction extends FlushFunctions { // ==== then functions ==== class FlushSensitivityFunction extends FlushFunctions { - @override final double min; - @override final double max; - @override final double step; FlushSensitivityFunction({ @@ -216,13 +202,9 @@ 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({ @@ -242,7 +224,7 @@ class FlushNearDetectionFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min; value <= max; value += step) { + for (var value = min.toDouble(); value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -254,13 +236,9 @@ 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({ @@ -292,13 +270,9 @@ 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({ @@ -318,7 +292,7 @@ class FlushTargetConfirmTimeFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min; value <= max; value += step) { + for (var value = min.toDouble(); value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -330,13 +304,9 @@ 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({ @@ -356,7 +326,7 @@ class FlushDisappeDelayFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min; value <= max; value += step) { + for (var value = min.toDouble(); value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -368,13 +338,9 @@ 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({ @@ -394,7 +360,7 @@ class FlushIndentLevelFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min; value <= max; value += step) { + for (var value = min.toDouble(); value <= max; value += step) { values.add(FlushOperationalValue( icon: Assets.nobodyTime, description: '$value $unit', @@ -406,13 +372,9 @@ 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({ @@ -432,7 +394,7 @@ class FlushTriggerLevelFunction extends FlushFunctions { @override List getOperationalValues() { final values = []; - for (var value = min; value <= max; value += step) { + for (var value = min.toDouble(); 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 78d32069..9451f89f 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 eee0019d..9bdd30b4 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,11 +3,8 @@ 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 String type, - }) : super( + ThreeGangSwitch1Function({required super.deviceId, required super.deviceName ,required type}) + : super( code: 'switch_1', operationName: 'Light 1 Switch', icon: Assets.assetsAcPower, @@ -17,23 +14,20 @@ 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 String type, - }) : super( + ThreeGangCountdown1Function({required super.deviceId, required super.deviceName ,required type}) + : super( code: 'countdown_1', operationName: 'Light 1 Countdown', icon: Assets.assetsLightCountdown, @@ -43,7 +37,7 @@ class ThreeGangCountdown1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: 'sec', + description: "sec", value: 0.0, minValue: 0, maxValue: 43200, @@ -53,11 +47,8 @@ class ThreeGangCountdown1Function extends BaseSwitchFunction { } class ThreeGangSwitch2Function extends BaseSwitchFunction { - ThreeGangSwitch2Function({ - required super.deviceId, - required super.deviceName, - required String type, - }) : super( + ThreeGangSwitch2Function({required super.deviceId, required super.deviceName, required type}) + : super( code: 'switch_2', operationName: 'Light 2 Switch', icon: Assets.assetsAcPower, @@ -67,23 +58,20 @@ 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 String type, - }) : super( + ThreeGangCountdown2Function({required super.deviceId, required super.deviceName ,required type}) + : super( code: 'countdown_2', operationName: 'Light 2 Countdown', icon: Assets.assetsLightCountdown, @@ -93,7 +81,7 @@ class ThreeGangCountdown2Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: 'sec', + description: "sec", value: 0.0, minValue: 0, maxValue: 43200, @@ -103,11 +91,8 @@ class ThreeGangCountdown2Function extends BaseSwitchFunction { } class ThreeGangSwitch3Function extends BaseSwitchFunction { - ThreeGangSwitch3Function({ - required super.deviceId, - required super.deviceName, - required String type, - }) : super( + ThreeGangSwitch3Function({required super.deviceId, required super.deviceName ,required type}) + : super( code: 'switch_3', operationName: 'Light 3 Switch', icon: Assets.assetsAcPower, @@ -117,23 +102,20 @@ 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 String type, - }) : super( + ThreeGangCountdown3Function({required super.deviceId, required super.deviceName ,required type}) + : super( code: 'countdown_3', operationName: 'Light 3 Countdown', icon: Assets.assetsLightCountdown, @@ -143,7 +125,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 a5f78436..95de1122 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,20 +37,19 @@ 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', @@ -61,7 +60,7 @@ class TwoGangCountdown1Function extends BaseSwitchFunction { List getOperationalValues() => [ SwitchOperationalValue( icon: '', - description: 'sec', + description: "sec", value: 0.0, minValue: 0, maxValue: 43200, @@ -71,8 +70,7 @@ 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', @@ -83,7 +81,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 06dc6f52..b1a70d2e 100644 --- a/lib/pages/routines/models/gateway.dart +++ b/lib/pages/routines/models/gateway.dart @@ -13,8 +13,7 @@ class GatewayOperationalValue { }); } -abstract class GatewayFunctions - extends DeviceFunction { +abstract class GatewayFunctions extends DeviceFunction { final String type; GatewayFunctions({ @@ -44,12 +43,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, ), ]; @@ -71,12 +70,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', ), ]; @@ -99,12 +98,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 5945faa4..4bf3ddd8 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 364a5bec..c42b4d36 100644 --- a/lib/pages/routines/models/routine_details_model.dart +++ b/lib/pages/routines/models/routine_details_model.dart @@ -48,8 +48,7 @@ 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(), ); @@ -64,8 +63,7 @@ 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, @@ -82,12 +80,10 @@ 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'], @@ -141,8 +137,7 @@ 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 d1d3cdcd..2f7c2a24 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 6c76a41d..7ebea019 100644 --- a/lib/pages/routines/models/water_heater/water_heater_functions.dart +++ b/lib/pages/routines/models/water_heater/water_heater_functions.dart @@ -29,6 +29,7 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { operationName: 'Restart Status', icon: Assets.refreshStatusIcon, ); + @override List getOperationalValues() { @@ -36,7 +37,7 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { WaterHeaterOperationalValue( icon: Assets.assetsAcPowerOFF, description: 'Power OFF', - value: 'off', + value: "off", ), WaterHeaterOperationalValue( icon: Assets.assetsAcPower, @@ -45,7 +46,7 @@ class WHRestartStatusFunction extends WaterHeaterFunctions { ), WaterHeaterOperationalValue( icon: Assets.refreshStatusIcon, - description: 'Restart Memory', + description: "Restart Memory", value: 'memory', ), ]; @@ -104,7 +105,8 @@ 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 3eae35a8..101c5cf0 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,13 +62,9 @@ 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( @@ -98,11 +94,8 @@ 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( @@ -131,11 +124,8 @@ class MotionSensitivityFunction extends WpsFunctions { } class MotionLessSensitivityFunction extends WpsFunctions { - @override final double min; - @override final double max; - @override final double step; MotionLessSensitivityFunction( @@ -177,23 +167,20 @@ 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( @@ -234,23 +221,20 @@ 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( @@ -267,11 +251,11 @@ class CurrentDistanceFunction extends WpsFunctions { @override List getOperationalValues() { - final values = []; - for (var cm = min.toInt(); cm <= max; cm += step.toInt()) { + List values = []; + for (int cm = min.toInt(); cm <= max; cm += step.toInt()) { values.add(WpsOperationalValue( icon: Assets.assetsTempreture, - description: '${cm}CM', + description: "${cm}CM", value: cm, )); } @@ -280,11 +264,8 @@ class CurrentDistanceFunction extends WpsFunctions { } class IlluminanceValueFunction extends WpsFunctions { - @override final double min; - @override final double max; - @override final double step; IlluminanceValueFunction({ @@ -302,11 +283,11 @@ class IlluminanceValueFunction extends WpsFunctions { @override List getOperationalValues() { - final values = []; - for (var lux = min.toInt(); lux <= max; lux += step.toInt()) { + List values = []; + for (int 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 8369d790..b54e4075 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 51176419..f46ef15f 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 { - Future _handleRoutineCreation(BuildContext context) async { + void _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 8a26db83..541ad431 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 List _icons = [ + static const _conditions = ["<", "==", ">"]; + static const _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.withValues(alpha: 0.5), + color: ColorsManager.softGray.withOpacity(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 f7ceda8f..f0767df4 100644 --- a/lib/pages/routines/widgets/custom_routines_textbox.dart +++ b/lib/pages/routines/widgets/custom_routines_textbox.dart @@ -1,5 +1,4 @@ import 'dart:math'; - import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:syncrow_web/pages/routines/widgets/condition_toggle.dart'; @@ -46,10 +45,10 @@ class _CustomRoutinesTextboxState extends State { String? errorMessage; int getDecimalPlaces(double step) { - final stepStr = step.toString(); + String stepStr = step.toString(); if (stepStr.contains('.')) { - final parts = stepStr.split('.'); - var decimalPart = parts[1]; + List parts = stepStr.split('.'); + String decimalPart = parts[1]; decimalPart = decimalPart.replaceAll(RegExp(r'0+$'), ''); return decimalPart.isEmpty ? 0 : decimalPart.length; } else { @@ -112,11 +111,13 @@ 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; @@ -127,23 +128,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 { - final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - final factor = pow(10, decimalPlaces).toInt(); - final scaledStep = (widget.stepIncreaseAmount * factor).round(); - final scaledValue = (doubleValue * factor).round(); + int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + int factor = pow(10, decimalPlaces).toInt(); + int scaledStep = (widget.stepIncreaseAmount * factor).round(); + int 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 { @@ -155,10 +156,11 @@ class _CustomRoutinesTextboxState extends State { } } + void _correctAndUpdateValue(String value) { final doubleValue = double.tryParse(value) ?? 0.0; - final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - var rounded = (doubleValue / widget.stepIncreaseAmount).round() * + int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + double rounded = (doubleValue / widget.stepIncreaseAmount).round() * widget.stepIncreaseAmount; rounded = rounded.clamp(widget.sliderRange.$1, widget.sliderRange.$2); rounded = double.parse(rounded.toStringAsFixed(decimalPlaces)); @@ -177,9 +179,9 @@ class _CustomRoutinesTextboxState extends State { @override Widget build(BuildContext context) { - final decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); + int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount); - final formatters = []; + List formatters = []; if (decimalPlaces == 0) { formatters.add(FilteringTextInputFormatter.digitsOnly); } else { @@ -231,7 +233,7 @@ class _CustomRoutinesTextboxState extends State { color: ColorsManager.lightGrayBorderColor, width: 1), boxShadow: [ BoxShadow( - color: ColorsManager.blackColor.withValues(alpha: 0.05), + color: ColorsManager.blackColor.withOpacity(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 13121493..10eeb493 100644 --- a/lib/pages/routines/widgets/delete_scene.dart +++ b/lib/pages/routines/widgets/delete_scene.dart @@ -33,17 +33,13 @@ 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()); @@ -54,10 +50,7 @@ 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 69daa31c..9853df7c 100644 --- a/lib/pages/routines/widgets/dragable_card.dart +++ b/lib/pages/routines/widgets/dragable_card.dart @@ -33,18 +33,17 @@ 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']] ?? []; - final index = state.thenItems.indexWhere( - (item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); + int index = state.thenItems + .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); if (index != -1) { return _buildCardContent(context, deviceFunctions, padding: padding); } - final ifIndex = state.ifItems.indexWhere( - (item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); + int ifIndex = state.ifItems + .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']); if (ifIndex != -1) { return _buildCardContent(context, deviceFunctions, padding: padding); @@ -54,8 +53,7 @@ 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), @@ -64,8 +62,7 @@ class DraggableCard extends StatelessWidget { ); } - Widget _buildCardContent( - BuildContext context, List deviceFunctions, + Widget _buildCardContent(BuildContext context, List deviceFunctions, {EdgeInsetsGeometry? padding}) { return Stack( children: [ @@ -95,8 +92,7 @@ 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']), ) @@ -122,15 +118,12 @@ 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'] ?? '', @@ -148,23 +141,20 @@ 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'] ?? '', @@ -232,8 +222,7 @@ 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 559d8b20..50167a7b 100644 --- a/lib/pages/routines/widgets/function_slider.dart +++ b/lib/pages/routines/widgets/function_slider.dart @@ -17,13 +17,12 @@ class FunctionSlider extends StatelessWidget { @override Widget build(BuildContext context) { final (min, max) = range; - final isValidRange = max > min; - final value = initialValue is int + final bool isValidRange = max > min; + final double value = initialValue is int ? (initialValue as int).toDouble() : (initialValue as double); - final divisions = - isValidRange ? ((max - min) / dividendOfRange).round() : null; + final int? 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 9832f627..da77c7c2 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 d28f88f0..f9c20c54 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,9 +16,8 @@ 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( @@ -27,23 +26,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 8c587aba..4fc4bd0f 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 cardWidth = widget.isSmallScreenSize(context) + final double cardWidth = widget.isSmallScreenSize(context) ? 120 : widget.isMediumScreenSize(context) ? 135 : 150; - final cardHeight = widget.isSmallScreenSize(context) ? 190 : 200; + final double cardHeight = widget.isSmallScreenSize(context) ? 190 : 200; - final iconSize = widget.isSmallScreenSize(context) + final double iconSize = widget.isSmallScreenSize(context) ? 70 : widget.isMediumScreenSize(context) ? 80 @@ -99,42 +99,41 @@ class _RoutineViewCardState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - 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(), + 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(), Column( children: [ Center( @@ -160,9 +159,8 @@ 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, @@ -205,8 +203,7 @@ 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 != '') @@ -225,9 +222,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, ), ), ], diff --git a/lib/pages/routines/widgets/period_option.dart b/lib/pages/routines/widgets/period_option.dart index 2e455008..09ec590e 100644 --- a/lib/pages/routines/widgets/period_option.dart +++ b/lib/pages/routines/widgets/period_option.dart @@ -21,12 +21,9 @@ 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), @@ -37,8 +34,7 @@ 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( @@ -82,16 +78,12 @@ 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 ee2389be..4920408a 100644 --- a/lib/pages/routines/widgets/repeat_days.dart +++ b/lib/pages/routines/widgets/repeat_days.dart @@ -16,9 +16,7 @@ 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) { @@ -33,8 +31,7 @@ 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( @@ -45,9 +42,7 @@ 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, ), ), @@ -58,9 +53,7 @@ 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 5b054908..f0b77467 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 220bcde0..cbf13178 100644 --- a/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/ac_dialog.dart @@ -24,7 +24,8 @@ class ACHelper { required bool? removeComparetors, required String dialogType, }) async { - final acFunctions = functions.whereType().where((function) { + List acFunctions = + functions.whereType().where((function) { if (dialogType == 'THEN') { return function.type == 'THEN' || function.type == 'BOTH'; } @@ -370,7 +371,7 @@ class ACHelper { // return Container( // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), // decoration: BoxDecoration( - // color: ColorsManager.primaryColorWithOpacity.withValues(alpha:0.1), + // color: ColorsManager.primaryColorWithOpacity.withOpacity(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 0ef19067..3c1eb1c2 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_footer.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/utils/constants/assets.dart'; class AutomationDialog extends StatefulWidget { @@ -31,11 +31,9 @@ class _AutomationDialogState extends State { @override void initState() { super.initState(); - final functions = context - .read() - .state - .selectedFunctions[widget.uniqueCustomId]; - for (final data in functions ?? []) { + List? functions = + context.read().state.selectedFunctions[widget.uniqueCustomId]; + for (DeviceFunctionData data in functions ?? []) { if (data.entityId == widget.automationId) { selectedAutomationActionExecutor = data.value; } @@ -67,8 +65,7 @@ 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 5bcc558d..504017a2 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,8 +45,7 @@ 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 0ce2fd04..d11871a7 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 4fa2e66c..fd637c28 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,6 +1,5 @@ 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) { @@ -63,10 +62,7 @@ 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 b81c6a80..4580f6e1 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 { - var hours = 0; - var minutes = 0; + int hours = 0; + int minutes = 0; return showDialog?>( context: context, builder: (BuildContext context) { final routineBloc = context.read(); - var totalSec = 0; + int totalSec = 0; final selectedFunctionData = routineBloc.state.selectedFunctions[data['uniqueCustomId']] ?? []; @@ -43,8 +43,7 @@ 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; @@ -56,7 +55,7 @@ class DelayHelper { Navigator.of(context).pop(); }, onConfirm: () { - final totalSeconds = (hours * 3600) + (minutes * 60); + int 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 3a493abd..40036d32 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.withValues(alpha: 0.8), + onConfirmColor: ColorsManager.red.withOpacity(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 5543ec96..5fc31a96 100644 --- a/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/effictive_period_dialog.dart @@ -8,14 +8,13 @@ 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 { - var selectedStartTime = '00:00'; - var selectedEndTime = '23:59'; - final pageController = PageController(initialPage: 0); + static Future?> showCustomTimePicker(BuildContext context) async { + String selectedStartTime = "00:00"; + String selectedEndTime = "23:59"; + PageController pageController = PageController(initialPage: 0); - final startDateTime = DateTime(2022, 1, 1, 0, 0); - final endDateTime = DateTime(2022, 1, 1, 23, 59); + DateTime startDateTime = DateTime(2022, 1, 1, 0, 0); + DateTime endDateTime = DateTime(2022, 1, 1, 23, 59); context.customAlertDialog( alertBody: SizedBox( @@ -47,7 +46,7 @@ class EffectPeriodHelper { ], ), ), - title: 'Custom', + title: "Custom", onConfirm: () { context.read().add( SetCustomTime(selectedStartTime, selectedEndTime), @@ -89,7 +88,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, @@ -136,17 +135,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 b4fa1080..7ca89edb 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,6 +7,7 @@ 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; @@ -61,7 +62,7 @@ class FlushValueSelectorWidget extends StatelessWidget { selectedFunction == FlushMountedPresenceSensorModel.codeFarDetection; final isDistanceDetection = isNearDetection || isFarDetection; - var initialValue = (functionData.value as num?)?.toDouble() ?? 0.0; + double initialValue = (functionData.value as num?)?.toDouble() ?? 0.0; if (isDistanceDetection) { initialValue = initialValue / 100; @@ -156,7 +157,7 @@ class FlushValueSelectorWidget extends StatelessWidget { String get getDisplayText { final num? value = functionData.value; - var displayValue = value?.toDouble() ?? 0.0; + double 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 4e296e65..56f74054 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,6 +49,8 @@ class _TimeWheelPickerState extends State { } } + + @override void dispose() { _hoursController.dispose(); @@ -101,7 +103,7 @@ class _TimeWheelPickerState extends State { } void _handleTimeChange(int hours, int minutes, int seconds) { - var total = hours * 3600 + minutes * 60 + seconds; + int 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 1d22f1a1..392c3012 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,8 +45,7 @@ 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 e2b103c5..641fd234 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,7 +25,8 @@ class OneGangSwitchHelper { required String uniqueCustomId, required bool removeComparetors, }) async { - final oneGangFunctions = functions.whereType().toList(); + List oneGangFunctions = + functions.whereType().toList(); return showDialog?>( context: context, @@ -245,9 +246,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 e6f832c8..2b8ba68f 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,4 +81,6 @@ 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 3695d075..696251a1 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,11 +27,13 @@ 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 sliderRange = (selectedFn.min ?? 0.0, selectedFn.max ?? 100.0); + final step = selectedFn.step ?? 1.0; + final _unit = selectedFn.unit ?? ''; + final (double, double) sliderRange = + (selectedFn.min ?? 0.0, selectedFn.max ?? 100.0); if (_isSliderFunction(selectedFunction)) { return CustomRoutinesTextbox( @@ -63,7 +65,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 2d02304a..b8449838 100644 --- a/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart +++ b/lib/pages/routines/widgets/routine_dialogs/setting_dialog.dart @@ -1,4 +1,3 @@ -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'; @@ -14,6 +13,7 @@ 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,16 +30,14 @@ 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, @@ -47,18 +45,15 @@ class SettingHelper { builder: (context, effectPeriodState) { return BlocBuilder( builder: (context, settingState) { - var selectedIcon = ''; - var list = []; + String selectedIcon = ''; + List 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), @@ -81,18 +76,14 @@ 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', @@ -100,18 +91,14 @@ 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, ) ], @@ -121,27 +108,22 @@ class SettingHelper { height: 5, ), const Divider( - color: - ColorsManager.graysColor, + color: ColorsManager.graysColor, ), const SizedBox( height: 5, ), InkWell( onTap: () { - BlocProvider.of< - SettingBloc>( - context) - .add(FetchIcons( + BlocProvider.of(context).add( + FetchIcons( expanded: !context - .read< - SettingBloc>() + .read() .isExpanded)); }, child: Row( mainAxisAlignment: - MainAxisAlignment - .spaceBetween, + MainAxisAlignment.spaceBetween, children: [ Text( 'Effective Period', @@ -149,18 +131,14 @@ 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, ) ], @@ -170,16 +148,13 @@ 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', @@ -187,11 +162,8 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager - .textPrimaryColor, - fontWeight: - FontWeight - .w400, + color: ColorsManager.textPrimaryColor, + fontWeight: FontWeight.w400, fontSize: 14), ), Text('Cloud', @@ -199,19 +171,12 @@ 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() ], @@ -223,27 +188,20 @@ 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< - SettingBloc>( - context) - .add(FetchIcons( + BlocProvider.of(context).add( + FetchIcons( expanded: !context - .read< - SettingBloc>() + .read() .isExpanded)); }, child: Row( mainAxisAlignment: - MainAxisAlignment - .spaceBetween, + MainAxisAlignment.spaceBetween, children: [ Text( 'Icons', @@ -251,18 +209,14 @@ 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, ) ], @@ -272,16 +226,13 @@ 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', @@ -289,30 +240,23 @@ 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, ), ), @@ -324,16 +268,13 @@ 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', @@ -341,11 +282,8 @@ class SettingHelper { .textTheme .bodyMedium! .copyWith( - color: ColorsManager - .textPrimaryColor, - fontWeight: - FontWeight - .w400, + color: ColorsManager.textPrimaryColor, + fontWeight: FontWeight.w400, fontSize: 14), ), Text('Cloud', @@ -353,19 +291,12 @@ 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() ], @@ -373,14 +304,12 @@ 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( @@ -397,8 +326,7 @@ class SettingHelper { height: 35, child: InkWell( onTap: () { - BlocProvider.of( - context) + BlocProvider.of(context) .add(SelectIcon( iconId: iconModel.uuid, )); @@ -407,17 +335,13 @@ 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, @@ -432,12 +356,8 @@ 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( @@ -461,33 +381,23 @@ 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); @@ -497,12 +407,8 @@ 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 8416837a..5e50c11d 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,7 +24,8 @@ class ThreeGangSwitchHelper { required String dialogType, required bool removeComparetors, }) async { - final switchFunctions = functions.whereType().toList(); + List 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 1ed89cd4..6b3dc813 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,7 +25,8 @@ class TwoGangSwitchHelper { required bool removeComparetors, required String dialogType, }) async { - final switchFunctions = functions.whereType().toList(); + List switchFunctions = + functions.whereType().toList(); return showDialog?>( context: context, @@ -236,7 +237,7 @@ class TwoGangSwitchHelper { DeviceFunctionData? selectedFunctionData, // Function(String) onConditionChanged, ) { - final conditions = ['<', '==', '>']; + final conditions = ["<", "==", ">"]; return ToggleButtons( onPressed: (int index) { @@ -263,8 +264,8 @@ class TwoGangSwitchHelper { minWidth: 40.0, ), isSelected: - conditions.map((c) => c == (currentCondition ?? '==')).toList(), - children: conditions.map(Text.new).toList(), + conditions.map((c) => c == (currentCondition ?? "==")).toList(), + children: conditions.map((c) => Text(c)).toList(), ); } @@ -279,7 +280,7 @@ class TwoGangSwitchHelper { return Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), decoration: BoxDecoration( - color: ColorsManager.primaryColorWithOpacity.withValues(alpha: 0.1), + color: ColorsManager.primaryColorWithOpacity.withOpacity(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 4e296e65..56f74054 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,6 +49,8 @@ class _TimeWheelPickerState extends State { } } + + @override void dispose() { _hoursController.dispose(); @@ -101,7 +103,7 @@ class _TimeWheelPickerState extends State { } void _handleTimeChange(int hours, int minutes, int seconds) { - var total = hours * 3600 + minutes * 60 + seconds; + int 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 497ee3db..4d04102d 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,8 +63,7 @@ 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 6dacb85e..6c149cd3 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,8 +30,7 @@ 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]), ); } @@ -62,8 +61,7 @@ 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 25839c68..4042df36 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,4 +61,5 @@ 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 9647408c..a09bbba7 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,13 +39,14 @@ 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 e261b3b1..efeedf9d 100644 --- a/lib/pages/routines/widgets/routine_search_and_buttons.dart +++ b/lib/pages/routines/widgets/routine_search_and_buttons.dart @@ -15,8 +15,7 @@ class RoutineSearchAndButtons extends StatefulWidget { }); @override - State createState() => - _RoutineSearchAndButtonsState(); + State createState() => _RoutineSearchAndButtonsState(); } class _RoutineSearchAndButtonsState extends State { @@ -62,9 +61,8 @@ 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, @@ -73,13 +71,10 @@ 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, @@ -93,23 +88,20 @@ 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) { @@ -122,44 +114,41 @@ class _RoutineSearchAndButtonsState extends State { ], ), ), - 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, + (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, + ), + ), ), ), ), - ), - ), ], ), ), @@ -197,12 +186,10 @@ 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( @@ -216,12 +203,10 @@ 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( @@ -236,10 +221,8 @@ 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), @@ -278,14 +261,10 @@ 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, @@ -335,12 +314,10 @@ 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( @@ -354,12 +331,10 @@ 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( @@ -374,8 +349,7 @@ 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 785686b6..14cb8d61 100644 --- a/lib/pages/routines/widgets/scenes_and_automations.dart +++ b/lib/pages/routines/widgets/scenes_and_automations.dart @@ -27,16 +27,14 @@ class _ScenesAndAutomationsState extends State { return BlocBuilder( builder: (context, state) { if (!state.isLoading) { - final scenes = [...state.scenes, ...state.automations]; + var 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 9d2320bd..9ffcbf63 100644 --- a/lib/pages/routines/widgets/search_bar_condition_title.dart +++ b/lib/pages/routines/widgets/search_bar_condition_title.dart @@ -6,8 +6,7 @@ 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 e32a2e67..d9eee4c4 100644 --- a/lib/pages/routines/widgets/then_container.dart +++ b/lib/pages/routines/widgets/then_container.dart @@ -30,118 +30,123 @@ class ThenContainer extends StatelessWidget { style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(height: 16), - 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]); + 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 (result != null) { - context - .read() - .add(AddToThenContainer({ - ...state.thenItems[index], - 'imagePath': Assets.delay, - 'title': 'Delay', - })); + 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])); } - 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'])); + }, + ), + ))), ], ), ), @@ -163,7 +168,7 @@ class ThenContainer extends StatelessWidget { } if (mutableData['type'] == 'automation') { - final index = state.thenItems.indexWhere( + int index = state.thenItems.indexWhere( (item) => item['deviceId'] == mutableData['deviceId']); if (index != -1) { return; @@ -189,7 +194,7 @@ class ThenContainer extends StatelessWidget { } if (mutableData['type'] == 'tap_to_run' && state.isAutomation) { - final index = state.thenItems.indexWhere( + int index = state.thenItems.indexWhere( (item) => item['deviceId'] == mutableData['deviceId']); if (index != -1) { return; @@ -225,7 +230,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 (![ @@ -236,8 +241,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 b03720cf..6a8bd949 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.withValues(alpha: 0.1), + color: ColorsManager.primaryColorWithOpacity.withOpacity(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 cd374eb5..e8c2e015 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), () {}); - Future _onCommunityUpdate( + void _onCommunityUpdate( OnCommunityUpdated event, Emitter emit, ) async { @@ -54,13 +54,12 @@ class SpaceTreeBloc extends Bloc { } } - Future _fetchSpaces( - InitialEvent event, Emitter emit) async { + _fetchSpaces(InitialEvent event, Emitter emit) async { emit(SpaceTreeLoadingState()); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final paginationModel = await CommunitySpaceManagementApi() + PaginationModel paginationModel = await CommunitySpaceManagementApi() .fetchCommunitiesAndSpaces(projectId: projectUuid, page: 1); // List updatedCommunities = await Future.wait( @@ -90,11 +89,10 @@ class SpaceTreeBloc extends Bloc { } } - Future _fetchPaginationSpaces( - PaginationEvent event, Emitter emit) async { + _fetchPaginationSpaces(PaginationEvent event, Emitter emit) async { emit(state.copyWith(paginationIsLoading: true)); - var paginationModel = event.paginationModel; - final communities = List.from(event.communities); + PaginationModel paginationModel = event.paginationModel; + List communities = List.from(event.communities); try { if (paginationModel.hasNext && state.searchQuery.isEmpty) { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -116,7 +114,7 @@ class SpaceTreeBloc extends Bloc { paginationIsLoading: false)); } - Future _onCommunityAdded( + void _onCommunityAdded( OnCommunityAdded event, Emitter emit) async { final updatedCommunities = List.from(state.communityList); updatedCommunities.add(event.newCommunity); @@ -124,11 +122,11 @@ class SpaceTreeBloc extends Bloc { emit(state.copyWith(communitiesList: updatedCommunities)); } - Future _onCommunityExpanded( + _onCommunityExpanded( OnCommunityExpanded event, Emitter emit) async { try { - final updatedExpandedCommunityList = - List.from(state.expandedCommunities); + List updatedExpandedCommunityList = + List.from(state.expandedCommunities); if (updatedExpandedCommunityList.contains(event.communityId)) { updatedExpandedCommunityList.remove(event.communityId); @@ -144,10 +142,9 @@ class SpaceTreeBloc extends Bloc { } } - Future _onSpaceExpanded( - OnSpaceExpanded event, Emitter emit) async { + _onSpaceExpanded(OnSpaceExpanded event, Emitter emit) async { try { - final updatedExpandedSpacesList = List.from(state.expandedSpaces); + List updatedExpandedSpacesList = List.from(state.expandedSpaces); if (updatedExpandedSpacesList.contains(event.spaceId)) { updatedExpandedSpacesList.remove(event.spaceId); @@ -161,21 +158,20 @@ class SpaceTreeBloc extends Bloc { } } - Future _onCommunitySelected( + _onCommunitySelected( OnCommunitySelected event, Emitter emit) async { try { - 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 = + 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 = communityAndSpaces[event.communityId] ?? []; - final childrenIds = _getAllChildIds(event.children); + List childrenIds = _getAllChildIds(event.children); if (!updatedSelectedCommunities.contains(event.communityId)) { // Select the community and all its children @@ -202,25 +198,23 @@ class SpaceTreeBloc extends Bloc { } } - Future _onSpaceSelected( - OnSpaceSelected event, Emitter emit) async { + _onSpaceSelected(OnSpaceSelected event, Emitter emit) async { try { - 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 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 selectedSpacesInCommunity = + List selectedSpacesInCommunity = communityAndSpaces[event.communityModel.uuid] ?? []; - final childrenIds = _getAllChildIds(event.children); - var isChildSelected = false; + List childrenIds = _getAllChildIds(event.children); + bool isChildSelected = false; - for (final id in childrenIds) { + for (String id in childrenIds) { if (updatedSelectedSpaces.contains(id)) { isChildSelected = true; } @@ -238,9 +232,9 @@ class SpaceTreeBloc extends Bloc { selectedSpacesInCommunity.addAll(childrenIds); } - final spaces = + List spaces = _getThePathToChild(event.communityModel.uuid, event.spaceId); - for (final space in spaces) { + for (String space in spaces) { if (!updatedSelectedSpaces.contains(space) && !updatedSoldChecks.contains(space)) { updatedSoldChecks.add(space); @@ -264,7 +258,7 @@ class SpaceTreeBloc extends Bloc { } updatedSoldChecks.remove(event.spaceId); - final parents = + List parents = _getThePathToChild(event.communityModel.uuid, event.spaceId) .toSet() .toList(); @@ -274,7 +268,7 @@ class SpaceTreeBloc extends Bloc { updatedSelectedCommunities.remove(event.communityModel.uuid); } else { // Check if any parent has selected children - for (final space in parents) { + for (String space in parents) { if (!_noChildrenSelected( event.communityModel, space, updatedSelectedSpaces, parents)) { updatedSoldChecks.remove(space); @@ -301,17 +295,17 @@ class SpaceTreeBloc extends Bloc { } } - bool _noChildrenSelected(CommunityModel community, String spaceId, + _noChildrenSelected(CommunityModel community, String spaceId, List selectedSpaces, List parents) { if (selectedSpaces.contains(spaceId)) { return true; } - final children = _getAllChildSpaces(community.spaces); - for (final child in children) { + List children = _getAllChildSpaces(community.spaces); + for (var child in children) { if (spaceId == child.uuid) { - final ids = _getAllChildIds(child.children); - for (final id in ids) { + List ids = _getAllChildIds(child.children); + for (var id in ids) { if (selectedSpaces.contains(id)) { return true; } @@ -322,15 +316,14 @@ class SpaceTreeBloc extends Bloc { return false; } - Future _onSearch( - SearchQueryEvent event, Emitter emit) async { + _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 = []; @@ -354,12 +347,12 @@ class SpaceTreeBloc extends Bloc { } } - Future _onDebouncedSearch( + _onDebouncedSearch( DebouncedSearchEvent event, Emitter emit) async { emit(state.copyWith( isSearching: true, )); - var paginationModel = const PaginationModel.emptyConstructor(); + PaginationModel paginationModel = const PaginationModel.emptyConstructor(); try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; @@ -374,8 +367,7 @@ class SpaceTreeBloc extends Bloc { searchQuery: event.searchQuery)); } - Future _clearAllData( - ClearAllData event, Emitter emit) async { + _clearAllData(ClearAllData event, Emitter emit) async { try { emit(state.copyWith( communitiesList: [], @@ -393,8 +385,7 @@ class SpaceTreeBloc extends Bloc { } } - Future _clearCachedData( - ClearCachedData event, Emitter emit) async { + _clearCachedData(ClearCachedData event, Emitter emit) async { try { emit(state.copyWith( communitiesList: state.communityList, @@ -422,8 +413,8 @@ class SpaceTreeBloc extends Bloc { // } List _getAllChildIds(List spaces) { - final ids = []; - for (final child in spaces) { + List ids = []; + for (var child in spaces) { ids.add(child.uuid!); ids.addAll(_getAllChildIds(child.children)); } @@ -431,8 +422,8 @@ class SpaceTreeBloc extends Bloc { } List _getAllChildSpaces(List spaces) { - final children = []; - for (final child in spaces) { + List children = []; + for (var child in spaces) { children.add(child); children.addAll(_getAllChildSpaces(child.children)); } @@ -441,9 +432,9 @@ class SpaceTreeBloc extends Bloc { bool _anySpacesSelectedInCommunity(CommunityModel community, List selectedSpaces, List partialCheckedList) { - var result = false; - final ids = _getAllChildIds(community.spaces); - for (final id in ids) { + bool result = false; + List ids = _getAllChildIds(community.spaces); + for (var id in ids) { result = selectedSpaces.contains(id) || partialCheckedList.contains(id); if (result) { return result; @@ -453,11 +444,11 @@ class SpaceTreeBloc extends Bloc { } List _getThePathToChild(String communityId, String selectedSpaceId) { - var ids = []; - for (final community in state.communityList) { + List ids = []; + for (var community in state.communityList) { if (community.uuid == communityId) { - for (final space in community.spaces) { - final list = []; + for (var space in community.spaces) { + List list = []; list.add(space.uuid!); ids = _getAllParentsIds(space, selectedSpaceId, List.from(list)); if (ids.isNotEmpty) { @@ -471,7 +462,7 @@ class SpaceTreeBloc extends Bloc { List _getAllParentsIds( SpaceModel child, String spaceId, List listIds) { - final ids = listIds; + List ids = listIds; ids.add(child.uuid ?? ''); @@ -480,8 +471,8 @@ class SpaceTreeBloc extends Bloc { } if (child.children.isNotEmpty) { - for (final space in child.children) { - final result = _getAllParentsIds(space, spaceId, List.from(ids)); + for (var space in child.children) { + var result = _getAllParentsIds(space, spaceId, List.from(ids)); if (result.isNotEmpty) { return result; } @@ -492,7 +483,7 @@ class SpaceTreeBloc extends Bloc { return []; } - Future _onSpaceTreeClearSelectionEvent( + void _onSpaceTreeClearSelectionEvent( SpaceTreeClearSelectionEvent event, Emitter emit, ) async { @@ -505,7 +496,7 @@ class SpaceTreeBloc extends Bloc { ); } - Future _onAnalyticsClearAllSpaceTreeSelectionsEvent( + void _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 175a9da6..595380fd 100644 --- a/lib/pages/space_tree/bloc/space_tree_state.dart +++ b/lib/pages/space_tree/bloc/space_tree_state.dart @@ -44,16 +44,15 @@ class SpaceTreeState extends Equatable { PaginationModel? paginationModel, bool? paginationIsLoading}) { return SpaceTreeState( - communityList: communitiesList ?? communityList, + communityList: communitiesList ?? this.communityList, filteredCommunity: filteredCommunity ?? this.filteredCommunity, expandedSpaces: expandedSpaces ?? this.expandedSpaces, - expandedCommunities: expandedCommunity ?? expandedCommunities, + expandedCommunities: expandedCommunity ?? this.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 624045e9..e84851c5 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/add_device_type/bloc/add_device_type_model_event.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'; 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 51b1ea34..254b78fd 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; - const UpdateProductCountEvent( + UpdateProductCountEvent( {required this.productId, required this.count, required this.productName, @@ -26,6 +26,7 @@ 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 e95bc74d..ede6afb9 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/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/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/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,7 +24,8 @@ 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 4bda7999..a4d6628e 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,19 +1,20 @@ 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'; @@ -56,10 +57,10 @@ class SpaceManagementBloc UpdateSpaceModelCache event, Emitter emit) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final allSpaceModels = []; + List allSpaceModels = []; - var hasNext = true; - var page = 1; + bool hasNext = true; + int page = 1; while (hasNext) { final spaceModels = await _spaceModelApi.listSpaceModels( @@ -84,7 +85,7 @@ class SpaceManagementBloc allTags: _cachedTags ?? [])); } - Future _deleteSpaceModelFromCache(DeleteSpaceModelFromCache event, + void _deleteSpaceModelFromCache(DeleteSpaceModelFromCache event, Emitter emit) async { if (_cachedSpaceModels != null) { _cachedSpaceModels = _cachedSpaceModels! @@ -120,10 +121,10 @@ class SpaceManagementBloc final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final allSpaceModels = []; + List allSpaceModels = []; - var hasNext = true; - var page = 1; + bool hasNext = true; + int page = 1; while (hasNext) { final spaceModels = await _spaceModelApi.listSpaceModels( @@ -158,7 +159,7 @@ class SpaceManagementBloc } } - Future _onUpdateCommunity( + void _onUpdateCommunity( UpdateCommunityEvent event, Emitter emit, ) async { @@ -174,7 +175,7 @@ class SpaceManagementBloc if (previousState is SpaceManagementLoaded) { final updatedCommunities = List.from(previousState.communities); - for (final community in updatedCommunities) { + for (var community in updatedCommunities) { if (community.uuid == event.communityUuid) { community.name = event.name; _spaceTreeBloc.add(OnCommunityAdded(community)); @@ -183,7 +184,7 @@ class SpaceManagementBloc } } - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); emit(SpaceManagementLoaded( communities: updatedCommunities, @@ -200,14 +201,14 @@ class SpaceManagementBloc } } - Future _onloadProducts() async { + void _onloadProducts() async { if (_cachedProducts == null) { final products = await _productApi.fetchProducts(); _cachedProducts = products; } } - Future _onFetchProducts( + void _onFetchProducts( FetchProductsEvent event, Emitter emit, ) async { @@ -222,7 +223,7 @@ class SpaceManagementBloc String communityUuid) async { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - return _api.getSpaceHierarchy(communityUuid, projectUuid); + return await _api.getSpaceHierarchy(communityUuid, projectUuid); } Future _onNewCommunity( @@ -237,7 +238,7 @@ class SpaceManagementBloc return; } - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); emit(BlankState( communities: event.communities, @@ -254,15 +255,15 @@ class SpaceManagementBloc try { final previousState = state; final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - final spaceBloc = event.context.read(); - final spaceTreeState = event.context.read().state; + var spaceBloc = event.context.read(); + var spaceTreeState = event.context.read().state; - final communities = + List communities = await _waitForCommunityList(spaceBloc, spaceTreeState); await fetchSpaceModels(); // await fetchTags(); - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); if (previousState is SpaceManagementLoaded || previousState is BlankState) { @@ -286,17 +287,18 @@ class SpaceManagementBloc } } - Future _onLoadCommunityAndSpaces( + void _onLoadCommunityAndSpaces( LoadCommunityAndSpacesEvent event, Emitter emit, ) async { - final spaceTreeState = event.context.read().state; - final spaceBloc = event.context.read(); + var spaceTreeState = event.context.read().state; + var spaceBloc = event.context.read(); _onloadProducts(); await fetchTags(); // Wait until `communityList` is loaded - final communities = await _waitForCommunityList(spaceBloc, spaceTreeState); + List communities = + await _waitForCommunityList(spaceBloc, spaceTreeState); // Fetch space models after communities are available final prevSpaceModels = await fetchSpaceModels(); @@ -342,7 +344,7 @@ class SpaceManagementBloc } } - Future _onCommunityDelete( + void _onCommunityDelete( DeleteCommunityEvent event, Emitter emit, ) async { @@ -363,7 +365,7 @@ class SpaceManagementBloc } } - Future _onCreateCommunity( + void _onCreateCommunity( CreateCommunityEvent event, Emitter emit, ) async { @@ -373,9 +375,9 @@ class SpaceManagementBloc try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; await fetchTags(); - final newCommunity = await _api.createCommunity( + CommunityModel? newCommunity = await _api.createCommunity( event.name, event.description, projectUuid); - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); if (newCommunity != null) { if (previousState is SpaceManagementLoaded || @@ -403,7 +405,7 @@ class SpaceManagementBloc } } - Future _onSelectCommunity( + void _onSelectCommunity( SelectCommunityEvent event, Emitter emit, ) async { @@ -429,7 +431,7 @@ class SpaceManagementBloc ); } - Future _handleCommunitySpaceStateUpdate({ + void _handleCommunitySpaceStateUpdate({ required Emitter emit, CommunityModel? selectedCommunity, SpaceModel? selectedSpace, @@ -462,7 +464,7 @@ class SpaceManagementBloc } } - Future _onSaveSpaces( + void _onSaveSpaces( SaveSpacesEvent event, Emitter emit, ) async { @@ -492,9 +494,9 @@ class SpaceManagementBloc event.spaces.removeWhere( (space) => space.status == SpaceStatus.deleted, ); - for (final space in event.spaces) { - space.status = SpaceStatus.unchanged; - } + event.spaces.forEach( + (space) => space.status = SpaceStatus.unchanged, + ); } } catch (e) { // emit(SpaceManagementError('Error saving spaces: $e')); @@ -513,7 +515,7 @@ class SpaceManagementBloc Emitter emit, ) async { try { - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); await fetchTags(); @@ -521,7 +523,7 @@ class SpaceManagementBloc ? spaceTreeState.filteredCommunity : spaceTreeState.communityList; - for (final community in communities) { + for (var community in communities) { if (community.uuid == communityUuid) { community.spaces = allSpaces; _spaceTreeBloc.add(InitialEvent()); @@ -538,7 +540,7 @@ class SpaceManagementBloc } } emit(previousState); - } catch (e) { + } catch (e, stackTrace) { emit(previousState); // rethrow; } @@ -575,36 +577,36 @@ class SpaceManagementBloc space.status == SpaceStatus.deleted && (space.parent == null || space.parent?.status != SpaceStatus.deleted)); - for (final parent in parentsToDelete) { + for (var parent in parentsToDelete) { try { if (parent.uuid != null) { await _api.deleteSpace(communityUuid, parent.uuid!, projectUuid); } } catch (e) {} } - orderedSpaces.removeWhere(parentsToDelete.contains); + orderedSpaces.removeWhere((space) => parentsToDelete.contains(space)); - for (final space in orderedSpaces) { + for (var space in orderedSpaces) { try { if (space.uuid != null && space.uuid!.isNotEmpty) { - var tagUpdates = []; + List tagUpdates = []; - final matchedSpaces = + List matchedSpaces = findMatchingSpaces(selectedCommunity.spaces, space.uuid!); if (matchedSpaces.isEmpty) continue; final prevSpace = matchedSpaces.elementAtOrNull(0); - final subspaceUpdates = []; - final prevSubspaces = prevSpace?.subspaces; - final newSubspaces = space.subspaces; + final List subspaceUpdates = []; + final List? prevSubspaces = prevSpace?.subspaces; + final List? newSubspaces = space.subspaces; tagUpdates = processTagUpdates(prevSpace?.tags, space.tags); if (prevSubspaces != null || newSubspaces != null) { if (prevSubspaces != null && newSubspaces != null) { - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { final existsInNew = newSubspaces .any((subspace) => subspace.uuid == prevSubspace.uuid); if (!existsInNew) { @@ -614,7 +616,7 @@ class SpaceManagementBloc } } } else if (prevSubspaces != null && newSubspaces == null) { - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { subspaceUpdates.add(UpdateSubspaceTemplateModel( action: custom_action.Action.delete, uuid: prevSubspace.uuid)); @@ -622,13 +624,13 @@ class SpaceManagementBloc } if (newSubspaces != null) { - for (final newSubspace in newSubspaces) { + for (var newSubspace in newSubspaces) { // Tag without UUID - if (newSubspace.uuid == null || newSubspace.uuid!.isEmpty) { - final tagUpdates = []; + if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) { + final List tagUpdates = []; if (newSubspace.tags != null) { - for (final tag in newSubspace.tags!) { + for (var tag in newSubspace.tags!) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.add, newTagUuid: tag.uuid == '' ? null : tag.uuid, @@ -646,14 +648,14 @@ class SpaceManagementBloc if (prevSubspaces != null && newSubspaces != null) { final newSubspaceMap = { - for (final subspace in newSubspaces) subspace.uuid: subspace + for (var subspace in newSubspaces) subspace.uuid: subspace }; - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { final newSubspace = newSubspaceMap[prevSubspace.uuid]; if (newSubspace != null) { - final tagSubspaceUpdates = + final List tagSubspaceUpdates = processTagUpdates(prevSubspace.tags, newSubspace.tags); subspaceUpdates.add(UpdateSubspaceTemplateModel( action: custom_action.Action.update, @@ -667,7 +669,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, @@ -681,7 +683,7 @@ class SpaceManagementBloc projectId: projectUuid); } else { // Call create if the space does not have a UUID - var tagBodyModels = space.tags != null + List tagBodyModels = space.tags != null ? space.tags!.map((tag) => tag.toCreateTagBodyModel()).toList() : []; @@ -729,17 +731,17 @@ class SpaceManagementBloc void visit(SpaceModel space) { if (!result.contains(space)) { result.add(space); - for (final child in spaces.where((s) => s.parent == space)) { + for (var child in spaces.where((s) => s.parent == space)) { visit(child); } } } - for (final space in topLevelSpaces) { + for (var space in topLevelSpaces) { visit(space); } - for (final space in spaces) { + for (var space in spaces) { if (!result.contains(space)) { result.add(space); } @@ -747,7 +749,7 @@ class SpaceManagementBloc return result.toList(); // Convert back to a list } - Future _onLoadSpaceModel( + void _onLoadSpaceModel( SpaceModelLoadEvent event, Emitter emit) async { emit(SpaceManagementLoading()); @@ -758,9 +760,9 @@ class SpaceManagementBloc ? spaceTreeState.filteredCommunity : spaceTreeState.communityList; - final communities = filteredCommunities; + List communities = filteredCommunities; - final prevSpaceModels = await fetchSpaceModels(); + var prevSpaceModels = await fetchSpaceModels(); emit(SpaceModelLoaded( communities: communities, @@ -776,11 +778,11 @@ class SpaceManagementBloc List? prevTags, List? newTags, ) { - final tagUpdates = []; + final List tagUpdates = []; final processedTags = {}; if (prevTags == null && newTags != null) { - for (final newTag in newTags) { + for (var newTag in newTags) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.add, tag: newTag.tag, @@ -794,7 +796,7 @@ class SpaceManagementBloc if (newTags != null || prevTags != null) { // Case 1: Tags deleted if (prevTags != null && newTags != null) { - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { final existsInNew = newTags.any((newTag) => newTag.uuid == prevTag.uuid); if (!existsInNew) { @@ -803,7 +805,7 @@ class SpaceManagementBloc } } } else if (prevTags != null && newTags == null) { - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { tagUpdates.add(TagModelUpdate( action: custom_action.Action.delete, uuid: prevTag.uuid)); } @@ -813,7 +815,7 @@ class SpaceManagementBloc if (newTags != null) { final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {}; - for (final newTag in newTags) { + for (var newTag in newTags) { // Tag without UUID if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) && !processedTags.contains(newTag.tag)) { @@ -829,9 +831,9 @@ class SpaceManagementBloc // Case 3: Tags updated if (prevTags != null && newTags != null) { - final newTagMap = {for (final tag in newTags) tag.uuid: tag}; + final newTagMap = {for (var tag in newTags) tag.uuid: tag}; - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { final newTag = newTagMap[prevTag.uuid]; if (newTag != null) { tagUpdates.add(TagModelUpdate( @@ -850,9 +852,9 @@ class SpaceManagementBloc List findMatchingSpaces( List spaces, String targetUuid) { - final matched = []; + List matched = []; - for (final space in spaces) { + for (var 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 b6c90304..8a9db432 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; - const UpdateSpaceModelCache(this.updatedModel); + UpdateSpaceModelCache(this.updatedModel); } class DeleteSpaceModelFromCache extends SpaceManagementEvent { final String deletedUuid; - const DeleteSpaceModelFromCache(this.deletedUuid); + 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 361be6c9..3efa7c00 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,10 +40,7 @@ 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 44babc9e..57f223f4 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 23388375..d1e27095 100644 --- a/lib/pages/spaces_management/all_spaces/model/community_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/community_model.dart @@ -27,12 +27,9 @@ 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() : [], ); } @@ -45,9 +42,7 @@ 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 9ed528ed..8f905032 100644 --- a/lib/pages/spaces_management/all_spaces/model/product_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/product_model.dart @@ -1,6 +1,7 @@ -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 17fd429c..91314e42 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,11 +6,7 @@ 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 { @@ -20,7 +16,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 50cdb36c..f9c59d24 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 children = json['children'] != null + final List 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?) - ?.whereType>() // Validate type - .map(SubspaceModel.fromJson) + ?.where((e) => e is Map) // Validate type + .map((e) => SubspaceModel.fromJson(e as Map)) .toList() ?? [], parent: parentInternalId != null @@ -102,8 +102,8 @@ class SpaceModel { ? SpaceTemplateModel.fromJson(json['spaceModel']) : null, tags: (json['productAllocations'] as List?) - ?.whereType>() // Validate type - .map(Tag.fromJson) + ?.where((item) => item is Map) // Validate type + .map((item) => Tag.fromJson(item as Map)) .toList() ?? [], ); @@ -150,7 +150,7 @@ class SpaceModel { extension SpaceExtensions on SpaceModel { List listAllTagValues() { - final tagValues = []; + final List 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 d698b48b..34df3d30 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,4 +1,5 @@ -import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; + +import '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 9c1defa8..fd3e780e 100644 --- a/lib/pages/spaces_management/all_spaces/model/subspace_model.dart +++ b/lib/pages/spaces_management/all_spaces/model/subspace_model.dart @@ -1,8 +1,9 @@ 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 f17c3d86..a7ec1e15 100644 --- a/lib/pages/spaces_management/all_spaces/model/tag.dart +++ b/lib/pages/spaces_management/all_spaces/model/tag.dart @@ -6,12 +6,18 @@ import 'package:uuid/uuid.dart'; class Tag extends BaseTag { Tag({ - super.uuid, - required super.tag, - super.product, - super.internalId, - super.location, - }); + String? uuid, + required String? tag, + ProductModel? product, + String? internalId, + String? location, + }) : super( + uuid: uuid, + tag: tag, + product: product, + internalId: internalId, + location: location, + ); factory Tag.fromJson(Map json) { final String internalId = json['internalId'] ?? const Uuid().v4(); @@ -44,7 +50,6 @@ 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 9094ebc0..291e6235 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: const CenterBodyWidget(), + centerBody: 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 71bda2ca..0e9f4bd1 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,9 +32,8 @@ 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 @@ -97,12 +96,10 @@ 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); @@ -117,11 +114,7 @@ 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( @@ -150,17 +143,13 @@ 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) { @@ -203,8 +192,7 @@ 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 18dec3a1..66f1a026 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; - const BlankCommunityWidget({super.key, required this.communities}); + BlankCommunityWidget({required this.communities}); @override _BlankCommunityWidgetState createState() => _BlankCommunityWidgetState(); @@ -19,7 +19,7 @@ class _BlankCommunityWidgetState extends State { @override Widget build(BuildContext context) { return Expanded( - child: ColoredBox( + child: Container( 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 49a19681..f5188c1e 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 9a45d76a..6bc35cca 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 1e882d8a..4f68fb7e 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,23 +3,24 @@ 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/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/curved_line_painter.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'; @@ -40,8 +41,7 @@ class CommunityStructureArea extends StatefulWidget { final List projectTags; CommunityStructureArea( - {super.key, - this.selectedCommunity, + {this.selectedCommunity, this.selectedSpace, required this.communities, this.products, @@ -120,7 +120,7 @@ class _CommunityStructureAreaState extends State { ); } - final screenSize = MediaQuery.of(context).size; + Size screenSize = MediaQuery.of(context).size; return Expanded( child: GestureDetector( onTap: () { @@ -173,16 +173,16 @@ class _CommunityStructureAreaState extends State { children: [ InteractiveViewer( transformationController: _transformationController, - boundaryMargin: const EdgeInsets.all(500), + boundaryMargin: EdgeInsets.all(500), minScale: 0.5, maxScale: 3.0, constrained: false, - child: SizedBox( + child: Container( width: canvasWidth, height: canvasHeight, child: Stack( children: [ - for (final connection in connections) + for (var connection in connections) Opacity( opacity: ConnectionHelper.isHighlightedConnection( connection, widget.selectedSpace) @@ -191,7 +191,7 @@ class _CommunityStructureAreaState extends State { child: CustomPaint( painter: CurvedLinePainter([connection])), ), - for (final entry in spaces.asMap().entries) + for (var 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 isHighlighted = + final bool isHighlighted = SpaceHelper.isHighlightedSpace( spaces[index], widget.selectedSpace); @@ -267,9 +267,9 @@ class _CommunityStructureAreaState extends State { canvasHeight += 200; } if (node.position.dx <= 200) { - const double shiftAmount = 200; + double shiftAmount = 200; canvasWidth += shiftAmount; - for (final n in spaces) { + for (var n in spaces) { n.position = Offset(n.position.dx + shiftAmount, n.position.dy); } } @@ -280,7 +280,7 @@ class _CommunityStructureAreaState extends State { } void _adjustCanvasSizeForSpaces() { - for (final space in spaces) { + for (var 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); } - final newSpace = SpaceModel( + SpaceModel newSpace = SpaceModel( name: name, icon: icon, position: newPosition, @@ -336,7 +336,7 @@ class _CommunityStructureAreaState extends State { tags: tags); if (parentIndex != null) { - final parentSpace = spaces[parentIndex]; + SpaceModel 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 (final space in spaces) { + for (var 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) { - final result = []; - final idToSpace = {}; + List result = []; + Map 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 (final child in space.children) { + for (var child in space.children) { flatten(child); } } - for (final space in spaces) { + for (var space in spaces) { flatten(space); } - for (final space in result) { + for (var 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) { - final connections = []; + List connections = []; void addConnections(SpaceModel parent, String direction) { if (parent.status == SpaceStatus.deleted) return; - for (final child in parent.children) { + for (var child in parent.children) { if (child.status == SpaceStatus.deleted) continue; connections.add( @@ -480,8 +480,8 @@ class _CommunityStructureAreaState extends State { } } - for (final space in spaces) { - addConnections(space, 'down'); + for (var space in spaces) { + addConnections(space, "down"); } return connections; @@ -492,7 +492,7 @@ class _CommunityStructureAreaState extends State { return; } - final spacesToSave = spaces.where((space) { + List 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; } - final communityUuid = widget.selectedCommunity!.uuid; + String 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 (final space in spaces) { + for (var 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 (final child in parent.children) { + for (var child in parent.children) { child.status = SpaceStatus.parentDeleted; _markChildrenAsDeleted(child); @@ -543,11 +543,11 @@ class _CommunityStructureAreaState extends State { } void _moveToSpace(SpaceModel space) { - final viewportWidth = MediaQuery.of(context).size.width; - final viewportHeight = MediaQuery.of(context).size.height; + final double viewportWidth = MediaQuery.of(context).size.width; + final double viewportHeight = MediaQuery.of(context).size.height; - final dx = -space.position.dx + (viewportWidth / 2) - 400; - final dy = -space.position.dy + (viewportHeight / 2) - 300; + final double dx = -space.position.dx + (viewportWidth / 2) - 400; + final double 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 - final totalWidth = (parent.children.length) * (nodeWidth + 60); - final startX = parent.position.dx - (totalWidth / 2); + double totalWidth = (parent.children.length) * (nodeWidth + 60); + double startX = parent.position.dx - (totalWidth / 2); - final childX = startX + (parent.children.length * (nodeWidth + 60)); + double 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 (final child in node.children) { + for (var child in node.children) { totalWidth += calculateSubtreeWidth(child) + horizontalGap; } return totalWidth - horizontalGap; } void layoutSubtree(SpaceModel node, double startX, double y) { - final subtreeWidth = calculateSubtreeWidth(node); - final centerX = startX + subtreeWidth / 2 - nodeWidth / 2; + double subtreeWidth = calculateSubtreeWidth(node); + double 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 { - var childX = startX; - for (final child in node.children) { - final childWidth = calculateSubtreeWidth(child); + double childX = startX; + for (var child in node.children) { + double 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 roots = spaces + final List 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 - const double currentY = 100; // top margin + double currentY = 100; // top margin - for (final root in roots) { + for (var root in roots) { layoutSubtree(root, currentX, currentY); - final rootWidth = calculateSubtreeWidth(root); + double 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(() { - final parent = space.parent; + SpaceModel? parent = space.parent; - final duplicated = _deepCloneSpaceTree(space, parent: parent); + SpaceModel duplicated = _deepCloneSpaceTree(space, parent: parent); duplicated.position = Offset(space.position.dx + 300, space.position.dy + 100); - final duplicatedSubtree = []; + List duplicatedSubtree = []; void collectSubtree(SpaceModel node) { duplicatedSubtree.add(node); - for (final child in node.children) { + for (var child in node.children) { collectSubtree(child); } } @@ -782,7 +782,7 @@ class _CommunityStructureAreaState extends State { parent: parent, ); - for (final child in original.children) { + for (var 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 bd8c0a98..2289819b 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/counter_widget.dart @@ -7,10 +7,11 @@ class CounterWidget extends StatefulWidget { final bool isCreate; const CounterWidget( - {super.key, + {Key? key, this.initialCount = 0, required this.onCountChanged, - required this.isCreate}); + required this.isCreate}) + : super(key: key); @override State createState() => _CounterWidgetState(); @@ -54,8 +55,7 @@ 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,15 +69,12 @@ 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.withValues(alpha: 0.3) - : ColorsManager.spaceColor, + color: isDisabled? ColorsManager.spaceColor.withOpacity(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 caa71183..94896554 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,11 +1,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.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'; + +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'; class DevicesPartWidget extends StatelessWidget { const DevicesPartWidget({ @@ -27,73 +28,73 @@ class DevicesPartWidget extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - 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, + (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, + ), + ), ), ), - 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) - ], - ), - ), - ) - else - TextButton( - onPressed: onTextButtonPressed, - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - ), - child: ButtonContentWidget( - icon: Icons.add, - label: 'Add Devices', - disabled: isTagsAndSubspaceModelDisabled, - ), - ) + EditChip(onTap: onEditChip) + ], + ), + ), + ) + : 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 94467180..59a100a3 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 'package:syncrow_web/utils/color_manager.dart'; -import 'package:syncrow_web/utils/constants/assets.dart'; +import '../../../../../utils/color_manager.dart'; +import '../../../../../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 ceedad63..cd9ae470 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,8 +1,9 @@ import 'package:flutter/material.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'; + +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'; class SpaceModelLinkingWidget extends StatelessWidget { const SpaceModelLinkingWidget({ @@ -22,67 +23,66 @@ class SpaceModelLinkingWidget extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - 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, + 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), ), - ), - child: const Icon( - Icons.close, - size: 16, - color: ColorsManager.lightGrayColor, - ), - ), - onDeleted: onDeleted), - ], - ), - ), + 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), + ], + ), + ), ], ); } 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 5700b9c5..600cb8ad 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 'package:syncrow_web/utils/color_manager.dart'; +import '../../../../../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 868eefe5..e518877a 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,9 +1,10 @@ import 'package:flutter/material.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'; + +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'; class SubSpacePartWidget extends StatefulWidget { SubSpacePartWidget({ @@ -29,72 +30,71 @@ class _SubSpacePartWidgetState extends State { Widget build(BuildContext context) { return Column( children: [ - 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 + widget.subspaces == null || widget.subspaces!.isEmpty + ? TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + overlayColor: ColorsManager.transparentColor, ), - ), - 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(); + 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(); - 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 d0c3bd83..d8291110 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,11 +19,15 @@ class CurvedLinePainter extends CustomPainter { return; // Nothing to paint if there are no connections } - for (final connection in connections) { + for (var connection in connections) { // Ensure positions are valid before drawing lines - final start = connection.startSpace.position + + if (connection.endSpace.position == null) { + continue; + } + + Offset start = connection.startSpace.position + const Offset(75, 60); // Center bottom of start space - final end = connection.endSpace.position + + Offset 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 f6f7bded..8cf30f7c 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,6 +9,7 @@ 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'; @@ -98,9 +99,9 @@ class CreateSpaceDialogState extends State { @override Widget build(BuildContext context) { - final isSpaceModelDisabled = tags != null && tags!.isNotEmpty || - subspaces != null && subspaces!.isNotEmpty; - final isTagsAndSubspaceModelDisabled = (selectedSpaceModel != null); + bool isSpaceModelDisabled = (tags != null && tags!.isNotEmpty || + subspaces != null && subspaces!.isNotEmpty); + bool isTagsAndSubspaceModelDisabled = (selectedSpaceModel != null); final screenWidth = MediaQuery.of(context).size.width; return AlertDialog( @@ -297,7 +298,7 @@ class CreateSpaceDialogState extends State { } else if (isNameFieldExist) { return; } else { - final newName = enteredName.isNotEmpty + String newName = enteredName.isNotEmpty ? enteredName : (widget.name ?? ''); if (newName.isNotEmpty) { @@ -380,7 +381,7 @@ class CreateSpaceDialogState extends State { products: products, existingSubSpaces: existingSubSpaces, onSave: (slectedSubspaces, updatedSubSpaces) { - final tagsToAppendToSpace = []; + final List tagsToAppendToSpace = []; if (slectedSubspaces != null && slectedSubspaces.isNotEmpty) { final updatedIds = @@ -389,11 +390,11 @@ class CreateSpaceDialogState extends State { final deletedSubspaces = existingSubSpaces .where((s) => !updatedIds.contains(s.internalId)) .toList(); - for (final s in deletedSubspaces) { + for (var s in deletedSubspaces) { if (s.tags != null) { - for (final tag in s.tags!) { - tag.location = null; - } + s.tags!.forEach( + (tag) => tag.location = null, + ); tagsToAppendToSpace.addAll(s.tags!); } } @@ -402,11 +403,11 @@ class CreateSpaceDialogState extends State { if (existingSubSpaces != null) { final deletedSubspaces = existingSubSpaces; - for (final s in deletedSubspaces) { + for (var s in deletedSubspaces) { if (s.tags != null) { - for (final tag in s.tags!) { - tag.location = null; - } + s.tags!.forEach( + (tag) => 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 dd04bec6..27275be1 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,10 +2,9 @@ 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 title = isSpace ? 'Delete Space' : 'Delete Community'; - final subtitle = isSpace +void showDeleteConfirmationDialog(BuildContext context, VoidCallback onConfirm, bool isSpace) { + final String title = isSpace ? 'Delete Space' : 'Delete Community'; + final String subtitle = isSpace ? 'All the data in the space will be lost' : 'All the data in the community will be lost'; @@ -14,8 +13,7 @@ void showDeleteConfirmationDialog( 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( @@ -43,8 +41,7 @@ void showDeleteConfirmationDialog( 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)), ), ], ), @@ -57,17 +54,15 @@ void showDeleteConfirmationDialog( ); } -void showProcessingPopup( - BuildContext context, bool isSpace, VoidCallback onDelete) { - final title = isSpace ? 'Delete Space' : 'Delete Community'; +void showProcessingPopup(BuildContext context, bool isSpace, VoidCallback onDelete) { + final String 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( @@ -80,8 +75,7 @@ void showProcessingPopup( 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, @@ -89,8 +83,7 @@ void showProcessingPopup( 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', @@ -111,7 +104,7 @@ Widget _buildWarningIcon() { return Container( width: 50, height: 50, - decoration: const BoxDecoration( + decoration: BoxDecoration( color: ColorsManager.warningRed, shape: BoxShape.circle, ), @@ -130,10 +123,7 @@ 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 f3c7dda6..1f719b1a 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,7 +4,8 @@ import 'package:syncrow_web/utils/color_manager.dart'; class DuplicateProcessDialog extends StatefulWidget { final VoidCallback onDuplicate; - const DuplicateProcessDialog({required this.onDuplicate, super.key}); + const DuplicateProcessDialog({required this.onDuplicate, Key? key}) + : super(key: key); @override _DuplicateProcessDialogState createState() => _DuplicateProcessDialogState(); @@ -19,7 +20,7 @@ class _DuplicateProcessDialogState extends State { _startDuplication(); } - Future _startDuplication() async { + void _startDuplication() async { WidgetsBinding.instance.addPostFrameCallback((_) { widget.onDuplicate(); }); @@ -54,7 +55,7 @@ class _DuplicateProcessDialogState extends State { ), const SizedBox(height: 15), Text( - 'Duplicating in progress', + "Duplicating in progress", style: Theme.of(context) .textTheme .headlineSmall @@ -69,7 +70,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 71b9efef..b2a01988 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({ - super.key, + Key? key, required this.spaceIconList, required this.onIconSelected, - }); + }) : super(key: key); @override Widget build(BuildContext context) { @@ -21,23 +21,21 @@ 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 - .withValues(alpha: 0.2), // Shadow color + color: ColorsManager.blackColor.withOpacity(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 e0ca8827..e1d4e11b 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.withValues(alpha: 0.1), + ColorsManager.semiTransparentBlackColor.withOpacity(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 e545f26b..49a863b6 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({ - super.key, + Key? key, required this.iconPath, required this.text, required this.onTap, - }); + }) : super(key: key); @override State createState() => _HoverableButtonState(); @@ -34,17 +34,14 @@ 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.withValues(alpha: 0.4), + color: ColorsManager.warningRed.withOpacity(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 d2a7c3de..d2c72fa7 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,51 +81,49 @@ class _LoadedSpaceViewState extends State { return Stack( clipBehavior: Clip.none, children: [ - 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 ?? [], + 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, + ), + ), ), - child: SpaceModelPage( + ], + ) + : 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, - onSpaceModelsUpdated: _onSpaceModelsUpdated, + communities: widget.communities, + spaceModels: _spaceModels, 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 283bffac..7076a580 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({ - super.key, + Key? key, required this.products, required this.selectedProducts, required this.onProductsUpdated, required this.context, - }); + }) : super(key: key); @override Widget build(BuildContext context) { @@ -86,7 +86,9 @@ class SelectedProductsButtons extends StatelessWidget { builder: (context) => AddDeviceWidget( products: products, initialSelectedProducts: selectedProducts, - onProductsSelected: onProductsUpdated, + onProductsSelected: (selectedProductsMap) { + onProductsUpdated(selectedProductsMap); + }, ), ); } 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 3e2ad4dd..6149dbda 100644 --- a/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart +++ b/lib/pages/spaces_management/all_spaces/widgets/sidebar_widget.dart @@ -5,7 +5,6 @@ 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'; @@ -19,6 +18,8 @@ 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; @@ -54,15 +55,13 @@ 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, ), ); @@ -135,28 +134,24 @@ 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) - const Center( + if (spaceTreeState.paginationIsLoading || spaceTreeState.isSearching) + Center( child: CircularProgressIndicator(), ) ], @@ -219,8 +214,7 @@ class _SidebarWidgetState extends State { }); context.read().add( - SelectSpaceEvent( - selectedCommunity: community, selectedSpace: space), + SelectSpaceEvent(selectedCommunity: community, selectedSpace: space), ); }, children: space.children @@ -235,9 +229,8 @@ 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 344eddd3..7e6e132f 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 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/plus_button_widget.dart'; // Make sure to import your PlusButtonWidget +import '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 e43bccd3..6f52eb50 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.withValues(alpha: 0.5), + color: ColorsManager.lightGrayColor.withOpacity(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 1e805cb3..62d8197c 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.withValues(alpha: 0.5), + color: ColorsManager.lightGrayColor.withOpacity(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 7496eb16..afc0c852 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 (final tag in initialTags) { + for (var 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 (final selectedProduct in event.addedProducts) { + for (var 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 b79fb699..7d81ffdb 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/selected_product_model.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'; 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 3fda79bf..53700a33 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,8 +27,7 @@ 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 809dff64..21ba141c 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,10 +7,11 @@ 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; @@ -38,7 +39,7 @@ class AssignTagDialog extends StatelessWidget { @override Widget build(BuildContext context) { - final locations = (subspaces ?? []) + final List 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 c5b164cf..a81b7ad0 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,13 +1,14 @@ 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/spaces_management/helper/tag_helper.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/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 4a6548f8..7df82b5e 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,8 +3,7 @@ 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()) { @@ -12,29 +11,25 @@ class AssignTagModelBloc final initialTags = event.initialTags; final existingTagCounts = {}; - for (final tag in initialTags) { + for (var 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 (final selectedProduct in event.addedProducts) { + for (var 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( @@ -59,8 +54,7 @@ class AssignTagModelBloc 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; @@ -87,12 +81,10 @@ class AssignTagModelBloc 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); @@ -108,8 +100,7 @@ class AssignTagModelBloc 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( @@ -124,10 +115,8 @@ class AssignTagModelBloc 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); @@ -151,10 +140,8 @@ class AssignTagModelBloc 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) { @@ -175,13 +162,12 @@ class AssignTagModelBloc 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 d62e1523..cb878bde 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/selected_product_model.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'; 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 4f0fcee5..57ed93df 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,12 +6,13 @@ 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; @@ -29,7 +30,7 @@ class AssignTagModelsDialog extends StatelessWidget { final List projectTags; const AssignTagModelsDialog( - {super.key, + {Key? key, required this.products, required this.subspaces, required this.addedProducts, @@ -42,11 +43,12 @@ class AssignTagModelsDialog extends StatelessWidget { this.otherSpaceModels, this.spaceModel, this.allSpaceModels, - required this.projectTags}); + required this.projectTags}) + : super(key: key); @override Widget build(BuildContext context) { - final locations = (subspaces ?? []) + final List 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 72f8be87..9b2a1367 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,17 +1,18 @@ 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/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'; + +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'; 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 ee335637..0e17a0d7 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,10 +1,11 @@ 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 e52f09bf..724ed51a 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,9 +1,8 @@ import 'package:flutter_bloc/flutter_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 'community_dialog_event.dart'; +import '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 9321cc1e..13e676b5 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.withValues(alpha: 0.25), + color: ColorsManager.blackColor.withOpacity(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) { - var isNameValid = true; - var isNameEmpty = false; + bool isNameValid = true; + bool 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 bd14ff61..a2d44553 100644 --- a/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart +++ b/lib/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart @@ -1,9 +1,10 @@ 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) { @@ -76,7 +77,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 3e54288d..82df866a 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,11 +5,12 @@ 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 65bd0193..3952e105 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,11 +1,12 @@ 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 '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'; + +import '../../bloc/subspace_bloc.dart'; +import '../../bloc/subspace_event.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 7375a228..f655e178 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,13 +1,14 @@ 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 3337ce04..a331aed2 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 0a9c9610..098b4804 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,8 +28,7 @@ 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 45ee9777..4049eb7e 100644 --- a/lib/pages/spaces_management/helper/space_helper.dart +++ b/lib/pages/spaces_management/helper/space_helper.dart @@ -2,20 +2,18 @@ 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 (final community in communities) { - for (final space in community.spaces) { + static SpaceModel? findSpaceByUuid(String? uuid, List communities) { + for (var community in communities) { + for (var 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 (final space in spaces) { + for (var space in spaces) { if (space.internalId == internalId) return space; } } @@ -23,22 +21,21 @@ 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(); - var maxNumber = 0; + int maxNumber = 0; - for (final space in spaces) { + for (var space in spaces) { final match = RegExp(r'^(.*?)\((\d+)\)$').firstMatch(space.name); if (match != null && match.group(1)?.trim() == baseName) { - final existingNumber = int.parse(match.group(2)!); + int existingNumber = int.parse(match.group(2)!); if (existingNumber > maxNumber) { maxNumber = existingNumber; } } } - return '$baseName(${maxNumber + 1})'; + return "$baseName(${maxNumber + 1})"; } static bool isSave(List spaces) { @@ -54,13 +51,10 @@ 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() ?? @@ -71,19 +65,17 @@ 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 f810b8ba..e1dc3cc3 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 (final subspace in subspaces) { + for (var subspace in subspaces) { getSubspaceTags(subspace)?.removeWhere( (tag) => !modifiedTags.any( (updatedTag) => getInternalId(updatedTag) == getInternalId(tag)), @@ -32,7 +32,7 @@ class TagHelper { } } - for (final tag in modifiedTags.toList()) { + for (var tag in modifiedTags.toList()) { if (modifiedSubspaces.isEmpty) continue; final prevIndice = checkTagExistInSubspace(tag, modifiedSubspaces); @@ -131,7 +131,8 @@ class TagHelper { static List getAvailableTagModels( List allTags, List currentTags, Tag currentTag) { - final availableTagsForTagModel = TagHelper.getAvailableTags( + List availableTagsForTagModel = + TagHelper.getAvailableTags( allTags: allTags, currentTags: currentTags, currentTag: currentTag, @@ -144,14 +145,14 @@ class TagHelper { List? spaceTagModels, List? subspaces, }) { - final initialTags = []; + final List initialTags = []; if (spaceTagModels != null) { initialTags.addAll(spaceTagModels); } if (subspaces != null) { - for (final subspace in subspaces) { + for (var subspace in subspaces) { if (subspace.tags != null) { initialTags.addAll( subspace.tags!.map( @@ -173,14 +174,14 @@ class TagHelper { List? spaceTags, List? subspaces, }) { - final initialTags = []; + final List initialTags = []; if (spaceTags != null) { initialTags.addAll(spaceTags); } if (subspaces != null) { - for (final subspace in subspaces) { + for (var subspace in subspaces) { if (subspace.tags != null) { initialTags.addAll( subspace.tags!.map( @@ -199,8 +200,8 @@ class TagHelper { } static Map groupTags(List tags) { - final groupedTags = {}; - for (final tag in tags) { + final Map groupedTags = {}; + for (var tag in tags) { if (tag.product != null) { final product = tag.product!; groupedTags[product] = (groupedTags[product] ?? 0) + 1; @@ -211,10 +212,10 @@ class TagHelper { static List createInitialSelectedProducts( List? tags, List? subspaces) { - final productCounts = {}; + final Map productCounts = {}; if (tags != null) { - for (final tag in tags) { + for (var tag in tags) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; } @@ -222,9 +223,9 @@ class TagHelper { } if (subspaces != null) { - for (final subspace in subspaces) { + for (var subspace in subspaces) { if (subspace.tags != null) { - for (final tag in subspace.tags!) { + for (var tag in subspace.tags!) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; @@ -246,10 +247,10 @@ class TagHelper { static List createInitialSelectedProductsForTags( List? tags, List? subspaces) { - final productCounts = {}; + final Map productCounts = {}; if (tags != null) { - for (final tag in tags) { + for (var tag in tags) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; } @@ -257,9 +258,9 @@ class TagHelper { } if (subspaces != null) { - for (final subspace in subspaces) { + for (var subspace in subspaces) { if (subspace.tags != null) { - for (final tag in subspace.tags!) { + for (var tag in subspace.tags!) { if (tag.product != null) { productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1; @@ -279,13 +280,14 @@ class TagHelper { .toList(); } - static int? checkTagExistInSubspaceModels(Tag tag, List? subspaces) { + static int? checkTagExistInSubspaceModels( + Tag tag, List? subspaces) { if (subspaces == null) return null; - for (var i = 0; i < subspaces.length; i++) { + for (int i = 0; i < subspaces.length; i++) { final subspace = subspaces[i] as SubspaceTemplateModel; // Explicit cast if (subspace.tags == null) continue; - for (final t in subspace.tags!) { + for (var t in subspace.tags!) { if (tag.internalId == t.internalId) { return i; } @@ -312,11 +314,11 @@ class TagHelper { final processedSubspaces = List.from(result['subspaces'] as List); - for (final subspace in processedSubspaces) { + for (var subspace in processedSubspaces) { final subspaceTags = subspace.tags; if (subspaceTags != null) { - for (var i = 0; i < subspaceTags.length; i++) { + for (int i = 0; i < subspaceTags.length; i++) { final tag = subspaceTags[i]; // Find the updated tag inside processedTags @@ -339,10 +341,10 @@ class TagHelper { static int? checkTagExistInSubspace(Tag tag, List? subspaces) { if (subspaces == null) return null; - for (var i = 0; i < subspaces.length; i++) { + for (int i = 0; i < subspaces.length; i++) { final subspace = subspaces[i]; if (subspace.tags == null) continue; - for (final t in subspace.tags!) { + for (var t in subspace.tags!) { if (tag.internalId == t.internalId) { return i; } @@ -369,11 +371,11 @@ class TagHelper { final processedSubspaces = List.from(result['subspaces'] as List); - for (final subspace in processedSubspaces) { + for (var subspace in processedSubspaces) { final subspaceTags = subspace.tags; if (subspaceTags != null) { - for (var i = 0; i < subspaceTags.length; i++) { + for (int i = 0; i < subspaceTags.length; i++) { final tag = subspaceTags[i]; final changedTag = updatedTags.firstWhere( @@ -395,10 +397,10 @@ class TagHelper { static List getAllTagValues( List communities, List? spaceModels) { - final allTags = {}; + final Set allTags = {}; if (spaceModels != null) { - for (final model in spaceModels) { + for (var 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 aab51b59..5b85e17e 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 { - final context = NavigationService.navigatorKey.currentContext!; - final spaceBloc = context.read(); - spacesListIds.clear(); - for (final communityId in spaceBloc.state.selectedCommunities) { - final spacesList = + BuildContext context = NavigationService.navigatorKey.currentContext!; + var spaceBloc = context.read(); + spacesListIds.clear(); + for (var communityId in spaceBloc.state.selectedCommunities) { + List spacesList = spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? []; - spacesListIds.addAll(spacesList); + spacesListIds.addAll(spacesList); } hasSelectedSpaces = spaceBloc.state.selectedCommunities.any((communityId) { - final spacesList = + List 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 ec358985..ad18b3c7 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,9 +5,9 @@ abstract class LinkSpaceToModelState { class SpaceModelInitial extends LinkSpaceToModelState {} class SpaceModelLoading extends LinkSpaceToModelState {} - class LinkSpaceModelLoading extends LinkSpaceToModelState {} + class SpaceModelSelectedState extends LinkSpaceToModelState { final int selectedIndex; const SpaceModelSelectedState(this.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 9e50b881..bbd0de36 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({ - super.key, + Key? key, this.onSave, this.initialSelectedIndex, required this.spaceModels, - }); + }) : super(key: key); @override Widget build(BuildContext context) { @@ -39,10 +39,9 @@ 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) { - var selectedIndex = -1; + int selectedIndex = -1; if (state is SpaceModelSelectedState) { selectedIndex = state.selectedIndex; } @@ -73,9 +72,7 @@ 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 e386b186..5428c343 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,6 +5,7 @@ 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'; @@ -20,7 +21,7 @@ class CreateSpaceModelBloc try { final projectUuid = await ProjectManager.getProjectUUID() ?? ''; - late final spaceTemplate = event.spaceTemplate; + late SpaceTemplateModel spaceTemplate = event.spaceTemplate; final tagBodyModels = spaceTemplate.tags?.map((tag) => tag.toTagBodyModel()).toList() ?? @@ -54,7 +55,7 @@ class CreateSpaceModelBloc } } } catch (e) { - emit(const CreateSpaceModelError('Error creating space model')); + emit(CreateSpaceModelError('Error creating space model')); } }); @@ -64,14 +65,14 @@ class CreateSpaceModelBloc if (_space != null) { emit(CreateSpaceModelLoaded(_space!)); } else { - emit(const CreateSpaceModelError('No space template found')); + emit(CreateSpaceModelError("No space template found")); } }); }); on((event, emit) { _space = event.spaceTemplate; - final errorMessage = _checkDuplicateModelName( + final String? errorMessage = _checkDuplicateModelName( event.allModels ?? [], event.spaceTemplate.modelName); emit(CreateSpaceModelLoaded(_space!, errorMessage: errorMessage)); }); @@ -93,8 +94,9 @@ class CreateSpaceModelBloc orElse: () => subspace, ); + final updatedTags = [ - ...subspace.tags?.map((tag) { + ...?subspace.tags?.map((tag) { final matchingTag = matchingEventSubspace.tags?.firstWhere( (e) => e.internalId == tag.internalId, @@ -106,7 +108,7 @@ class CreateSpaceModelBloc : tag; }) ?? [], - ...matchingEventSubspace.tags?.where( + ...?matchingEventSubspace.tags?.where( (e) => subspace.tags ?.every((t) => t.internalId != e.internalId) ?? @@ -125,7 +127,9 @@ class CreateSpaceModelBloc event.subspaces .where((e) => updatedSubspaces.every((s) => s.internalId != e.internalId)) - .forEach(updatedSubspaces.add); + .forEach((newSubspace) { + updatedSubspaces.add(newSubspace); + }); final updatedSpace = currentState.space.copyWith(subspaceModels: updatedSubspaces); @@ -133,7 +137,7 @@ class CreateSpaceModelBloc emit(CreateSpaceModelLoaded(updatedSpace, errorMessage: currentState.errorMessage)); } else { - emit(const CreateSpaceModelError('Space template not initialized')); + emit(CreateSpaceModelError("Space template not initialized")); } }); @@ -159,12 +163,14 @@ class CreateSpaceModelBloc event.tags .where( (e) => updatedTags.every((t) => t.internalId != e.internalId)) - .forEach(updatedTags.add); + .forEach((e) { + updatedTags.add(e); + }); emit(CreateSpaceModelLoaded( currentState.space.copyWith(tags: updatedTags))); } else { - emit(const CreateSpaceModelError('Space template not initialized')); + emit(CreateSpaceModelError("Space template not initialized")); } }); @@ -174,12 +180,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 = @@ -188,7 +194,7 @@ class CreateSpaceModelBloc emit(CreateSpaceModelLoaded(updatedSpaceModel)); } } else { - emit(const CreateSpaceModelError('Space template not initialized')); + emit(CreateSpaceModelError("Space template not initialized")); } }); @@ -205,17 +211,19 @@ class CreateSpaceModelBloc if (prevSpaceModel?.modelName != newSpaceModel.modelName) { spaceModelName = newSpaceModel.modelName; } - var tagUpdates = []; - final subspaceUpdates = []; - final prevSubspaces = prevSpaceModel?.subspaceModels; - final newSubspaces = newSpaceModel.subspaceModels; + List tagUpdates = []; + final List subspaceUpdates = []; + final List? prevSubspaces = + prevSpaceModel?.subspaceModels; + final List? newSubspaces = + newSpaceModel.subspaceModels; tagUpdates = processTagUpdates(prevSpaceModel?.tags, newSpaceModel.tags); if (prevSubspaces != null || newSubspaces != null) { if (prevSubspaces != null && newSubspaces != null) { - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { final existsInNew = newSubspaces .any((subspace) => subspace.uuid == prevSubspace.uuid); if (!existsInNew) { @@ -224,20 +232,20 @@ class CreateSpaceModelBloc } } } else if (prevSubspaces != null && newSubspaces == null) { - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { subspaceUpdates.add(UpdateSubspaceTemplateModel( action: Action.delete, uuid: prevSubspace.uuid)); } } if (newSubspaces != null) { - for (final newSubspace in newSubspaces) { + for (var newSubspace in newSubspaces) { // Tag without UUID - if (newSubspace.uuid == null || newSubspace.uuid!.isEmpty) { - final tagUpdates = []; + if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) { + final List tagUpdates = []; if (newSubspace.tags != null) { - for (final tag in newSubspace.tags!) { + for (var tag in newSubspace.tags!) { tagUpdates.add(TagModelUpdate( action: Action.add, newTagUuid: tag.uuid == '' ? null : tag.uuid, @@ -255,14 +263,14 @@ class CreateSpaceModelBloc if (prevSubspaces != null && newSubspaces != null) { final newSubspaceMap = { - for (final subspace in newSubspaces) subspace.uuid: subspace + for (var subspace in newSubspaces) subspace.uuid: subspace }; - for (final prevSubspace in prevSubspaces) { + for (var prevSubspace in prevSubspaces) { final newSubspace = newSubspaceMap[prevSubspace.uuid]; if (newSubspace != null) { - final tagSubspaceUpdates = + final List tagSubspaceUpdates = processTagUpdates(prevSubspace.tags, newSubspace.tags); subspaceUpdates.add(UpdateSubspaceTemplateModel( action: Action.update, @@ -290,7 +298,7 @@ class CreateSpaceModelBloc } } } catch (e) { - emit(const CreateSpaceModelError('Error creating space model')); + emit(CreateSpaceModelError('Error creating space model')); } }); } @@ -299,11 +307,11 @@ class CreateSpaceModelBloc List? prevTags, List? newTags, ) { - final tagUpdates = []; + final List tagUpdates = []; final processedTags = {}; if (prevTags == null && newTags != null) { - for (final newTag in newTags) { + for (var newTag in newTags) { tagUpdates.add(TagModelUpdate( action: Action.add, tag: newTag.tag, @@ -317,7 +325,7 @@ class CreateSpaceModelBloc if (newTags != null || prevTags != null) { // Case 1: Tags deleted if (prevTags != null && newTags != null) { - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { final existsInNew = newTags.any((newTag) => newTag.uuid == prevTag.uuid); if (!existsInNew) { @@ -326,7 +334,7 @@ class CreateSpaceModelBloc } } } else if (prevTags != null && newTags == null) { - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { tagUpdates .add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid)); } @@ -336,7 +344,7 @@ class CreateSpaceModelBloc if (newTags != null) { final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {}; - for (final newTag in newTags) { + for (var newTag in newTags) { // Tag without UUID if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) && !processedTags.contains(newTag.tag)) { @@ -352,9 +360,9 @@ class CreateSpaceModelBloc // Case 3: Tags updated if (prevTags != null && newTags != null) { - final newTagMap = {for (final tag in newTags) tag.uuid: tag}; + final newTagMap = {for (var tag in newTags) tag.uuid: tag}; - for (final prevTag in prevTags) { + for (var prevTag in prevTags) { final newTag = newTagMap[prevTag.uuid]; if (newTag != null) { tagUpdates.add(TagModelUpdate( @@ -373,7 +381,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 897bc59c..0d2a3a4f 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; - const UpdateSpaceTemplateName({required this.name, required this.allModels}); + 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; - const AddSubspacesToSpaceTemplate(this.subspaces); + AddSubspacesToSpaceTemplate(this.subspaces); } class AddTagsToSpaceTemplate extends CreateSpaceModelEvent { final List tags; - const AddTagsToSpaceTemplate(this.tags); + AddTagsToSpaceTemplate(this.tags); } class ValidateSpaceTemplateName extends CreateSpaceModelEvent { final String name; - const ValidateSpaceTemplateName({required this.name}); + ValidateSpaceTemplateName({required this.name}); } class ModifySpaceTemplate extends CreateSpaceModelEvent { @@ -65,7 +65,7 @@ class ModifySpaceTemplate extends CreateSpaceModelEvent { final SpaceTemplateModel updatedSpaceTemplate; final Function(SpaceTemplateModel)? onUpdate; - const ModifySpaceTemplate( + 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 d28913b5..0fc5c48d 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; - const CreateSpaceModelLoaded(this.space, {this.errorMessage}); + 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; - const CreateSpaceModelError(this.message); + 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 0450d4ec..37a8c0a9 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,21 +21,18 @@ 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) { @@ -44,15 +41,13 @@ 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; @@ -66,16 +61,14 @@ 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 1481dec4..f8926051 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,18 +30,19 @@ 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?) - ?.whereType>() - .map(SubspaceTemplateModel.fromJson) + ?.where((e) => e is Map) + .map((e) => + SubspaceTemplateModel.fromJson(e as Map)) .toList() ?? [], tags: (json['tags'] as List?) - ?.whereType>() // Validate type - .map(Tag.fromJson) + ?.where((item) => item is Map) // Validate type + .map((item) => Tag.fromJson(item as Map)) .toList() ?? [], ); @@ -108,7 +109,7 @@ class UpdateSubspaceTemplateModel { extension SpaceTemplateExtensions on SpaceTemplateModel { List listAllTagValues() { - final tagValues = []; + final List 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 69829f4a..eef196be 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,10 +18,8 @@ class SpaceModelPage extends StatelessWidget { final List projectTags; const SpaceModelPage( - {super.key, - this.products, - this.onSpaceModelsUpdated, - required this.projectTags}); + {Key? key, this.products, this.onSpaceModelsUpdated, required this.projectTags}) + : super(key: key); @override Widget build(BuildContext context) { @@ -79,8 +77,7 @@ 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: () { @@ -118,10 +115,8 @@ 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), ), ); } @@ -131,7 +126,7 @@ class SpaceModelPage extends StatelessWidget { } double _calculateChildAspectRatio(BuildContext context) { - final screenWidth = MediaQuery.of(context).size.width; + double screenWidth = MediaQuery.of(context).size.width; if (screenWidth > 1600) { return 1.5; // Decrease to make cards taller } @@ -145,7 +140,7 @@ class SpaceModelPage extends StatelessWidget { } List _getAllTagValues(List spaceModels) { - final allTags = []; + final List allTags = []; for (final spaceModel in spaceModels) { if (spaceModel.tags != null) { allTags.addAll(spaceModel.listAllTagValues()); @@ -155,7 +150,7 @@ class SpaceModelPage extends StatelessWidget { } List _getAllSpaceModelName(List spaceModels) { - final names = []; + final List 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 23377f7d..20876a39 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({super.key}); + const AddSpaceModelWidget({Key? key}) : super(key: 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 303ef187..2cd338e4 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({ - super.key, + Key? 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 8079ad4a..2a39d67b 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 51a555a3..0497b570 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 1a429d4c..70dde231 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,12 +9,13 @@ 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_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/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/widgets/subspace_model_create_widget.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/utils/color_manager.dart'; @@ -28,21 +29,22 @@ class CreateSpaceModelDialog extends StatelessWidget { final List projectTags; const CreateSpaceModelDialog( - {super.key, + {Key? key, this.products, this.allTags, this.spaceModel, this.pageContext, this.otherSpaceModels, this.allSpaceModels, - required this.projectTags}); + required this.projectTags}) + : super(key: key); @override Widget build(BuildContext context) { - final spaceModelApi = SpaceModelManagementApi(); + final SpaceModelManagementApi _spaceModelApi = SpaceModelManagementApi(); final screenWidth = MediaQuery.of(context).size.width; - final spaceNameController = TextEditingController( + final TextEditingController spaceNameController = TextEditingController( text: spaceModel?.modelName ?? '', ); @@ -54,7 +56,7 @@ class CreateSpaceModelDialog extends StatelessWidget { child: BlocProvider( create: (_) { final bloc = CreateSpaceModelBloc( - spaceModelApi, + _spaceModelApi, ); if (spaceModel != null) { bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels)); @@ -69,8 +71,7 @@ class CreateSpaceModelDialog extends StatelessWidget { spaceNameController.addListener(() { bloc.add(UpdateSpaceTemplateName( - name: spaceNameController.text, - allModels: otherSpaceModels ?? [])); + name: spaceNameController.text, allModels: otherSpaceModels ?? [])); }); return bloc; @@ -88,9 +89,7 @@ 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 @@ -102,10 +101,8 @@ 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 @@ -179,84 +176,55 @@ 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(CreateSpaceModel( - newSpaceModel: - newModel)); - pageContext! - .read< - SpaceManagementBloc>() - .add( - UpdateSpaceModelCache( - newModel)); + .read() + .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 currentSpaceModel = - spaceModels - .cast() - .firstWhere( - (sm) => - sm?.uuid == - updatedSpaceModel - .uuid, + final SpaceTemplateModel? 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< - SpaceModelBloc>() - .add(UpdateSpaceModel( + if (pageContext != null) { + pageContext!.read().add( + UpdateSpaceModel( spaceModelUuid: - newModel.uuid ?? - '')); + newModel.uuid ?? '')); pageContext! - .read< - SpaceManagementBloc>() - .add(UpdateSpaceModelCache( - newModel)); + .read() + .add(UpdateSpaceModelCache(newModel)); } - Navigator.of(context) - .pop(); + Navigator.of(context).pop(); })); } } @@ -265,11 +233,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 8313360c..e0260887 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,10 +1,9 @@ import 'dart:math'; - import 'package:flutter/material.dart'; +import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/linking_successful.dart'; + class CustomLoadingIndicator extends StatefulWidget { - const CustomLoadingIndicator({super.key}); - @override _CustomLoadingIndicatorState createState() => _CustomLoadingIndicatorState(); } @@ -51,22 +50,22 @@ class _CustomLoadingIndicatorState extends State class LoadingPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final paint = Paint() + final Paint paint = Paint() ..strokeWidth = 5 ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke; - final radius = size.width / 2; - final center = Offset(size.width / 2, size.height / 2); + final double radius = size.width / 2; + final Offset center = Offset(size.width / 2, size.height / 2); - 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); + 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); - paint.color = Colors.blue.withValues(alpha: i / 12); // Gradient effect + paint.color = Colors.blue.withOpacity(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 c5a11c4a..8349baa4 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,7 +6,8 @@ import 'package:syncrow_web/utils/color_manager.dart'; class DeleteSpaceModelDialog extends StatelessWidget { final VoidCallback onConfirmDelete; - const DeleteSpaceModelDialog({super.key, required this.onConfirmDelete}); + const DeleteSpaceModelDialog({Key? key, required this.onConfirmDelete}) + : super(key: key); @override Widget build(BuildContext context) { @@ -19,7 +20,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 @@ -33,13 +34,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 @@ -59,7 +60,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 8a4b1a67..4da0c642 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(); - final formattedDate = + String formattedDate = DateFormat('yyyy-MM-dd').format(widget.spaceModel.createdAt!); - final formattedTime = + String 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,21 +81,22 @@ 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: TextStyle(fontWeight: FontWeight.bold), + "Creation date and time:", + style: const TextStyle( + fontWeight: FontWeight.bold), ), ), const SizedBox(width: 8), Expanded( child: Text( - '$formattedDate $formattedTime', + "$formattedDate $formattedTime", style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.black), @@ -106,14 +107,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), @@ -123,7 +124,7 @@ class _LinkSpaceModelSpacesDialogState children: [ Expanded( flex: 7, - child: ColoredBox( + child: Container( color: ColorsManager.whiteColors, child: SpaceTreeView( isSide: true, @@ -169,7 +170,7 @@ class _LinkSpaceModelSpacesDialogState ), ), ), - child: _buildButton('Cancel', Colors.grey, () { + child: _buildButton("Cancel", Colors.grey, () { Navigator.of(context).pop(); }), ), @@ -190,14 +191,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 d16f2c7e..15d92029 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 ca8f3aeb..9f57a4b1 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 475b24ed..4f42e3bf 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({ - super.key, + Key? key, required this.productTagCount, required this.maxWidth, required this.maxHeight, - }); + }) : super(key: key); @override Widget build(BuildContext context) { - const itemSpacing = 8.0; - const lineSpacing = 8.0; - const textPadding = 16.0; - const itemHeight = 40.0; + const double itemSpacing = 8.0; + const double lineSpacing = 8.0; + const double textPadding = 16.0; + const double itemHeight = 40.0; - final productWidgets = []; - var currentLineWidth = 0.0; - var currentHeight = itemHeight; + List productWidgets = []; + double currentLineWidth = 0.0; + double currentHeight = itemHeight; for (final product in productTagCount.entries) { - final prodType = product.key; - final count = product.value; + final String prodType = product.key; + final int count = product.value; - final textPainter = TextPainter( + final TextPainter textPainter = TextPainter( text: TextSpan( text: 'x$count', style: Theme.of(context) @@ -42,7 +42,7 @@ class DynamicProductWidget extends StatelessWidget { textDirection: TextDirection.ltr, )..layout(); - final itemWidth = textPainter.width + textPadding + 20; + final double 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 d9610ff9..f3da4122 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,37 +8,38 @@ class DynamicRoomWidget extends StatelessWidget { final double maxHeight; const DynamicRoomWidget({ - super.key, + Key? key, required this.subspaceModels, required this.maxWidth, required this.maxHeight, - }); + }) : super(key: key); @override Widget build(BuildContext context) { - const itemSpacing = 8.0; - const lineSpacing = 8.0; - const textPadding = 16.0; - const itemHeight = 30.0; + const double itemSpacing = 8.0; + const double lineSpacing = 8.0; + const double textPadding = 16.0; + const double itemHeight = 30.0; - final roomWidgets = []; - var currentLineWidth = 0.0; - var currentHeight = itemHeight; + List roomWidgets = []; + double currentLineWidth = 0.0; + double currentHeight = itemHeight; for (final subspace in subspaceModels!) { - final textPainter = TextPainter( + final TextPainter 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 itemWidth = textPainter.width + textPadding; + final double 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 8b3f2965..7ede09a7 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({super.key}); + const EllipsisItemWidget({Key? key}) : super(key: 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 aea3b56a..c28a82b8 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({ - super.key, + Key? 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 7ba1b095..d59f8c1e 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({super.key, required this.name}); + const RoomNameWidget({Key? key, required this.name}) : super(key: key); @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 67a72268..4d72a419 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({ - super.key, + Key? key, required this.model, this.pageContext, this.topActionsDisabled = true, - }); + }) : super(key: key); @override Widget build(BuildContext context) { - final productTagCount = {}; + final Map productTagCount = {}; if (model.tags != null) { - for (final tag in model.tags!) { + for (var tag in model.tags!) { final prodIcon = tag.product?.icon ?? 'Unknown'; productTagCount[prodIcon] = (productTagCount[prodIcon] ?? 0) + 1; } } if (model.subspaceModels != null) { - for (final subspace in model.subspaceModels!) { + for (var subspace in model.subspaceModels!) { if (subspace.tags != null) { - for (final tag in subspace.tags!) { + for (var 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) { - final showOnlyName = constraints.maxWidth < 250; + bool 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.withValues(alpha: 0.5), + color: Colors.grey.withOpacity(0.5), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), @@ -81,12 +81,11 @@ 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, ), @@ -101,15 +100,12 @@ 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, @@ -117,18 +113,14 @@ 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: const Padding( - padding: EdgeInsets.symmetric( - vertical: 30, - horizontal: 50), + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 30, horizontal: 50), child: Column( - mainAxisSize: - MainAxisSize.min, + mainAxisSize: MainAxisSize.min, children: [ CustomLoadingIndicator(), ], @@ -137,19 +129,14 @@ 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(); @@ -157,29 +144,23 @@ 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(); @@ -237,8 +218,7 @@ 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 0d66dbac..70ac6e24 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({ - super.key, + Key? 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 5cb4a9ff..4ebd65df 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({ - super.key, + Key? 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 tagsToAppendToSpace = []; + final List tagsToAppendToSpace = []; - for (final s in deletedSubspaces) { + for (var 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 c27a1436..6a6aec44 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({ - super.key, + Key? 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 2ff1b085..86f99e02 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,8 +50,7 @@ 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 23cfb1d9..1de2ae13 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 d70a0b55..72cdbd1c 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 {} +class CommunitySelectedEvent extends CenterBodyEvent {} \ No newline at end of file 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 6b0ff481..dbc6c7ef 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,13 +2,11 @@ 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( @@ -54,7 +52,7 @@ class CenterBodyWidget extends StatelessWidget { .textTheme .bodyLarge! .color! - .withValues(alpha: 0.5), + .withOpacity(0.5), ), ), ), @@ -75,7 +73,7 @@ class CenterBodyWidget extends StatelessWidget { // .textTheme // .bodyLarge! // .color! - // .withValues(alpha:0.5), + // .withOpacity(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 5ee52b08..27f183a6 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,4 +1,5 @@ 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'; @@ -12,7 +13,7 @@ abstract class AddDeviceTypeModelEvent extends Equatable { class UpdateProductCountEvent extends AddDeviceTypeModelEvent { final SelectedProduct selectedProduct; - const UpdateProductCountEvent({required this.selectedProduct}); + 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 e9823fee..c0226ba8 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/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/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/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,8 +80,7 @@ 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, @@ -153,11 +152,10 @@ 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, @@ -170,15 +168,13 @@ 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 8a64fe41..d1775c66 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,12 +12,13 @@ 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 6bcd8b62..438b1abf 100644 --- a/lib/pages/visitor_password/bloc/visitor_password_bloc.dart +++ b/lib/pages/visitor_password/bloc/visitor_password_bloc.dart @@ -14,10 +14,14 @@ 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); @@ -67,13 +71,13 @@ class VisitorPasswordBloc String startTimeAccess = 'Start Time'; String endTimeAccess = 'End Time'; PasswordStatus? passwordStatus; - void selectAccessType( + selectAccessType( SelectPasswordType event, Emitter emit) { accessTypeSelected = event.type; emit(PasswordTypeSelected(event.type)); } - void selectUsageFrequency( + selectUsageFrequency( SelectUsageFrequency event, Emitter emit) { usageFrequencySelected = event.usageType; emit(UsageFrequencySelected(event.usageType)); @@ -83,7 +87,7 @@ class VisitorPasswordBloc SelectTimeVisitorPassword event, Emitter emit, ) async { - final picked = await showDatePicker( + final DateTime? picked = await showDatePicker( context: event.context, initialDate: DateTime.now(), firstDate: DateTime(2015, 8), @@ -91,7 +95,7 @@ class VisitorPasswordBloc ); if (picked != null) { - final timePicked = await showTimePicker( + final TimeOfDay? timePicked = await showTimePicker( context: event.context, initialTime: TimeOfDay.now(), builder: (context, child) { @@ -160,13 +164,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 = []; @@ -188,12 +192,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())); } } @@ -204,7 +208,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); generate7DigitNumber(); - final res = await AccessMangApi().postOnlineOneTime( + var res = await AccessMangApi().postOnlineOneTime( email: event.email, password: passwordController, devicesUuid: selectedDevices, @@ -218,8 +222,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - final String errorMessage = errorData['message']; - emit(FailedState(errorMessage)); + String errorMessage = errorData['message']; + emit(FailedState(errorMessage.toString())); } } @@ -230,12 +234,13 @@ class VisitorPasswordBloc emit(LoadingInitialState()); await generate7DigitNumber(); - final res = await AccessMangApi().postOnlineMultipleTime( + var res = await AccessMangApi().postOnlineMultipleTime( scheduleList: [ if (repeat) Schedule( effectiveTime: getTimeFromDateTimeString(effectiveTime), - invalidTime: getTimeFromDateTimeString(expirationTime), + invalidTime: + getTimeFromDateTimeString(expirationTime).toString(), workingDay: selectedDays, ), ], @@ -252,8 +257,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - final String errorMessage = errorData['message']; - emit(FailedState(errorMessage)); + String errorMessage = errorData['message']; + emit(FailedState(errorMessage.toString())); } } @@ -263,7 +268,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); await generate7DigitNumber(); - final res = await AccessMangApi().postOffLineOneTime( + var res = await AccessMangApi().postOffLineOneTime( email: event.email, devicesUuid: selectedDevices, passwordName: event.passwordName); @@ -274,8 +279,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - final String errorMessage = errorData['message']; - emit(FailedState(errorMessage)); + String errorMessage = errorData['message']; + emit(FailedState(errorMessage.toString())); } } @@ -285,7 +290,7 @@ class VisitorPasswordBloc try { emit(LoadingInitialState()); await generate7DigitNumber(); - final res = await AccessMangApi().postOffLineMultipleTime( + var res = await AccessMangApi().postOffLineMultipleTime( email: event.email, devicesUuid: selectedDevices, passwordName: event.passwordName, @@ -299,8 +304,8 @@ class VisitorPasswordBloc emit(TableLoaded(data)); } on DioException catch (e) { final errorData = e.response!.data; - final String errorMessage = errorData['message']; - emit(FailedState(errorMessage)); + String errorMessage = errorData['message']; + emit(FailedState(errorMessage.toString())); } } @@ -322,9 +327,9 @@ class VisitorPasswordBloc Future generate7DigitNumber() async { passwordController = ''; - final random = Random(); - const min = 1000000; - const max = 9999999; + Random random = Random(); + int min = 1000000; + int max = 9999999; passwordController = (min + random.nextInt(max - min + 1)).toString(); return passwordController; } @@ -360,7 +365,7 @@ class VisitorPasswordBloc emit(TableLoaded(event.filteredData)); } - void addDeviceToList(context) { + addDeviceToList(context) { selectedDevices = selectedDeviceIds; Navigator.of(context).pop(selectedDevices); } @@ -368,14 +373,14 @@ class VisitorPasswordBloc Future selectTimeOfLinePassword( SelectTimeEvent event, Emitter emit) async { emit(ChangeTimeState()); - final picked = await showDatePicker( + final DateTime? picked = await showDatePicker( context: event.context, initialDate: DateTime.now(), firstDate: DateTime.now(), lastDate: DateTime.now().add(const Duration(days: 2095)), ); if (picked != null) { - final timePicked = await showHourPicker( + final TimeOfDay? timePicked = await showHourPicker( context: event.context, initialTime: TimeOfDay.now(), ); @@ -400,7 +405,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; @@ -422,7 +427,7 @@ class VisitorPasswordBloc } } - void changeTime(ChangeTimeEvent event, Emitter emit) { + changeTime(ChangeTimeEvent event, Emitter emit) { if (event.isStartEndTime == true) { startTime = event.val; } else { @@ -432,8 +437,8 @@ class VisitorPasswordBloc DateTime? convertStringToDateTime(String dateTimeString) { try { - final inputFormat = DateFormat('yyyy-MM-dd HH:mm:ss'); - final dateTime = inputFormat.parse(dateTimeString); + final DateFormat inputFormat = DateFormat('yyyy-MM-dd HH:mm:ss'); + DateTime dateTime = inputFormat.parse(dateTimeString); return dateTime; } catch (e) { return null; @@ -441,7 +446,7 @@ class VisitorPasswordBloc } String getTimeFromDateTimeString(String dateTimeString) { - final dateTime = convertStringToDateTime(dateTimeString); + DateTime? 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 6e7b056b..6ecae200 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; - const UpdateFilteredDevicesEvent(this.filteredData); + 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 dc6c4858..f9711eed 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) { - var tempIcon = ''; - final type = devicesTypesMap[json['productType']] ?? DeviceType.Other; + String tempIcon = ''; + DeviceType 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 02bd6802..223f9ac5 100644 --- a/lib/pages/visitor_password/model/failed_operation.dart +++ b/lib/pages/visitor_password/model/failed_operation.dart @@ -26,6 +26,8 @@ class FailedOperation { } } + + class SuccessOperation { final bool success; // final Result result; @@ -90,6 +92,8 @@ class SuccessOperation { // } // } + + class PasswordStatus { final List successOperations; final List failedOperations; @@ -117,3 +121,4 @@ 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 68f970b3..d69aa21d 100644 --- a/lib/pages/visitor_password/view/add_device_dialog.dart +++ b/lib/pages/visitor_password/view/add_device_dialog.dart @@ -2,14 +2,15 @@ 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/buttons/default_button.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/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/app_enum.dart'; import 'package:syncrow_web/utils/constants/assets.dart'; +import 'package:syncrow_web/utils/constants/app_enum.dart'; import 'package:syncrow_web/utils/style.dart'; class AddDeviceDialog extends StatelessWidget { @@ -17,14 +18,15 @@ class AddDeviceDialog extends StatelessWidget { const AddDeviceDialog({super.key, this.selectedDeviceIds}); @override Widget build(BuildContext context) { - final size = MediaQuery.of(context).size; + Size 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 (final device in selectedDeviceIds!) { + for (var device in selectedDeviceIds!) { if (selectedDeviceIds!.contains(device)) { visitorBloc.add(SelectDeviceEvent(device)); } @@ -52,7 +54,7 @@ class AddDeviceDialog extends StatelessWidget { padding: const EdgeInsets.all(15), decoration: containerDecoration.copyWith( color: ColorsManager.worningColor, - border: Border.all(color: const Color(0xffFFD22F)), + border: Border.all(color: Color(0xffFFD22F)), boxShadow: []), child: Row( children: [ @@ -126,7 +128,9 @@ 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'), ), @@ -137,7 +141,7 @@ class AddDeviceDialog extends StatelessWidget { const SizedBox(width: 10), Expanded( flex: 2, - child: SizedBox( + child: Container( width: size.width * 0.06, child: DefaultButton( backgroundColor: ColorsManager.whiteColors, @@ -173,7 +177,7 @@ class AddDeviceDialog extends StatelessWidget { isEmpty: visitorBloc.data.isEmpty, selectAll: (p0) { visitorBloc.selectedDeviceIds.clear(); - for (final item in state.data) { + for (var item in state.data) { visitorBloc .add(SelectDeviceEvent(item.uuid)); } @@ -197,7 +201,7 @@ class AddDeviceDialog extends StatelessWidget { item.uuid.toString(), item.productType.toString(), item.spaceName.toString(), - item.online.value, + item.online.value.toString(), ]; }).toList(), ) @@ -219,7 +223,7 @@ class AddDeviceDialog extends StatelessWidget { backgroundColor: Colors.white, child: Text( 'Cancel', - style: Theme.of(context).textTheme.bodyMedium, + style: Theme.of(context).textTheme.bodyMedium!, ), ), ), @@ -231,7 +235,7 @@ class AddDeviceDialog extends StatelessWidget { visitorBloc.addDeviceToList(context); }, borderRadius: 8, - child: const Text('Ok'), + child: Text('Ok'), ), ), ], diff --git a/lib/pages/visitor_password/view/repeat_widget.dart b/lib/pages/visitor_password/view/repeat_widget.dart index 621dbbba..8b40b580 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) { - final size = MediaQuery.of(context).size; + Size 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: const EdgeInsets.all(5), + margin: 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 1849ccf2..1e43af46 100644 --- a/lib/pages/visitor_password/view/visitor_password_dialog.dart +++ b/lib/pages/visitor_password/view/visitor_password_dialog.dart @@ -2,6 +2,7 @@ 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'; @@ -19,11 +20,8 @@ class VisitorPasswordDialog extends StatelessWidget { @override Widget build(BuildContext context) { - final size = MediaQuery.of(context).size; - final text = Theme.of(context) - .textTheme - .bodySmall! - .copyWith(color: Colors.black, fontSize: 13); + Size size = MediaQuery.of(context).size; + var text = Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.black, fontSize: 13); return BlocProvider( create: (context) => VisitorPasswordBloc(), child: BlocListener( @@ -37,8 +35,7 @@ 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'), @@ -48,26 +45,22 @@ 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: const EdgeInsets.all(5), + margin: 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'), @@ -77,18 +70,15 @@ 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: const EdgeInsets.all(5), + margin: EdgeInsets.all(5), decoration: containerDecoration, height: 45, child: Center( - child: Text(visitorBloc - .passwordStatus! - .successOperations[index] - .deviceUuid)), + child: Text(visitorBloc.passwordStatus! + .successOperations[index].deviceUuid)), ); }, ), @@ -99,6 +89,7 @@ class VisitorPasswordDialog extends StatelessWidget { )) .then((v) { Navigator.of(context).pop(true); + }); } else if (state is FailedState) { visitorBloc.stateDialog( @@ -111,16 +102,15 @@ class VisitorPasswordDialog extends StatelessWidget { child: BlocBuilder( builder: (BuildContext context, VisitorPasswordState state) { final visitorBloc = BlocProvider.of(context); - final isRepeat = - state is IsRepeatState ? state.repeat : visitorBloc.repeat; + bool 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()) @@ -138,8 +128,7 @@ class VisitorPasswordDialog extends StatelessWidget { flex: 2, child: CustomWebTextField( validator: visitorBloc.validate, - controller: - visitorBloc.userNameController, + controller: visitorBloc.userNameController, isRequired: true, textFieldName: 'Name', description: '', @@ -188,26 +177,20 @@ 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< - VisitorPasswordBloc>() - .add( - SelectPasswordType( - value)); + .read() + .add(SelectPasswordType(value)); } }, ), @@ -215,25 +198,17 @@ 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< - VisitorPasswordBloc>() - .add( - SelectPasswordType( - value)); + .read() + .add(SelectPasswordType(value)); } }, ), @@ -267,29 +242,21 @@ 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( @@ -304,206 +271,143 @@ class VisitorPasswordDialog extends StatelessWidget { ) ], ), - if (visitorBloc.accessTypeSelected == - 'Dynamic Password') - const SizedBox() - else - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( + visitorBloc.accessTypeSelected == 'Dynamic Password' + ? const SizedBox() + : Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - '* ', - style: Theme.of(context) - .textTheme - .bodyMedium! - .copyWith(color: Colors.red), - ), - Text( - 'Usage Frequency', - style: text, - ), - ], - ), - Row( - children: [ - SizedBox( - width: size.width * 0.12, - child: RadioListTile( - contentPadding: EdgeInsets.zero, - title: Text( - 'One-Time', + Row( + children: [ + Text( + '* ', + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(color: Colors.red), + ), + Text( + 'Usage Frequency', 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)); - } - }, - ), + 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), + ), ], ), - - //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)); - } else { + if (visitorBloc.usageFrequencySelected == 'Periodic' && + visitorBloc.accessTypeSelected == 'Offline Password') { visitorBloc.add( - SelectTimeVisitorPassword( - context: context, - isStart: true, - isRepeat: false)); + SelectTimeEvent(context: context, isEffective: true)); + } else { + 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, - secondString: (visitorBloc - .usageFrequencySelected == - 'Periodic' && - visitorBloc.accessTypeSelected == - 'Offline Password') + : visitorBloc.startTimeAccess.toString(), + secondString: (visitorBloc.usageFrequencySelected == + 'Periodic' && visitorBloc.accessTypeSelected == 'Offline Password') ? visitorBloc.expirationTime - : visitorBloc.endTimeAccess, + : visitorBloc.endTimeAccess.toString(), 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, ), @@ -527,21 +431,16 @@ 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( @@ -552,8 +451,7 @@ class VisitorPasswordDialog extends StatelessWidget { child: CupertinoSwitch( value: visitorBloc.repeat, onChanged: (value) { - visitorBloc - .add(ToggleRepeatEvent()); + visitorBloc.add(ToggleRepeatEvent()); }, applyTheme: true, ), @@ -561,13 +459,9 @@ 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, @@ -578,28 +472,22 @@ 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), ), ), ), @@ -637,35 +525,30 @@ 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 != 'End Time' && - visitorBloc.startTimeAccess != 'Start Time') { + } else if( + visitorBloc.endTimeAccess.toString()!='End Time' + &&visitorBloc.startTimeAccess.toString()!='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, @@ -679,16 +562,14 @@ 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( @@ -733,9 +614,8 @@ class VisitorPasswordDialog extends StatelessWidget { alignment: Alignment.center, content: SizedBox( height: size.height * 0.25, - child: const Center( - child: - CircularProgressIndicator(), // Display a loading spinner + child: Center( + child: CircularProgressIndicator(), // Display a loading spinner ), ), ); @@ -759,10 +639,7 @@ 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, @@ -812,45 +689,37 @@ 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 a10292c5..a780a12b 100644 --- a/lib/services/access_mang_api.dart +++ b/lib/services/access_mang_api.dart @@ -12,8 +12,7 @@ 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."); } } @@ -23,8 +22,8 @@ class AccessMangApi { path: ApiEndpoints.visitorPassword, showServerMessage: true, expectedResponseModel: (json) { - final List jsonData = json['data'] ?? []; - final passwordList = jsonData.map((jsonItem) { + List jsonData = json['data'] ?? []; + List passwordList = jsonData.map((jsonItem) { return PasswordModel.fromJson(jsonItem); }).toList(); return passwordList; @@ -47,8 +46,8 @@ class AccessMangApi { }, showServerMessage: true, expectedResponseModel: (json) { - final List jsonData = json['data'] ?? []; - final deviceList = jsonData.map((jsonItem) { + List jsonData = json['data'] ?? []; + List deviceList = jsonData.map((jsonItem) { return DeviceModel.fromJson(jsonItem); }).toList(); return deviceList; @@ -70,13 +69,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) { @@ -94,18 +93,17 @@ class AccessMangApi { String? passwordName, List? scheduleList, List? devicesUuid}) async { - final body = { - 'email': email, - 'devicesUuid': devicesUuid, - 'passwordName': passwordName, - 'password': password, - 'effectiveTime': effectiveTime, - 'invalidTime': invalidTime, - 'operationType': 'ONLINE_MULTIPLE_TIME', + Map 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, @@ -125,10 +123,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) { @@ -147,12 +145,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 f6762daf..bef8d804 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,8 +18,7 @@ class HTTPInterceptor extends InterceptorsWrapper { ]; @override - Future onResponse( - Response response, ResponseInterceptorHandler handler) async { + void onResponse(Response response, ResponseInterceptorHandler handler) async { if (await validateResponse(response)) { super.onResponse(response, handler); } else { @@ -29,27 +28,26 @@ class HTTPInterceptor extends InterceptorsWrapper { } @override - Future onRequest( + void onRequest( RequestOptions options, RequestInterceptorHandler handler) async { - const storage = FlutterSecureStorage(); - final token = await storage.read(key: Token.loginAccessTokenKey); + var storage = const FlutterSecureStorage(); + var 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 - Future onError( - DioException err, ErrorInterceptorHandler handler) async { - final failure = ServerFailure.fromDioError(err); + void onError(DioException err, ErrorInterceptorHandler handler) async { + ServerFailure failure = ServerFailure.fromDioError(err); if (failure.toString().isNotEmpty) { CustomSnackBar.displaySnackBar(failure.toString()); } - const storage = FlutterSecureStorage(); - final token = await storage.read(key: Token.loginAccessTokenKey); + var storage = const FlutterSecureStorage(); + var token = await storage.read(key: Token.loginAccessTokenKey); if (err.response?.statusCode == 401 && token != null) { // await AuthCubit.get(NavigationService.navigatorKey.currentContext!).logout(); } @@ -74,10 +72,10 @@ class HTTPInterceptor extends InterceptorsWrapper { } } - bool checkHeaderExclusionListOfAddedParameters(String path) { - var shouldAddHeader = true; + checkHeaderExclusionListOfAddedParameters(String path) { + bool shouldAddHeader = true; - for (final urlConstant in headerExclusionListOfAddedParameters) { + for (var 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 8e0d0616..c76291bf 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() { - final client = Dio( + Dio 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 9ebc8486..d85ef27c 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: - final errors = []; + List errors = []; if (responseMessage is List) { - for (final error in responseMessage) { + for (var 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 ad4fec5f..18d951c1 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 16542c8c..f78cdef4 100644 --- a/lib/services/batch_control_devices_service.dart +++ b/lib/services/batch_control_devices_service.dart @@ -11,8 +11,7 @@ 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 06fe635c..6f60e34f 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) { - final List jsonData = json['data']; - final devicesList = jsonData.map((jsonItem) { + List jsonData = json['data']; + List 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) { - final devices = []; + List devices = []; if (json == null || json.isEmpty || json == []) { return devices; } - for (final device in json['data']['devices']) { + for (var device in json['data']['devices']) { devices.add(DeviceModel.fromJson(device)); } return devices; @@ -203,7 +203,7 @@ class DevicesManagementApi { } } - Future getPowerStatus(List uuids) async { + getPowerStatus(List uuids) async { try { final queryParameters = { 'devicesUuid': uuids.join(','), @@ -254,8 +254,8 @@ class DevicesManagementApi { .replaceAll('{category}', category), showServerMessage: true, expectedResponseModel: (json) { - final schedules = []; - for (final schedule in json) { + List schedules = []; + for (var 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 27f78ab9..055deb05 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 -void initialSetup() { +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 90dab310..02c9f143 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) { - final List jsonData = json['data']; + List jsonData = json['data']; - final productList = jsonData.map((jsonItem) { + List 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 f0d0b52a..bdc46ac1 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) { - final String errorMessage = + 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) { - final String errorMessage = + 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) { - final iconsList = []; + List iconsList = []; json.forEach((element) { iconsList.add(IconModel.fromJson(element)); }); @@ -89,8 +89,8 @@ class SceneApi { expectedResponseModel: (json) { final scenesJson = json['data'] as List; - final scenes = []; - for (final scene in scenesJson) { + List scenes = []; + for (var 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) { - final scenes = []; - for (final scene in json) { + List scenes = []; + for (var scene in json) { scenes.add(ScenesModel.fromJson(scene, isAutomation: true)); } return scenes; @@ -158,8 +158,7 @@ class SceneApi { } //update Scene - static Future updateScene( - CreateSceneModel createSceneModel, String sceneId) async { + static updateScene(CreateSceneModel createSceneModel, String sceneId) async { try { final response = await _httpService.put( path: ApiEndpoints.updateScene.replaceAll('{sceneId}', sceneId), @@ -171,14 +170,14 @@ class SceneApi { ); return response; } on DioException catch (e) { - final String errorMessage = + String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } } //update automation - static Future updateAutomation(CreateAutomationModel createAutomationModel, + static updateAutomation(CreateAutomationModel createAutomationModel, String automationId, String projectId) async { try { final response = await _httpService.put( @@ -193,7 +192,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - final String errorMessage = + String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -227,7 +226,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - final String errorMessage = + String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -248,7 +247,7 @@ class SceneApi { ); return response; } on DioException catch (e) { - final String errorMessage = + String errorMessage = e.response?.data['error']['message'][0] ?? 'something went wrong'; throw APIException(errorMessage); } @@ -296,8 +295,8 @@ class SceneApi { .replaceAll('{projectId}', projectId), showServerMessage: false, expectedResponseModel: (json) { - final scenes = []; - for (final scene in json) { + List scenes = []; + for (var 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 901d623f..14902bca 100644 --- a/lib/services/space_mana_api.dart +++ b/lib/services/space_mana_api.dart @@ -5,19 +5,22 @@ 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 { - final allCommunities = []; - var hasNext = true; + List allCommunities = []; + bool hasNext = true; while (hasNext) { await HTTPService().get( @@ -28,10 +31,10 @@ class CommunitySpaceManagementApi { }, expectedResponseModel: (json) { try { - final List jsonData = json['data'] ?? []; + List jsonData = json['data'] ?? []; hasNext = json['hasNext'] ?? false; - final int currentPage = json['page'] ?? 1; - final communityList = jsonData.map((jsonItem) { + int currentPage = json['page'] ?? 1; + List communityList = jsonData.map((jsonItem) { return CommunityModel.fromJson(jsonItem); }).toList(); allCommunities.addAll(communityList); @@ -53,10 +56,10 @@ class CommunitySpaceManagementApi { Future fetchCommunitiesAndSpaces( {required String projectId, int page = 1, String search = ''}) async { - var paginationModel = const PaginationModel.emptyConstructor(); + PaginationModel paginationModel = const PaginationModel.emptyConstructor(); try { - var hasNext = false; + bool hasNext = false; await HTTPService().get( path: ApiEndpoints.getCommunityList.replaceAll('{projectId}', projectId), @@ -68,10 +71,10 @@ class CommunitySpaceManagementApi { }, expectedResponseModel: (json) { try { - final List jsonData = json['data'] ?? []; + List jsonData = json['data'] ?? []; hasNext = json['hasNext'] ?? false; - final int currentPage = json['page'] ?? 1; - final communityList = jsonData.map((jsonItem) { + int currentPage = json['page'] ?? 1; + List communityList = jsonData.map((jsonItem) { return CommunityModel.fromJson(jsonItem); }).toList(); @@ -376,12 +379,12 @@ class CommunitySpaceManagementApi { final response = await HTTPService().get( path: path, - queryParameters: {'page': 1, 'pageSize': 10}, + queryParameters: {"page": 1, "pageSize": 10}, showServerMessage: false, expectedResponseModel: (json) { - final rooms = []; + List rooms = []; if (json['data'] != null) { - for (final subspace in json['data']) { + for (var subspace in json['data']) { rooms.add(SubSpaceModel.fromJson(subspace)); } } @@ -390,7 +393,7 @@ class CommunitySpaceManagementApi { ); return response; - } catch (error) { + } catch (error, stackTrace) { return []; } } diff --git a/lib/services/space_model_mang_api.dart b/lib/services/space_model_mang_api.dart index c6fff07d..cbb9cfeb 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) { - final List jsonData = json['data']; + 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 881f92df..3f02663d 100644 --- a/lib/services/user_permission.dart +++ b/lib/services/user_permission.dart @@ -23,18 +23,18 @@ class UserPermissionApi { }, ); return response; - } catch (e) { + } catch (e, stackTrace) { debugPrint('Error in fetchUsers: $e'); rethrow; } } - Future> fetchRoles() async { + fetchRoles() async { final response = await _httpService.get( path: ApiEndpoints.roleTypes, showServerMessage: true, expectedResponseModel: (json) { - final fetchedRoles = (json['data'] as List) + final List 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 { + } on DioException catch (e) { 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) { - final message = json['message']; + var 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) { - final res = EditUserModel.fromJson(json['data']); + EditUserModel 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 { + } on DioException catch (e) { 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,17 +193,16 @@ class UserPermissionApi { } } - Future changeUserStatusById( - userUuid, status, String projectUuid) async { + Future changeUserStatusById(userUuid, status, String projectUuid) async { try { - final bodya = { - 'disable': status, - 'projectUuid': projectUuid + Map 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 2b164590..50170ed9 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).withValues(alpha: 0.6); + const Color(0xFF023DFE).withOpacity(0.6); static const Color whiteColors = Colors.white; - static Color whiteColorsWithOpacity = Colors.white.withValues(alpha: 0.6); + static Color whiteColorsWithOpacity = Colors.white.withOpacity(0.6); static const Color secondaryColor = Color(0xFF023DFE); static const Color onSecondaryColor = Color(0xFF023DFE); - static Color shadowBlackColor = Colors.black.withValues(alpha: 0.2); + static Color shadowBlackColor = Colors.black.withOpacity(0.2); - static Color dialogBlueTitle = const Color(0xFF023DFE).withValues(alpha: 0.6); + static Color dialogBlueTitle = const Color(0xFF023DFE).withOpacity(0.6); static const Color primaryTextColor = Colors.black; @@ -83,5 +83,7 @@ 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 bfdb729d..411e72a5 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 ec5aeb2d..d603c3ea 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 5f030841..dfc0b394 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 3f70b347..2ea63fe4 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 0af5510b..9bfd322f 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 1c3a5dbc..0abd16a1 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, - double? dialogWidth, + final double? dialogWidth, TextStyle? titleStyle, String? onDismissText, String? onConfirmText, Color? onDismissColor, Color? onConfirmColor, }) { - showDialog( + showDialog( context: this, builder: (BuildContext context) { return AlertDialog( @@ -74,59 +74,58 @@ extension BuildContextExt on BuildContext { width: double.infinity, 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), + 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), + ), ), ), ), - 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 2b63b1d4..98d0eb5e 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 dateFormatter = DateFormat('dd/MM/yyyy'); - final timeFormatter = DateFormat('HH:mm'); + final DateFormat dateFormatter = DateFormat('dd/MM/yyyy'); + final DateFormat 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 d94bd090..e0473992 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 - var output = str.replaceAll('-', '+').replaceAll('_', '/'); + String 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 97a504e0..b9c7e0f4 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 Future saveStringToSP(String key, String value) async { + static saveStringToSP(String key, String value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(key, value); } - static Future saveBoolToSP(String key, bool value) async { + static saveBoolToSP(String key, bool value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(key, value); } - static Future saveIntToSP(String key, int value) async { + static saveIntToSP(String key, int value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt(key, value); } - static Future saveDoubleToSP(String key, double value) async { + static saveDoubleToSP(String key, double value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(key, value); } - static Future saveStringListToSP(String key, List value) async { + static 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(); - final value = prefs.getString(key) ?? ''; + String value = prefs.getString(key) ?? ''; return value; } static Future readBoolFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - final value = prefs.getBool(key); + bool? value = prefs.getBool(key); return value; } static Future readIntFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - final value = prefs.getInt(key) ?? 0; + int value = prefs.getInt(key) ?? 0; return value; } static Future> readStringListFromSP(String key) async { final prefs = await SharedPreferences.getInstance(); - final value = prefs.getStringList(key) ?? []; + List? value = prefs.getStringList(key) ?? []; return value; } diff --git a/lib/utils/navigation_service.dart b/lib/utils/navigation_service.dart index c0b12167..c9d654e6 100644 --- a/lib/utils/navigation_service.dart +++ b/lib/utils/navigation_service.dart @@ -5,3 +5,6 @@ class NavigationService { static GlobalKey? snackbarKey = GlobalKey(); } + + + diff --git a/lib/utils/snack_bar.dart b/lib/utils/snack_bar.dart index ae65541d..0a312e5a 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 void displaySnackBar(String message) { + static displaySnackBar(String message) { final key = NavigationService.snackbarKey; if (key != null) { final snackBar = SnackBar(content: Text(message)); @@ -12,9 +12,9 @@ class CustomSnackBar { } } - static void redSnackBar(String message) { + static redSnackBar(String message) { final key = NavigationService.snackbarKey; - final currentContext = key?.currentContext; + BuildContext? currentContext = key?.currentContext; if (key != null && currentContext != null) { final snackBar = SnackBar( padding: const EdgeInsets.all(16), @@ -30,8 +30,10 @@ 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), ) ]), ); @@ -39,9 +41,9 @@ class CustomSnackBar { } } - static void greenSnackBar(String message) { + static greenSnackBar(String message) { final key = NavigationService.snackbarKey; - final currentContext = key?.currentContext; + BuildContext? currentContext = key?.currentContext; if (key != null && currentContext != null) { final snackBar = SnackBar( padding: const EdgeInsets.all(16), @@ -57,8 +59,10 @@ 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 9964cf41..905bb7a8 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'; -InputDecoration? textBoxDecoration( - {bool suffixIcon = false, double radios = 8}) => +import 'color_manager.dart'; + +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( BoxDecoration containerDecoration = BoxDecoration( boxShadow: [ BoxShadow( - color: Colors.grey.withValues(alpha: 0.3), + color: Colors.grey.withOpacity(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.withValues(alpha: 0.3), + color: Colors.grey.withOpacity(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.withValues(alpha: 0.1), + color: Colors.black.withOpacity(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.withValues(alpha: 0.1), + color: Colors.black.withOpacity(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 27ddd487..5ac61afa 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.withValues(alpha: 0.5); + return ColorsManager.blueColor.withOpacity(0.5); } return ColorsManager.whiteColors; }), diff --git a/lib/utils/user_drop_down_menu.dart b/lib/utils/user_drop_down_menu.dart index f70b90c1..15da1f3a 100644 --- a/lib/utils/user_drop_down_menu.dart +++ b/lib/utils/user_drop_down_menu.dart @@ -1,8 +1,10 @@ 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'; @@ -64,9 +66,9 @@ class _UserDropdownMenuState extends State { } Future _showPopupMenu(BuildContext context) async { - final overlay = - Overlay.of(context).context.findRenderObject()! as RenderBox; - final position = RelativeRect.fromRect( + final RenderBox overlay = + Overlay.of(context).context.findRenderObject() as RenderBox; + final RelativeRect position = RelativeRect.fromRect( Rect.fromLTRB( overlay.size.width, 75, @@ -104,7 +106,7 @@ class _UserDropdownMenuState extends State { child: ListTile( leading: SvgPicture.asset(Assets.userManagement), title: Text( - 'User Management', + "User Management", style: context.textTheme.bodyMedium, ), ), @@ -253,7 +255,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 c156ecd5..e0a71b04 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 void Function()? onTap; + final 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 03e2e8a8..3cfe171e 100644 --- a/lib/web_layout/web_app_bar.dart +++ b/lib/web_layout/web_app_bar.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/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'; @@ -50,7 +49,7 @@ class DesktopAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final UserModel? user; + final dynamic user; const DesktopAppBar({ super.key, @@ -76,7 +75,7 @@ class DesktopAppBar extends StatelessWidget { if (centerBody != null) Padding( padding: const EdgeInsets.only(left: 80), - child: centerBody, + child: centerBody!, ), ], ), @@ -103,7 +102,7 @@ class TabletAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final UserModel? user; + final dynamic user; const TabletAppBar({ super.key, @@ -150,7 +149,7 @@ class MobileAppBar extends StatelessWidget { final Widget? title; final Widget? centerBody; final Widget? rightBody; - final UserModel? user; + final dynamic user; const MobileAppBar({ super.key, @@ -183,12 +182,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 812ea49e..a37727db 100644 --- a/lib/web_layout/web_scaffold.dart +++ b/lib/web_layout/web_scaffold.dart @@ -1,9 +1,10 @@ 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 8b137891..e69de29b 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1 +0,0 @@ -