diff --git a/android/build.gradle b/android/build.gradle index 419b3fd3..cf27c349 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -27,6 +27,6 @@ subprojects { project.evaluationDependsOn(':app') } -task clean(type: Delete) { +tasks.register("clean", Delete) { delete rootProject.buildDir } diff --git a/lib/controllers/api_routes/http_status_manger.dart b/lib/controllers/api_routes/http_status_manger.dart index 4aa0991e..efa234d7 100644 --- a/lib/controllers/api_routes/http_status_manger.dart +++ b/lib/controllers/api_routes/http_status_manger.dart @@ -3,10 +3,10 @@ import 'package:meta/meta.dart'; class HttpStatusManger { static String getStatusMessage({ - @required int status, - @required AppLocalizations subtitle, - String messageFor400, - String messageFor200, + required int? status, + required AppLocalizations subtitle, + String? messageFor400, + String? messageFor200, }) { if (status == null) // no status code - code error no need for subtitle diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 11e73fde..b865b455 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -11,7 +11,7 @@ class URLs { set host(String value) => _host = value; - static String getFileUrl(String file) => (file == null || file.isEmpty) ? null : (file.contains("/") ? file : "$_baseUrl/Files/DownloadFile?fileName=$file"); + static String? getFileUrl(String? file) => (file == null || file.isEmpty) ? null : (file.contains("/") ? file : "$_baseUrl/Files/DownloadFile?fileName=$file"); // static String getFileUrl(String file) => (file == null || file.isEmpty) ? null :1 (file.contains("/") ? file : "$_host/attachment/$file"); @@ -59,6 +59,7 @@ class URLs { static get getSingleServiceRequest => "$_baseUrl/return/call/information"; // get static get getSuppliersAutoComplete => "$_baseUrl/Supplier/GetSuppliersAutoComplete"; + static get addSupplierEngineer => "$_baseUrl/Supplier/AddSupplierEngineer"; static get getSystemNotifications => "$_baseUrl/SystemNotification/GetSystemNotifications"; // get diff --git a/lib/controllers/notification/firebase_notification_manger.dart b/lib/controllers/notification/firebase_notification_manger.dart index fbae40d4..7649388e 100644 --- a/lib/controllers/notification/firebase_notification_manger.dart +++ b/lib/controllers/notification/firebase_notification_manger.dart @@ -18,7 +18,7 @@ Future firebaseMessagingBackgroundHandler(RemoteMessage message) async {} class FirebaseNotificationManger { static FirebaseMessaging messaging = FirebaseMessaging.instance; - static String token; + static String? token; static Future getToken() async { NotificationSettings settings = await messaging.requestPermission( @@ -37,12 +37,12 @@ class FirebaseNotificationManger { } catch (ex) {} } print("pushToken:$token"); - return token; + return token!; } static void handleMessage(context, Map messageData) { if (messageData["requestType"] != null && messageData["requestNumber"] != null) { - Widget serviceClass; + Widget? serviceClass; if (messageData["requestType"] == "Service request to engineer") { serviceClass = ServiceRequestDetailsPage(serviceRequest: ServiceRequest(id: messageData["requestNumber"].toString())); @@ -66,7 +66,7 @@ class FirebaseNotificationManger { // } if (serviceClass != null) { - Navigator.of(context).push(MaterialPageRoute(builder: (_) => serviceClass)); + Navigator.of(context).push(MaterialPageRoute(builder: (_) => serviceClass!)); } } } @@ -105,7 +105,7 @@ class FirebaseNotificationManger { FirebaseMessaging.onMessage.listen((RemoteMessage message) { if (Platform.isAndroid) { NotificationManger.showNotification( - title: message.notification.title, subtext: message.notification.body, hashcode: int.tryParse("1234" ?? "") ?? 1, payload: json.encode(message.data), context: context); + title: message.notification?.title ?? "", subtext: message.notification?.body ?? "", hashcode: int.tryParse("1234" ?? "") ?? 1, payload: json.encode(message.data), context: context); } return; diff --git a/lib/controllers/notification/notification_manger.dart b/lib/controllers/notification/notification_manger.dart index 7bb6de1f..a52d3e38 100644 --- a/lib/controllers/notification/notification_manger.dart +++ b/lib/controllers/notification/notification_manger.dart @@ -9,7 +9,7 @@ class NotificationManger { // private constructor to avoid create object NotificationManger._(); - static FlutterLocalNotificationsPlugin localNotificationsPlugin; //= FlutterLocalNotificationsPlugin(); + static late FlutterLocalNotificationsPlugin localNotificationsPlugin; //= FlutterLocalNotificationsPlugin(); /// initialisation setting for all platform /// onNotificationPressed action when notification pressed to open tap @@ -31,8 +31,8 @@ class NotificationManger { if (Platform.isIOS) { await localNotificationsPlugin.resolvePlatformSpecificImplementation()?.requestPermissions(alert: true, badge: true, sound: true); } else if (Platform.isAndroid) { - AndroidFlutterLocalNotificationsPlugin androidImplementation = localNotificationsPlugin.resolvePlatformSpecificImplementation(); - bool granted = await androidImplementation?.requestPermission(); + AndroidFlutterLocalNotificationsPlugin? androidImplementation = localNotificationsPlugin.resolvePlatformSpecificImplementation(); + bool? granted = await androidImplementation?.requestPermission(); granted = granted ?? false; if (granted == false) { if (kDebugMode) { @@ -50,7 +50,7 @@ class NotificationManger { // push new notificationBuildContext - static Future showNotification({@required context, @required String title, @required String subtext, @required int hashcode, String payload}) async { + static Future showNotification({@required context, required String title, required String subtext, required int hashcode, String? payload}) async { const AndroidNotificationDetails androidChannel = AndroidNotificationDetails( 'com.hmg.atoms', 'ATOMS', diff --git a/lib/controllers/providers/api/asset_transfer_provider.dart b/lib/controllers/providers/api/asset_transfer_provider.dart index 48293a99..edf021b8 100644 --- a/lib/controllers/providers/api/asset_transfer_provider.dart +++ b/lib/controllers/providers/api/asset_transfer_provider.dart @@ -11,7 +11,6 @@ import 'package:test_sa/models/device/asset_transfer.dart'; import 'package:test_sa/models/user.dart'; import '../../../models/hospital.dart'; -import '../../../models/ppm/ppm.dart'; import '../../../new_views/common_widgets/app_lazy_loading.dart'; class AssetTransferProvider extends ChangeNotifier { @@ -37,40 +36,40 @@ class AssetTransferProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int stateCode; + int? stateCode; // true if there is next page in product list and false if not bool nextPage = true; // list of user requests - List items; + List? items; // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; - Hospital hospital; - Buildings building; - Floors floor; - Departments department; - String room; - DateTime startDate; - DateTime endDate; + Hospital? hospital; + Buildings? building; + Floors? floor; + Departments? department; + String room = ""; + DateTime? startDate; + DateTime? endDate; /// return -2 if request in progress - /// return -1 if error happen when sending request + /// return -1if error happen when sending request /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart Future getRequests({ - @required String host, - @required User user, + required String host, + required User user, }) async { if (isLoading == true) return -2; isLoading = true; if (items?.isEmpty ?? true) notifyListeners(); - Response response; + late Response response; try { Map body = {}; body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1; @@ -80,12 +79,12 @@ class AssetTransferProvider extends ChangeNotifier { response = await ApiManager.instance.post(URLs.getDeviceTransfer, body: body); stateCode = response.statusCode; - if (stateCode >= 200 && stateCode < 300) { + if (stateCode! >= 200 && stateCode! < 300) { // client's request was successfully received List listJson = json.decode(response.body)["data"]; List itemsPage = listJson.map((request) => AssetTransfer.fromJson(request)).toList(); items ??= []; - items.addAll(itemsPage.toSet().toList()); + items!.addAll(itemsPage.toSet().toList()); notifyListeners(); if (itemsPage.length == pageItemNumber) { nextPage = true; @@ -104,7 +103,7 @@ class AssetTransferProvider extends ChangeNotifier { } } - Future getRequestById({int assetTransferId}) async { + Future getRequestById({int? assetTransferId}) async { Response response; try { response = await ApiManager.instance.get( @@ -122,18 +121,18 @@ class AssetTransferProvider extends ChangeNotifier { } Future createRequest({ - @required BuildContext context, - @required AssetTransfer assetDestination, - @required Asset asset, + required BuildContext context, + required AssetTransfer assetDestination, + required Asset asset, }) async { Response response; try { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading()); response = await ApiManager.instance.post(URLs.requestDeviceTransfer, body: assetDestination.transferBody(asset: asset)); stateCode = response.statusCode; if (response.statusCode >= 200 && response.statusCode < 300) { if (items != null) { - items.insert(0, AssetTransfer.fromJson(json.decode(utf8.decode(response.bodyBytes))[0])); + items!.insert(0, AssetTransfer.fromJson(json.decode(utf8.decode(response.bodyBytes))[0])); reset(); notifyListeners(); } @@ -149,10 +148,10 @@ class AssetTransferProvider extends ChangeNotifier { } } - Future updateRequest(BuildContext context, {@required AssetTransfer assetTransfer, @required bool isSender}) async { + Future updateRequest(BuildContext context, {required AssetTransfer assetTransfer, required bool isSender}) async { Response response; try { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading()); response = await ApiManager.instance.put(URLs.updateDeviceTransfer, body: assetTransfer.toJson()); //print(response.body); @@ -185,8 +184,8 @@ class AssetTransferProvider extends ChangeNotifier { } } - bool _isLocalUrl(String url) { - if (url?.isEmpty != false) return false; - return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); + bool _isLocalUrl(String? url) { + if (url?.isEmpty ?? true) return false; + return url!.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); } } diff --git a/lib/controllers/providers/api/comments_provider.dart b/lib/controllers/providers/api/comments_provider.dart index 2c30be3a..e1d728f2 100644 --- a/lib/controllers/providers/api/comments_provider.dart +++ b/lib/controllers/providers/api/comments_provider.dart @@ -23,8 +23,8 @@ class CommentsProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed - // 500 service not available - int stateCode; + //500 service not available + int? stateCode; // true if there is next page in product list and false if not bool nextPage = true; @@ -35,18 +35,18 @@ class CommentsProvider extends ChangeNotifier { // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; /// return -2 if request in progress /// return -1 if error happen when sending request /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getComments({@required String callId}) async { + Future getComments({required String callId}) async { if (isLoading == true) return -2; isLoading = true; notifyListeners(); - Response response; + late Response response; try { response = await ApiManager.instance.get(URLs.getComments + "?callRequestId=$callId"); @@ -79,13 +79,13 @@ class CommentsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future addComment(BuildContext context, {@required Comment comment}) async { + Future addComment(BuildContext context, {required Comment comment}) async { if (isLoading == true) return -2; isLoading = true; - Response response; + late Response response; try { comment.id = 0; - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading()); response = await ApiManager.instance.post(URLs.addComment, body: comment.toJson()); stateCode = response.statusCode; diff --git a/lib/controllers/providers/api/departments_provider.dart b/lib/controllers/providers/api/departments_provider.dart index 22a22f47..4994d426 100644 --- a/lib/controllers/providers/api/departments_provider.dart +++ b/lib/controllers/providers/api/departments_provider.dart @@ -1,4 +1,3 @@ -///check deleted import 'dart:convert'; import 'package:flutter/cupertino.dart'; @@ -17,16 +16,16 @@ class DepartmentsProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int stateCode; + int? stateCode; // contain user data // when user not login or register _user = null - List departments; + List? departments; // when categories in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; /// return -2 if request in progress /// return -1 if error happen when sending request @@ -37,7 +36,7 @@ class DepartmentsProvider extends ChangeNotifier { if (isLoading == true) return -2; isLoading = true; notifyListeners(); - Response response; + late Response response; try { response = await ApiManager.instance.post(URLs.getDepartments, body: { "pageSize": 50, diff --git a/lib/controllers/providers/api/devices_provider.dart b/lib/controllers/providers/api/devices_provider.dart index 49927b74..7642ba84 100644 --- a/lib/controllers/providers/api/devices_provider.dart +++ b/lib/controllers/providers/api/devices_provider.dart @@ -30,39 +30,40 @@ class AssetProvider extends ChangeNotifier { bool nextPage = true; - int _stateCode; + int? _stateCode; - int get stateCode => _stateCode; + int? get stateCode => _stateCode; - set stateCode(int code) => _stateCode = code; + set stateCode(int? code) => _stateCode = code; List _devices = []; List _searchDevices = []; List get devices => _devices; + List get searchDevices => _searchDevices; // when categories in-process _loading = true // done _loading = true // failed _loading = false - bool _loading; + bool _loading = false; bool get isLoading => _loading; - AssetByIdModel _assetById; + AssetByIdModel? _assetById; - AssetByIdModel get assetById => _assetById; + AssetByIdModel? get assetById => _assetById; set isLoading(bool isLoading) { _loading = isLoading; notifyListeners(); } - Future getAssets({AssetSearch search, bool isQr = false, bool isSearchBy = false}) async { + Future getAssets({AssetSearch? search, bool isQr = false, bool isSearchBy = false}) async { if (_loading == true) return -2; _loading = true; notifyListeners(); - Response response; + late Response response; try { final Map body = { "pageSize": isSearchBy ? searchPageItemNumber : pageItemNumber, @@ -99,7 +100,7 @@ class AssetProvider extends ChangeNotifier { } Future getAssetById(int assetId, AppLocalizations appLocalizations) async { - Response response; + late Response response; try { response = await ApiManager.instance.get(URLs.getAssetById + "$assetId"); } catch (error) { @@ -111,21 +112,21 @@ class AssetProvider extends ChangeNotifier { // client's request was successfully received Map assetData = json.decode(response.body)["data"]; _assetById = AssetByIdModel.fromJson(assetData); - return _assetById; + return _assetById!; } throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: appLocalizations)); } Future> getDevicesList({ - @required String host, - @required User user, - @required int hospitalId, + required String host, + required User user, + required int hospitalId, // String serialNumber, // String number, bool addPagination = true, - AssetSearch search, + AssetSearch? search, }) async { - Response response; + late Response response; try { Map body = { // "pageSize": pageItemNumber, @@ -162,13 +163,11 @@ class AssetProvider extends ChangeNotifier { } Future> getModels({ - String code, + String? code, }) async { - Response response; + late Response response; try { - response = await ApiManager.instance.get( - URLs.getModels + "?code=$code", - ); + response = await ApiManager.instance.get(URLs.getModels + "?code=${code ?? ""}"); List page = []; if (response.statusCode >= 200 && response.statusCode < 300) { // client's request was successfully received @@ -186,32 +185,4 @@ class AssetProvider extends ChangeNotifier { return []; } } - -// /// return -2 if request in progress -// /// return -1 if error happen when sending request -// /// return state code if request complete may be 200, 404 or 403 -// /// for more details check http state manager -// /// lib\controllers\http_status_manger\http_status_manger.dart -// Future> getDevicesListBySN({@required String host, @required User user, @required int hospitalId, @required String sn}) async { -// Response response; -// try { -// response = await get( -// Uri.parse(URLs.getEquipment + "?client=$hospitalId" + (sn == null || sn.isEmpty ? "" : "&serial_qr=$sn")), -// ); -// -// _stateCode = response.statusCode; -// List _page = []; -// if (response.statusCode >= 200 && response.statusCode < 300) { -// // client's request was successfully received -// List categoriesListJson = json.decode(utf8.decode(response.bodyBytes)); -// _page = categoriesListJson.map((device) => Device.fromJson(device)).toList(); -// } -// return _page; -// } catch (error) { -// _loading = false; -// _stateCode = -1; -// notifyListeners(); -// return []; -// } -// } } diff --git a/lib/controllers/providers/api/gas_refill_comments.dart b/lib/controllers/providers/api/gas_refill_comments.dart index 0c7ab63b..10a5fa76 100644 --- a/lib/controllers/providers/api/gas_refill_comments.dart +++ b/lib/controllers/providers/api/gas_refill_comments.dart @@ -22,9 +22,8 @@ class GasRefillCommentsProvider extends ChangeNotifier { } // state code of current request to defied error message - // like 400 customer request failed - // 500 service not available - int stateCode; + // like 400 customer request failed// 500 service not available + int? stateCode; // true if there is next page in product list and false if not bool nextPage = true; @@ -35,18 +34,18 @@ class GasRefillCommentsProvider extends ChangeNotifier { // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; /// return -2 if request in progress /// return -1 if error happen when sending request /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getComments({@required String callId}) async { + Future getComments({required String callId}) async { if (isLoading == true) return -2; isLoading = true; notifyListeners(); - Response response; + late Response response; try { response = await ApiManager.instance.get(URLs.getGazRefillComments + "?gasRefillId=$callId"); @@ -56,8 +55,8 @@ class GasRefillCommentsProvider extends ChangeNotifier { List commentsPage = requestsListJson.map((request) => GasRefillComment.fromJson(request)).toList(); comments ??= []; comments.addAll(commentsPage); - comments.sort((a,b) { - return b.createdOn.compareTo(a.createdOn); + comments.sort((a, b) { + return b.createdOn!.compareTo(a.createdOn!); }); if (commentsPage.length == pageItemNumber) { nextPage = true; @@ -82,12 +81,12 @@ class GasRefillCommentsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future addComment(BuildContext context, {@required String comment, int id}) async { + Future addComment(BuildContext context, {required String comment, required int id}) async { if (isLoading == true) return -2; isLoading = true; - Response response; + late Response response; try { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading()); response = await ApiManager.instance.post(URLs.addGazRefillComment, body: {"id": 0, "gasRefillId": id, "comment": comment}); stateCode = response.statusCode; diff --git a/lib/controllers/providers/api/gas_refill_provider.dart b/lib/controllers/providers/api/gas_refill_provider.dart index 6ada850c..3077cda2 100644 --- a/lib/controllers/providers/api/gas_refill_provider.dart +++ b/lib/controllers/providers/api/gas_refill_provider.dart @@ -31,20 +31,20 @@ class GasRefillProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int stateCode; + int? stateCode; // true if there is next page in product list and false if not bool nextPage = true; // list of user requests - List items; + List? items; // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; - Future getGasRefillObjectById(num id) async { + Future getGasRefillObjectById(num id) async { try { Response response = await ApiManager.instance.get(URLs.getGasRefillById + "?gazRefillId=$id"); if (response.statusCode >= 200 && response.statusCode < 300) { @@ -63,14 +63,14 @@ class GasRefillProvider extends ChangeNotifier { /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart Future getRequests({ - @required String host, - @required User user, - @required bool mostRecent, + required String host, + required User user, + required bool mostRecent, }) async { if (isLoading == true) return -2; isLoading = true; if (items?.isEmpty ?? true) notifyListeners(); - Response response; + late Response response; Map body = {}; body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1; @@ -79,12 +79,12 @@ class GasRefillProvider extends ChangeNotifier { response = await ApiManager.instance.post(URLs.getGasRefill, body: body); stateCode = response.statusCode; - if (stateCode >= 200 && stateCode < 300) { + if (stateCode! >= 200 && stateCode! < 300) { // client's request was successfully received List requestsListJson = json.decode(response.body)["data"]; List itemsPage = requestsListJson.map((request) => GasRefillModel.fromJson(request)).toList(); items ??= []; - items.addAll(itemsPage); + items!.addAll(itemsPage); notifyListeners(); if (itemsPage.length == pageItemNumber) { nextPage = true; @@ -105,13 +105,13 @@ class GasRefillProvider extends ChangeNotifier { } Future createModel({ - @required BuildContext context, - @required User user, - @required GasRefillModel model, + required BuildContext context, + required User user, + required GasRefillModel model, }) async { - Response response; + late Response response; try { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading()); final Map body = { "uid": user.id.toString(), "token": user.token ?? "", @@ -137,10 +137,10 @@ class GasRefillProvider extends ChangeNotifier { } Future updateModel({ - @required String host, - @required User user, - @required GasRefillModel oldModel, - @required GasRefillModel newModel, + required String host, + required User user, + required GasRefillModel oldModel, + required GasRefillModel newModel, }) async { Map body = { "id": newModel.id, @@ -148,13 +148,12 @@ class GasRefillProvider extends ChangeNotifier { "status": newModel.status?.toJson(), //"expectedDate": newModel.expectedDate?.toIso8601String(), "expectedTime": newModel.expectedDate, - if (newModel.timer?.startAt != null) "startDate": newModel.timer.startAt.toIso8601String(), - if (newModel.timer?.startAt != null) "startTime": newModel.timer.startAt.toIso8601String(), - if (newModel.timer?.endAt != null) "endDate": newModel.timer.endAt.toIso8601String(), - if (newModel.timer?.endAt != null) "endTime": newModel.timer.endAt.toIso8601String(), + if (newModel.timer?.startAt != null) "startDate": newModel.timer!.startAt!.toIso8601String(), + if (newModel.timer?.startAt != null) "startTime": newModel.timer!.startAt!.toIso8601String(), + if (newModel.timer?.endAt != null) "endDate": newModel.timer!.endAt!.toIso8601String(), if (newModel.timer?.endAt != null) "endTime": newModel.timer!.endAt!.toIso8601String(), // "workingHours": ((endDate?.difference(startDate)?.inMinutes ?? 0) / 60), - 'workingHours': newModel.timer?.durationInSecond != null ? newModel.timer.durationInSecond / 60 / 60 : newModel.workingHours, - "assignedEmployee": oldModel?.assignedEmployee?.id == null ? null : oldModel?.assignedEmployee?.toJson(), + 'workingHours': newModel.timer?.durationInSecond != null ? newModel.timer!.durationInSecond! / 60 / 60 : newModel.workingHours, + "assignedEmployee": oldModel.assignedEmployee?.id == null ? null : oldModel.assignedEmployee?.toJson(), "site": hospital?.toMap(), "building": building?.toJson(includeFloors: false), "floor": floor?.toJson(includeDepartments: false), @@ -174,7 +173,7 @@ class GasRefillProvider extends ChangeNotifier { }) .toList(); log(body.toString()); - Response response; + late Response response; try { response = await ApiManager.instance.put(URLs.updateGasRefill, body: body); // response = await post( @@ -193,10 +192,10 @@ class GasRefillProvider extends ChangeNotifier { } } - Hospital hospital; - Buildings building; - Floors floor; - Departments department; - DateTime expectedDateTime; + Hospital? hospital; + Buildings? building; + Floors? floor; + Departments? department; + DateTime? expectedDateTime; //TimerModel timer; } diff --git a/lib/controllers/providers/api/hospitals_provider.dart b/lib/controllers/providers/api/hospitals_provider.dart index d9e6e42e..507d72e7 100644 --- a/lib/controllers/providers/api/hospitals_provider.dart +++ b/lib/controllers/providers/api/hospitals_provider.dart @@ -21,9 +21,9 @@ class HospitalsProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int _stateCode; + int? _stateCode; - int get stateCode => _stateCode; + int? get stateCode => _stateCode; // true if there is next page in product list and false if not bool _nextPage = true; @@ -32,14 +32,14 @@ class HospitalsProvider extends ChangeNotifier { // contain user data // when user not login or register _user = null - List _hospitals; + List? _hospitals; - List get hospitals => _hospitals; + List? get hospitals => _hospitals; // when categories in-process _loading = true // done _loading = true // failed _loading = false - bool _loading; + bool _loading = false; bool get isLoading => _loading; @@ -53,11 +53,11 @@ class HospitalsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getHospitals({String host, User user, String title}) async { + Future getHospitals({String? host, User? user, String? title}) async { if (_loading == true) return -2; _loading = true; notifyListeners(); - Response response; + late Response response; try { response = await ApiManager.instance.post(URLs.getSites, body: { "pageNumber": (hospitals?.length ?? 0) ~/ pageItemNumber + 1, @@ -71,7 +71,7 @@ class HospitalsProvider extends ChangeNotifier { List _page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList(); if (hospitals == null) _hospitals = []; - _hospitals.addAll(_page); + _hospitals!.addAll(_page); if (_page.length >= pageItemNumber) { _nextPage = true; } else { @@ -89,8 +89,8 @@ class HospitalsProvider extends ChangeNotifier { } } - Future> getHospitalsList({String host, User user, String title}) async { - Response response; + Future> getHospitalsList({String? host, User? user, String? title}) async { + late Response response; try { response = await ApiManager.instance.post(URLs.getSites, body: { "pageSize": 50, @@ -121,7 +121,7 @@ class HospitalsProvider extends ChangeNotifier { } Future> getHospitalsListByVal({String searchVal = ""}) async { - Response response; + late Response response; try { if (searchVal.isNotEmpty) { searchVal = "?searchText=$searchVal"; diff --git a/lib/controllers/providers/api/notifications_provider.dart b/lib/controllers/providers/api/notifications_provider.dart index 75fec696..84fd6578 100644 --- a/lib/controllers/providers/api/notifications_provider.dart +++ b/lib/controllers/providers/api/notifications_provider.dart @@ -19,12 +19,11 @@ class NotificationsProvider extends ChangeNotifier { } // state code of current request to defied error message - // like 400 customer request failed - // 500 service not available - int stateCode; + // like 400 customer request failed// 500 service not available + int? stateCode; // true if there is next page in product list and false if not - bool nextPage = true; + bool nextPage = true; // Properly initialized // list of user requests List notifications = []; @@ -32,14 +31,14 @@ class NotificationsProvider extends ChangeNotifier { // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; /// return -2 if request in progress /// return -1 if error happen when sending request /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getSystemNotifications({User user, bool resetProvider = false}) async { + Future getSystemNotifications({required User user, bool resetProvider = false}) async { if (isLoading == true) return -2; if (resetProvider) { @@ -47,7 +46,7 @@ class NotificationsProvider extends ChangeNotifier { } isLoading = true; notifyListeners(); - Response response; + late Response response; try { final Map body = {"pageSize": pageItemNumber, "pageNumber": notifications.length ~/ pageItemNumber + 1, "userId": user.userID}; response = await ApiManager.instance.post(URLs.getSystemNotifications, body: body); @@ -56,17 +55,12 @@ class NotificationsProvider extends ChangeNotifier { print('notifaction response is ${response}'); if (response.statusCode >= 200 && response.statusCode < 300) { // client's request was successfully received - // List requestsListJson = json.decode(utf8.decode(response.bodyBytes)); - List requestsListJson = json.decode(response.body)["data"]; List _serviceRequestsPage = requestsListJson.map((request) => SystemNotificationModel.fromJson(request)).toList(); if (notifications == null) notifications = []; notifications.addAll(_serviceRequestsPage); - if (_serviceRequestsPage.length == pageItemNumber) { - nextPage = true; - } else { - nextPage = false; - } + // Update nextPage based on response length + nextPage = _serviceRequestsPage.length == pageItemNumber; } isLoading = false; notifyListeners(); @@ -85,11 +79,11 @@ class NotificationsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future> getRecentNotifications({ - @required String host, - @required User user, + Future?> getRecentNotifications({ + required String host, + required User user, }) async { - Response response; + late Response response; //userId = 397.toString(); // testing id to view data try { diff --git a/lib/controllers/providers/api/parts_provider.dart b/lib/controllers/providers/api/parts_provider.dart index 842c63a7..8cc463b1 100644 --- a/lib/controllers/providers/api/parts_provider.dart +++ b/lib/controllers/providers/api/parts_provider.dart @@ -20,25 +20,25 @@ class PartsProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int _stateCode; + int? _stateCode; - int get stateCode => _stateCode; + int? get stateCode => _stateCode; - // true if there is next page in product list and false if not + // true if there is next pagein product list and false if not bool _nextPage = true; bool get nextPage => _nextPage; // contain user data // when user not login or register _user = null - List _parts; + List? _parts; - List get parts => _parts; + List? get parts => _parts; // when categories in-process _loading = true // done _loading = true // failed _loading = false - bool _loading; + bool _loading = false; bool get isLoading => _loading; @@ -52,11 +52,11 @@ class PartsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getParts({String title}) async { + Future getParts({String? title}) async { if (_loading == true) return -2; _loading = true; notifyListeners(); - Response response; + late Response response; try { response = await ApiManager.instance.post(URLs.getPartNumber, body: {if (title != null && title.isNotEmpty) "partName": title}); _stateCode = response.statusCode; @@ -65,12 +65,8 @@ class PartsProvider extends ChangeNotifier { List categoriesListJson = json.decode(utf8.decode(response.bodyBytes)); List _page = categoriesListJson.map((part) => SparePart.fromJson(part)).toList(); _parts ??= []; - _parts.addAll(_page.map((e) => SparePartsWorkOrders(sparePart: e)).toList()); - if (_page.length >= pageItemNumber) { - _nextPage = true; - } else { - _nextPage = false; - } + _parts!.addAll(_page.map((e) => SparePartsWorkOrders(sparePart: e)).toList()); + _nextPage = _page.length >= pageItemNumber; } _loading = false; notifyListeners(); @@ -88,8 +84,8 @@ class PartsProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future> getPartsList({num assetId, String partNo, String partName}) async { - Response response; + Future> getPartsList({num? assetId, String? partNo, String? partName}) async { + late Response response; try { if (partNo != null) { response = await ApiManager.instance.post(URLs.getPartNumber, body: {"partNo": partNo, "assetId": assetId}); diff --git a/lib/controllers/providers/api/ppm_provider.dart b/lib/controllers/providers/api/ppm_provider.dart index 1570737b..e2310270 100644 --- a/lib/controllers/providers/api/ppm_provider.dart +++ b/lib/controllers/providers/api/ppm_provider.dart @@ -27,18 +27,18 @@ class PpmProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int stateCode; + int? stateCode; // Now nullable // true if there is next page in product list and false if not bool nextPage = true; // list of user requests - List ppms; + List? ppms; // Now nullable // when requests in-process _loading = true // done _loading = true // failed _loading = false - bool isLoading; + bool isLoading = false; PpmSearch visitsSearch = PpmSearch(); @@ -48,15 +48,14 @@ class PpmProvider extends ChangeNotifier { /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart Future getVisits({ - @required String host, - @required User user, - // VisitsSearch visitsSearch, + required String host, + required User user, + //VisitsSearch visitsSearch, }) async { if (isLoading == true) return -2; isLoading = true; if (ppms?.isEmpty ?? true) notifyListeners(); - Response response; - //userId = 397.toString(); // testing id to view data + late Response response; // Using 'late' for initialization later try { Map body = {}; @@ -80,8 +79,8 @@ class PpmProvider extends ChangeNotifier { try { List requestsListJson = json.decode(response.body)["data"]; List visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList(); - ppms ??= []; - ppms.addAll(visits); + ppms ??= []; // Initialize if null + ppms!.addAll(visits); // Use '!' since ppms is now non-nullable after initialization notifyListeners(); if (visits.length == pageItemNumber) { nextPage = true; @@ -89,7 +88,7 @@ class PpmProvider extends ChangeNotifier { nextPage = false; } } catch (error) { - log(error ?? ""); + log(error.toString()); // Convert error to string isLoading = false; stateCode = -1; notifyListeners(); @@ -101,7 +100,8 @@ class PpmProvider extends ChangeNotifier { return response.statusCode; } - Future getPpmById(num id) async { + Future getPpmById(num id) async { + // Return type is nullable try { visitsSearch.id = id; visitsSearch.pageNumber = 1; @@ -111,7 +111,7 @@ class PpmProvider extends ChangeNotifier { if (response.statusCode >= 200 && response.statusCode < 300) { List requestsListJson = json.decode(response.body)["data"]; List visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList(); - return visits?.firstWhere((element) => id == element.id, orElse: () => null); + return visits.firstWhere((element) => id == element.id, orElse: null); // Handle case where no element is found } return null; } catch (error) { @@ -125,11 +125,11 @@ class PpmProvider extends ChangeNotifier { /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart Future updateGroupOfVisits({ - @required String host, - @required User user, + required String host, + required User user, // VisitsGroup group, }) async { - Response response; + late Response response; // Using 'late' for initialization later try { Map body = {} /*group.toJson()*/; @@ -154,10 +154,11 @@ class PpmProvider extends ChangeNotifier { } } - Future getPentry({String host, User user, int id}) async { + Future getPentry({required String host, required User user, required int id}) async { + // Return type is nullable Response response; response = await ApiManager.instance.get("${URLs.getPentry}/$id"); - Ppm pantry; + Ppm? pantry; // Now nullable if (response.statusCode >= 200 && response.statusCode < 300) { pantry = Ppm.fromJson(json.decode(utf8.decode(response.bodyBytes))); } @@ -166,20 +167,20 @@ class PpmProvider extends ChangeNotifier { Future updatePentry( BuildContext context, { - @required User user, - @required Ppm ppm, + required User user, + required Ppm ppm, }) async { try { ppm.visitTimers.add( VisitTimers( id: 0, - startDateTime: ppm.tbsTimer?.startAt?.toIso8601String(), - endDateTime: ppm.tbsTimer?.endAt?.toIso8601String(), + startDateTime: ppm.tbsTimer?.startAt!.toIso8601String(), // Handle potential null + endDateTime: ppm.tbsTimer?.endAt?.toIso8601String(), // Handle potential null workingHours: ((ppm.tbsTimer?.durationInSecond ?? 0) / 60 / 60), ), ); showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); - Response response; + late Response response; // Using 'late' for initialization later Map body = ppm.copyWith(assignedEmployeeId: user.userName, tbsTimer: ppm.tbsTimer).toJson(); response = await ApiManager.instance.put(URLs.updatePentry, body: body); if (response.statusCode >= 200 && response.statusCode < 300) { diff --git a/lib/controllers/providers/api/service_requests_provider.dart b/lib/controllers/providers/api/service_requests_provider.dart index aa865b04..a51f396a 100644 --- a/lib/controllers/providers/api/service_requests_provider.dart +++ b/lib/controllers/providers/api/service_requests_provider.dart @@ -249,9 +249,9 @@ class ServiceRequestsProvider extends ChangeNotifier { } Future createIssueReport({ - @required String host, - @required User user, - @required Issue issue, + required String host, + required User user, + required Issue issue, }) async { Response response; Map body = issue.toMap(); diff --git a/lib/controllers/providers/api/status_drop_down/employee/nurse_provider.dart b/lib/controllers/providers/api/status_drop_down/employee/nurse_provider.dart index 62267bcf..b9a7e7e4 100644 --- a/lib/controllers/providers/api/status_drop_down/employee/nurse_provider.dart +++ b/lib/controllers/providers/api/status_drop_down/employee/nurse_provider.dart @@ -2,11 +2,9 @@ import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:http/http.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/models/employee.dart'; -import 'package:test_sa/models/user.dart'; class NurseProvider extends ChangeNotifier { //reset provider data @@ -15,17 +13,17 @@ class NurseProvider extends ChangeNotifier { _stateCode = null; } - int _stateCode; + int? _stateCode; // Now nullable - int get stateCode => _stateCode; - List _items; + int? get stateCode => _stateCode; + List? _items; // Now nullable - List get nursesList => _items; - bool _loading; + List get nursesList => _items ?? []; // Return empty list if null + bool _loading = false; // Initialize loading to false bool get isLoading => _loading; - int siteId; + int? siteId; // Now nullable set isLoading(bool isLoading) { _loading = isLoading; @@ -33,10 +31,9 @@ class NurseProvider extends ChangeNotifier { } Future getData() async { - if (_loading == true) return -2; + if (_loading) return -2; _loading = true; notifyListeners(); - Response response; try { if (siteId == null) { await Future.delayed(const Duration(seconds: 1)); @@ -44,15 +41,14 @@ class NurseProvider extends ChangeNotifier { _loading = false; notifyListeners(); _stateCode = 200; - return _stateCode; + return _stateCode!; // Non-null assertion since _stateCode is set to 200 } - response = await ApiManager.instance.get(URLs.getNursesBySiteId + "&siteId=$siteId"); + final response = await ApiManager.instance.get(URLs.getNursesBySiteId + "&siteId=$siteId"); _stateCode = response.statusCode; if (response.statusCode >= 200 && response.statusCode < 300) { - // client's request was successfully received - List categoriesListJson = json.decode(response.body); + final categoriesListJson = json.decode(response.body) as List; _items = categoriesListJson.map((type) => Employee.fromJson(type)).toList(); - _items.sort((a, b) => a.name.compareTo(b.name)); + _items!.sort((a, b) => a.name!.compareTo(b.name!)); // Null-aware operator for sorting } _loading = false; notifyListeners(); diff --git a/lib/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart b/lib/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart index 60b40d1b..706f86d5 100644 --- a/lib/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart +++ b/lib/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; -import 'package:test_sa/models/user.dart'; import '../../../../../models/fault_description.dart'; @@ -19,20 +18,20 @@ class ServiceRequestFaultDescriptionProvider extends ChangeNotifier { // state code of current request to defied error message // like 400 customer request failed // 500 service not available - int _stateCode; + int? _stateCode; - int get stateCode => _stateCode; + int? get stateCode => _stateCode; // contain user data // when user not login or register _user = null - List _items; + List? _items; - List get items => _items; + List? get items => _items; // when categories in-process _loading = true // done _loading = true // failed _loading = false - bool _loading; + bool _loading = false; // Initialize _loading to false bool get isLoading => _loading; @@ -46,7 +45,7 @@ class ServiceRequestFaultDescriptionProvider extends ChangeNotifier { /// return state code if request complete may be 200, 404 or 403 /// for more details check http state manager /// lib\controllers\http_status_manger\http_status_manger.dart - Future getCallRequestForWorkOrder({String host, User user, String requestId}) async { + Future getCallRequestForWorkOrder(String requestId) async { if (_loading == true) return -2; _loading = true; notifyListeners(); diff --git a/lib/controllers/providers/settings/setting_provider.dart b/lib/controllers/providers/settings/setting_provider.dart index 4824b6f3..5097310a 100644 --- a/lib/controllers/providers/settings/setting_provider.dart +++ b/lib/controllers/providers/settings/setting_provider.dart @@ -12,7 +12,33 @@ import 'package:test_sa/models/user.dart'; import '../settings/app_settings.dart'; class SettingProvider extends ChangeNotifier { - resetSettings() async { + // Check if settings are loaded or not + bool isLoaded = false; + + // Contain saved user data + User? user; + + // AssetGroup + AssetGroup? _assetGroup; + String? _host; + String? _language; + String? _theme; + String? _speechToText; + + // Other settings + bool rememberMe = false; + String username = ""; + String password = ""; + bool isLocalAuthEnable = false; + + // Local authentication instance + final LocalAuthentication auth = LocalAuthentication(); + + SettingProvider() { + loadSharedPreferences(); + } + + Future resetSettings() async { SharedPreferences prefs = await SharedPreferences.getInstance(); user = null; _assetGroup = null; @@ -22,12 +48,6 @@ class SettingProvider extends ChangeNotifier { notifyListeners(); } - // check if setting loaded or not - bool isLoaded = false; - - // contain saved user data - User user; - Future setUser(User user) async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString(ASettings.user, json.encode(user.toJson())); @@ -56,20 +76,15 @@ class SettingProvider extends ChangeNotifier { } } setAssetGroup(_assetGroup); - // ApiManager.instance.assetGroup = _assetGroup; } - Future setAssetGroup(AssetGroup assetGroup) async { - // SharedPreferences prefs = await SharedPreferences.getInstance(); - // prefs.setString(ASettings.assetGroup, json.encode(assetGroup.toJson())); + Future setAssetGroup(AssetGroup? assetGroup) async { _assetGroup = assetGroup; - ApiManager.instance.assetGroup = _assetGroup; + ApiManager.instance.assetGroup = _assetGroup!; notifyListeners(); } - String _host; - - String get host => _host; + String? get host => _host; Future setHost(String host) async { SharedPreferences prefs = await SharedPreferences.getInstance(); @@ -78,16 +93,13 @@ class SettingProvider extends ChangeNotifier { notifyListeners(); } - String _language; - AssetGroup _assetGroup; + String? get language => _language; - String get language => _language; + AssetGroup? get assetGroup => _assetGroup; - AssetGroup get assetGroup => _assetGroup; + String? get theme => _theme; - bool rememberMe = false; - String username = ""; - String password = ""; + bool get localAuth => isLocalAuthEnable; Future setLanguage(String currentLanguage) async { SharedPreferences prefs = await SharedPreferences.getInstance(); @@ -96,8 +108,6 @@ class SettingProvider extends ChangeNotifier { notifyListeners(); } - bool isLocalAuthEnable = false; - Future setAuth(bool status) async { SharedPreferences prefs = await SharedPreferences.getInstance(); isLocalAuthEnable = status; @@ -105,22 +115,7 @@ class SettingProvider extends ChangeNotifier { notifyListeners(); } - String _theme; - - String get theme => _theme; - - bool get localAuth => isLocalAuthEnable; - - Future setDarkTheme(bool value) async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - _theme = value ? "dark" : "light"; - prefs.setString(ASettings.theme, _theme); - notifyListeners(); - } - - String _speechToText; - - String get speechToText => _speechToText; + String? get speechToText => _speechToText; Future setSpeechToText(String currentLanguage) async { SharedPreferences prefs = await SharedPreferences.getInstance(); @@ -129,79 +124,47 @@ class SettingProvider extends ChangeNotifier { notifyListeners(); } - // call loadSharedPreferences when provider initialise - SettingProvider() { - loadSharedPreferences(); + Future setDarkTheme(bool value) async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + _theme = value ? "dark" : "light"; + prefs.setString(ASettings.theme, _theme!); + notifyListeners(); } - LocalAuthentication auth = LocalAuthentication(); - - // get app setting + // Get app setting Future loadSharedPreferences() async { SharedPreferences prefs = await SharedPreferences.getInstance(); - if (prefs.containsKey(ASettings.language)) { - _language = prefs.getString(ASettings.language); - } else { - _language = 'en'; - } - - if (prefs.containsKey(ASettings.theme)) { - _theme = prefs.getString(ASettings.theme); - } else { - _theme = 'light'; - } - - if (prefs.containsKey(ASettings.localAuth)) { - isLocalAuthEnable = prefs.getBool(ASettings.localAuth); - } else { - isLocalAuthEnable = false; - } - - if (prefs.containsKey(ASettings.speechToText)) { - _speechToText = prefs.getString(ASettings.speechToText); - } else { - _speechToText = 'ar'; - } + _language = prefs.getString(ASettings.language) ?? 'en'; + _theme = prefs.getString(ASettings.theme) ?? 'light'; + isLocalAuthEnable = prefs.getBool(ASettings.localAuth) ?? false; + _speechToText = prefs.getString(ASettings.speechToText) ?? 'ar'; if (prefs.containsKey(ASettings.user)) { - String userJson = prefs.getString(ASettings.user); + String userJson = prefs.getString(ASettings.user)!; user = User.fromJson(json.decode(userJson)); - selectAssetGroup(user); + selectAssetGroup(user!); } rememberMe = prefs.getBool(ASettings.rememberMe) ?? false; username = prefs.getString(ASettings.userName) ?? ""; password = prefs.getString(ASettings.password) ?? ""; - // if (prefs.containsKey(ASettings.assetGroup)) { // - // String assetJson = prefs.getString(ASettings.assetGroup); - // _assetGroup = AssetGroup.fromJson(json.decode(assetJson)); - // } - - if (prefs.containsKey(ASettings.host)) { - _host = prefs.getString(ASettings.host); - } else { - _host = URLs.host1; - } + _host = prefs.getString(ASettings.host) ?? URLs.host1; isLoaded = true; notifyListeners(); } Future checkUserTokenValidation(String token) async { - Response response; - bool isValid = false; try { - Map body = {}; - response = await ApiManager.instance.post(URLs.checkLoginValidation + "?token=$token", body: body); - if (response.statusCode >= 200 && response.statusCode < 300) { - isValid = true; - } - - return isValid; + final response = await ApiManager.instance.post( + "${URLs.checkLoginValidation}?token=$token", + body: {}, + ); + return response.statusCode >= 200 && response.statusCode < 300; } catch (error) { - return isValid; + return false; } } } diff --git a/lib/dashboard_latest/dashboard_view.dart b/lib/dashboard_latest/dashboard_view.dart index 1a544913..0306fbdc 100644 --- a/lib/dashboard_latest/dashboard_view.dart +++ b/lib/dashboard_latest/dashboard_view.dart @@ -10,12 +10,9 @@ import 'package:test_sa/controllers/providers/api/notifications_provider.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/controllers/providers/settings/setting_provider.dart'; import 'package:test_sa/dashboard_latest/widgets/app_bar_widget.dart'; -import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; -import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/user.dart'; -import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/progress_fragment.dart'; import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/requests_fragment.dart'; import 'package:test_sa/utilities/request_utils.dart'; @@ -78,28 +75,25 @@ class _DashboardViewState extends State { allRequestsProvider.filterRequest = null; var tabs = RequestUtils.getTabs(userType: userProvider.user.type, context: context); allRequestsProvider.status = tabs[0]['status']; - allRequestsProvider.getRequests(); - allRequestsProvider.pageNum = 1; - allRequestsProvider.getFilterRequests(showLoader: true, status: tabs[0]['status']).whenComplete(() { - allRequestsProvider.requestDetailList = allRequestsProvider.filterRequest; - }); - allRequestsProvider.isAllLoading = false; - notificationsProvider.getSystemNotifications(user: userProvider.user, resetProvider: true); + allRequestsProvider.getRequests(); + allRequestsProvider.pageNum = 1; + allRequestsProvider.getFilterRequests(showLoader: true, status: tabs[0]['status']).whenComplete(() { + allRequestsProvider.requestDetailList = allRequestsProvider.filterRequest; + }); + allRequestsProvider.isAllLoading = false; + notificationsProvider.getSystemNotifications(user: userProvider.user, resetProvider: true); } - void handleScroll() async{ + void handleScroll() async { _scrollController = ScrollController(); _scrollController.addListener(() async { - if (_scrollController?.position?.pixels == - _scrollController?.position?.maxScrollExtent && - !allRequestsProvider.isFilterRequestLoading) { + if (_scrollController?.position?.pixels == _scrollController?.position?.maxScrollExtent && !allRequestsProvider.isFilterRequestLoading) { allRequestsProvider.pageNum = allRequestsProvider.pageNum + 1; - await allRequestsProvider.getFilterRequests(showLoader:false,status: allRequestsProvider.status); + await allRequestsProvider.getFilterRequests(showLoader: false, status: allRequestsProvider.status); } }); } - @override void dispose() { _scrollController.dispose(); @@ -110,33 +104,21 @@ class _DashboardViewState extends State { Widget build(BuildContext context) { return Scaffold( // backgroundColor: AppColor.background(context), - appBar: PreferredSize( - preferredSize: const Size.fromHeight(kToolbarHeight), - child: AppBarWidget( - onDrawerPress: widget.onDrawerPress, - )), + appBar: PreferredSize(preferredSize: const Size.fromHeight(kToolbarHeight), child: AppBarWidget(onDrawerPress: widget.onDrawerPress)), body: RefreshIndicator( onRefresh: () async { - getInitialData(); + getInitialData(); return Future.delayed(const Duration(milliseconds: 250)); }, child: Scrollbar( controller: _scrollController, child: SingleChildScrollView( - // physics: AlwaysScrollableScrollPhysics(), - controller: _scrollController, + // physics: AlwaysScrollableScrollPhysics(), + controller: _scrollController, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, - children: [ - 14.height, - ProgressFragment(), - 25.height, - SizedBox( - height: 110.toScreenHeight, child: const RequestsFragment()), - 16.height, - const RequestCategoryFragment() - ], + children: [14.height, ProgressFragment(), 25.height, SizedBox(height: 110.toScreenHeight, child: const RequestsFragment()), 16.height, const RequestCategoryFragment()], ).paddingOnly(start: 16, end: 16, top: 0, bottom: 8), ), ), diff --git a/lib/dashboard_latest/widgets/app_bar_widget.dart b/lib/dashboard_latest/widgets/app_bar_widget.dart index 09500dac..ea13c125 100644 --- a/lib/dashboard_latest/widgets/app_bar_widget.dart +++ b/lib/dashboard_latest/widgets/app_bar_widget.dart @@ -14,9 +14,9 @@ import '../../controllers/providers/api/user_provider.dart'; import '../../models/user.dart'; class AppBarWidget extends StatelessWidget { - final VoidCallback onDrawerPress; + final VoidCallback onDrawerPress; // Made nullable - const AppBarWidget({Key key, this.onDrawerPress}) : super(key: key); + const AppBarWidget({Key? key, required this.onDrawerPress}) : super(key: key); @override Widget build(BuildContext context) { @@ -36,23 +36,23 @@ class AppBarWidget extends StatelessWidget { padding: const EdgeInsets.all(1), // Border radius child: ClipOval( child: snapshot.profileImage != null - ? Image.file(snapshot.profileImage) - : (snapshot.user.profilePhotoName?.isNotEmpty ?? false) - ? Image.network(snapshot.user.profilePhotoName) + ? Image.file(snapshot.profileImage!) // Added null check + : (snapshot.user?.profilePhotoName?.isNotEmpty ?? false) + ? Image.network(snapshot.user!.profilePhotoName!) // Added null check : const Icon(Icons.person, size: 24, color: Colors.white), ), ), - ).onPress(onDrawerPress), + ).onPress(onDrawerPress), // Handle potential null 8.width, Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - snapshot.user == null ? "" : (snapshot.user?.username ?? ""), + snapshot.user?.username ?? "", // Simplified null check style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600), ), Text( - snapshot.user == null ? "" : snapshot.user?.type?.name?.toCamelCase ?? "", + snapshot.user?.type?.name?.toCamelCase ?? "", // Simplified null check style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20), ), ], @@ -73,7 +73,8 @@ class AppBarWidget extends StatelessWidget { ) ], ), - child: DropdownButton( + child: DropdownButton( + // Made AssetGroup nullable value: settingProvider.assetGroup, //iconSize: 24, isDense: true, @@ -88,19 +89,22 @@ class AppBarWidget extends StatelessWidget { settingProvider.setAssetGroup(newValue); WidgetsBinding.instance.addPostFrameCallback((_) { Provider.of(context, listen: false).getRequests(); - Provider.of(context, listen: false).getSystemNotifications(user: Provider.of(context, listen: false).user, resetProvider: true); + Provider.of(context, listen: false) + .getSystemNotifications(user: Provider.of(context, listen: false).user!, resetProvider: true); // Added null check }); } }, - items: Provider.of(context, listen: false).user.assetGroups.map>((value) { - return DropdownMenuItem( - value: value, - child: Text( - value?.name ?? "", - style: Theme.of(context).textTheme.bodyLarge, - ), - ); - })?.toList(), + items: Provider.of(context, listen: false).user?.assetGroups.map>((value) { + // Added null check and made AssetGroup nullable + return DropdownMenuItem( + value: value, + child: Text( + value?.name ?? "", + style: Theme.of(context).textTheme.bodyLarge, + ), + ); + })?.toList() ?? + [], // Added null check and empty list default ), ); }), @@ -110,18 +114,7 @@ class AppBarWidget extends StatelessWidget { children: [ Icon(Icons.notifications, color: context.isDark ? AppColor.neutral30 : AppColor.neutral20, size: 30).paddingOnly(top: 6, end: 0), // todo @sikander will add count for unread notifications - // Positioned( - // top: 0, - // right: 0, - // child: Container( - // padding: const EdgeInsets.all(4), - // decoration: const ShapeDecoration( - // color: Color(0xFFD02127), - // shape: CircleBorder(), - // ), - // child: Text("", style: AppTextStyles.bodyText), - // ), - // ) + // ... (rest of the code remains the same) ], ).onPress(() { Navigator.of(context).pushNamed(NotificationsPage.id); diff --git a/lib/extensions/context_extension.dart b/lib/extensions/context_extension.dart index 44f1fb9b..536b9154 100644 --- a/lib/extensions/context_extension.dart +++ b/lib/extensions/context_extension.dart @@ -6,7 +6,7 @@ import 'package:provider/provider.dart'; import '../controllers/providers/settings/setting_provider.dart'; extension BuildContextExtension on BuildContext { - AppLocalizations get translation => AppLocalizations.of(this); + AppLocalizations get translation => AppLocalizations.of(this)!; List get getIssues => [translation.reason1, translation.reason2, translation.reason3, translation.reason4, translation.reason5]; diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index fa760b9e..76ff2b66 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -7,13 +7,13 @@ extension StringExtensions on String { void get showToast => Fluttertoast.showToast(msg: this); String get toServiceRequestCardFormat { - DateTime dateTime = DateTime.tryParse(this); + DateTime dateTime = DateTime.parse(this); return "${DateFormat('dd MMM, yyyy').format(dateTime)}\n${DateFormat('hh:mm a').format(dateTime)}"; } String get toServiceRequestDetailsFormat { try { - DateTime dateTime = DateTime.tryParse(this); + DateTime dateTime = DateTime.parse(this); return "${DateFormat('dd MMM, yyyy').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}"; } catch (e) { return ""; @@ -22,7 +22,7 @@ extension StringExtensions on String { String get toFirstActionFormat { try { - DateTime dateTime = DateTime.tryParse(this); + DateTime dateTime = DateTime.parse(this); return "${DateFormat('yyyy-MM-dd').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}"; } catch (e) { return ""; @@ -31,7 +31,7 @@ extension StringExtensions on String { String get toAssetDetailsFormat { try { - DateTime dateTime = DateTime.tryParse(this); + DateTime dateTime = DateTime.parse(this); return DateFormat('dd MMM, yyyy').format(dateTime); } catch (e) { return "-"; diff --git a/lib/extensions/text_extensions.dart b/lib/extensions/text_extensions.dart index 325bded8..9ecd586e 100644 --- a/lib/extensions/text_extensions.dart +++ b/lib/extensions/text_extensions.dart @@ -16,6 +16,7 @@ extension TextStyles on String { Text heading4(BuildContext context) => getTextWithStyle(this, AppTextStyles.heading4, context.isDark ? AppColor.neutral30 : AppColor.neutral50); Text heading5(BuildContext context) => getTextWithStyle(this, AppTextStyles.heading5, context.isDark ? AppColor.neutral30 : AppColor.neutral50); + Text customHeadingText(BuildContext context) => getTextWithStyle(this, AppTextStyles.customHeadingText, context.isDark ? AppColor.neutral30 : AppColor.neutral50); Text heading6(BuildContext context) => getTextWithStyle(this, AppTextStyles.heading6, context.isDark ? AppColor.neutral30 : AppColor.neutral50); @@ -32,11 +33,18 @@ extension TextStyles on String { } extension CustomText on Text { - Text custom({Color color, FontWeight fontWeight, TextAlign align,double fontSize,double lineHeight,double letterSpacing}) { + Text custom({ + Color? color, + FontWeight? fontWeight, + TextAlign? align, + double? fontSize, + double? lineHeight, + double? letterSpacing, + }) { return Text( - data, + data!, textAlign: align, - style: style.copyWith( + style: style?.copyWith( color: color, height: lineHeight, letterSpacing: letterSpacing, @@ -86,12 +94,16 @@ abstract class AppTextStyles { decoration: TextDecoration.none, ); static const TextStyle customHeadingText = TextStyle( - fontFamily: 'Poppins', - fontSize: 27, // Font size in logical pixels - fontWeight: FontWeight.w500, // Equivalent to font-weight: 500 - height: 31 / 27, // Line height (in Flutter, it's a multiplier of font size) - letterSpacing: -0.04 * 27, // Letter spacing, converted to logical pixels - color: Colors.black, // Set your desired text color + fontFamily: 'Poppins', + fontSize: 27, + // Font size in logical pixels + fontWeight: FontWeight.w500, + // Equivalent to font-weight: 500 + height: 31 / 27, + // Line height (in Flutter, it's a multiplier of font size) + letterSpacing: -0.04 * 27, + // Letter spacing, converted to logical pixels + color: Colors.black, // Set your desired text color ); static final TextStyle heading6 = TextStyle( @@ -149,24 +161,24 @@ extension CapExtension on String { extension FilesExtension on String { SvgPicture toSvgAsset({ - int width, - int height, - Color color, + int? width, + int? height, + Color? color, BoxFit fit = BoxFit.contain, }) => SvgPicture.asset("assets/images/$this.svg", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit); Image toPngAsset({ - int width, - int height, - Color color, + int? width, + int? height, + Color? color, BoxFit fit = BoxFit.contain, }) => Image.asset("assets/images/$this.png", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit); LottieBuilder toLottieAsset({ - int width, - int height, + int? width, + int? height, BoxFit fit = BoxFit.contain, bool repeat = true, }) => diff --git a/lib/extensions/widget_extensions.dart b/lib/extensions/widget_extensions.dart index 9d5bb524..34da1f1e 100644 --- a/lib/extensions/widget_extensions.dart +++ b/lib/extensions/widget_extensions.dart @@ -6,7 +6,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import '../new_views/app_style/app_color.dart'; extension WidgetExtensions on Widget { - Widget onPress(VoidCallback onTap) => InkWell(onTap: onTap, child: this, highlightColor: Colors.transparent, splashColor: Colors.transparent); + Widget onPress(VoidCallback? onTap) => InkWell(onTap: onTap, child: this, highlightColor: Colors.transparent, splashColor: Colors.transparent); Widget get expanded => Expanded(child: this); diff --git a/lib/models/all_requests_and_count_model.dart b/lib/models/all_requests_and_count_model.dart index 62032ca6..64715e46 100644 --- a/lib/models/all_requests_and_count_model.dart +++ b/lib/models/all_requests_and_count_model.dart @@ -1,15 +1,23 @@ import 'dart:convert'; class AllRequestsAndCount { - CountServiceRequest countServiceRequest; - CountServiceRequest countGasRefill; - CountServiceRequest countAssetTransfer; - CountServiceRequest countPPM; - DetailsStatusTotal detailsStatusTotal; - CountServiceRequest total; - List requestsDetails; - - AllRequestsAndCount({this.countServiceRequest, this.countGasRefill, this.countAssetTransfer, this.countPPM, this.detailsStatusTotal, this.total, this.requestsDetails}); + CountServiceRequest? countServiceRequest; + CountServiceRequest? countGasRefill; + CountServiceRequest? countAssetTransfer; + CountServiceRequest? countPPM; + DetailsStatusTotal? detailsStatusTotal; + CountServiceRequest? total; + List? requestsDetails; + + AllRequestsAndCount({ + this.countServiceRequest, + this.countGasRefill, + this.countAssetTransfer, + this.countPPM, + this.detailsStatusTotal, + this.total, + this.requestsDetails, + }); AllRequestsAndCount.fromJson(Map json) { countServiceRequest = json['countServiceRequest'] != null ? CountServiceRequest.fromJson(json['countServiceRequest']) : null; @@ -21,7 +29,7 @@ class AllRequestsAndCount { if (json['requestsDetails'] != null) { requestsDetails = []; json['requestsDetails'].forEach((v) { - requestsDetails.add(RequestsDetails.fromJson(v)); + requestsDetails!.add(RequestsDetails.fromJson(v)); }); } } @@ -29,34 +37,32 @@ class AllRequestsAndCount { Map toJson() { final Map data = {}; if (countServiceRequest != null) { - data['countServiceRequest'] = countServiceRequest.toJson(); + data['countServiceRequest'] = countServiceRequest!.toJson(); } - if (countGasRefill != null) { - data['countGasRefill'] = countGasRefill.toJson(); + data['countGasRefill'] = countGasRefill!.toJson(); } if (countAssetTransfer != null) { - data['countAssetTransfer'] = countAssetTransfer.toJson(); + data['countAssetTransfer'] = countAssetTransfer!.toJson(); } if (countPPM != null) { - data['countPPM'] = countPPM.toJson(); + data['countPPM'] = countPPM!.toJson(); } - if (detailsStatusTotal != null) { - data['detailsStatusTotal'] = detailsStatusTotal.toJson(); + data['detailsStatusTotal'] = detailsStatusTotal!.toJson(); } if (total != null) { - data['total'] = total.toJson(); + data['total'] = total!.toJson(); } if (requestsDetails != null) { - data['requestsDetails'] = requestsDetails.map((v) => v.toJson()).toList(); + data['requestsDetails'] = requestsDetails!.map((v) => v.toJson()).toList(); } return data; } } class CountServiceRequest { - int count; + int? count; CountServiceRequest({this.count}); @@ -72,9 +78,9 @@ class CountServiceRequest { } class DetailsStatusTotal { - int open; - int inProgress; - int closed; + int? open; + int? inProgress; + int? closed; DetailsStatusTotal({this.open, this.inProgress, this.closed}); @@ -94,50 +100,51 @@ class DetailsStatusTotal { } class RequestsDetails { - int id; - String nameOfType; - String priority; - String status; - String assetName; - String assetNo; - String assetSN; - String model; - String supplier; - String manufacturer; - String requestType; - String requestNo; - String gasType; - String site; - String statusReceiver; - String assetTransferFrom; - String assetTransferTo; - String code; - String date; - String siteTransferFrom; - String siteTransferTo; - - RequestsDetails( - {this.id, - this.nameOfType, - this.priority, - this.status, - this.assetName, - this.assetNo, - this.assetSN, - this.model, - this.supplier, - this.manufacturer, - this.requestType, - this.requestNo, - this.gasType, - this.site, - this.statusReceiver, - this.assetTransferFrom, - this.assetTransferTo, - this.code, - this.siteTransferFrom, - this.siteTransferTo, - this.date}); + int? id; + String? nameOfType; + String? priority; + String? status; + String? assetName; + String? assetNo; + String? assetSN; + String? model; + String? supplier; + String? manufacturer; + String? requestType; + String? requestNo; + String? gasType; + String? site; + String? statusReceiver; + String? assetTransferFrom; + String? assetTransferTo; + String? code; + String? date; + String? siteTransferFrom; + String? siteTransferTo; + + RequestsDetails({ + this.id, + this.nameOfType, + this.priority, + this.status, + this.assetName, + this.assetNo, + this.assetSN, + this.model, + this.supplier, + this.manufacturer, + this.requestType, + this.requestNo, + this.gasType, + this.site, + this.statusReceiver, + this.assetTransferFrom, + this.assetTransferTo, + this.code, + this.siteTransferFrom, + this.siteTransferTo, + this.date, + }); RequestsDetails.fromJson(Map json) { id = json['id']; @@ -190,12 +197,11 @@ class RequestsDetails { } } - class RequestQueryModel { - List typeTransaction; - List statusTransaction; - List priority; - List displayData; + List? typeTransaction; + List? statusTransaction; + List? priority; + List? displayData; int pageNumber; int pageSize; bool showLoader; @@ -205,24 +211,23 @@ class RequestQueryModel { this.statusTransaction, this.priority, this.displayData, - this.pageNumber=1, - this.pageSize=10, + this.pageNumber = 1, + this.pageSize = 10, this.showLoader = true, }); - // Factory method to create an instance from a JSON map factory RequestQueryModel.fromJson(Map json) { return RequestQueryModel( typeTransaction: List.from(json['typeTransaction']), statusTransaction: List.from(json['statusTransaction']), priority: List.from(json['priority']), displayData: List.from(json['displayData']), - pageNumber: json['pageNumber'], - pageSize: json['pageSize'], + pageNumber: json['pageNumber'] ?? 1, + pageSize: json['pageSize'] ?? 10, + showLoader: json['showLoader'] ?? true, ); } - // Method to convert an instance to a JSON map Map toJson() { return { 'typeTransaction': typeTransaction, @@ -231,14 +236,11 @@ class RequestQueryModel { 'displayData': displayData, 'pageNumber': pageNumber, 'pageSize': pageSize, + 'showLoader': showLoader, }; } - // Method to encode the model to a JSON string String encodeToJson() => json.encode(toJson()); - // Method to decode the model from a JSON string - static RequestQueryModel decodeFromJson(String jsonString) => - RequestQueryModel.fromJson(json.decode(jsonString)); + static RequestQueryModel decodeFromJson(String jsonString) => RequestQueryModel.fromJson(json.decode(jsonString)); } - diff --git a/lib/models/base.dart b/lib/models/base.dart index 02b2cea5..93f4168c 100644 --- a/lib/models/base.dart +++ b/lib/models/base.dart @@ -1,5 +1,5 @@ class Base { - String name, identifier; + String? name, identifier; Base({this.name, this.identifier}); } diff --git a/lib/models/comment.dart b/lib/models/comment.dart index 63cd4732..e0fc0f51 100644 --- a/lib/models/comment.dart +++ b/lib/models/comment.dart @@ -10,23 +10,23 @@ class Comment { Comment.fromJson(dynamic json) { id = json['id']; callRequestId = json['callRequestId']; - createdOn = json['createdOn']; + createdOn = json['createdOn'] ?? ''; createdBy = json['createdBy'] != null ? CreatedBy.fromJson(json['createdBy']) : null; - comment = json['comment']; + comment = json['comment'] ?? ''; } - num id; - num callRequestId; - String createdOn; - CreatedBy createdBy; - String comment; + num? id; + num? callRequestId; + String? createdOn; + CreatedBy? createdBy; + String? comment; Comment copyWith({ - num id, - num callRequestId, - String createdOn, - CreatedBy createdBy, - String comment, + num? id, + num? callRequestId, + String? createdOn, + CreatedBy? createdBy, + String? comment, }) => Comment( id: id ?? this.id, @@ -42,7 +42,7 @@ class Comment { map['callRequestId'] = callRequestId; map['createdOn'] = createdOn; if (createdBy != null) { - map['createdBy'] = createdBy.toJson(); + map['createdBy'] = createdBy?.toJson(); } map['comment'] = comment; return map; @@ -56,16 +56,16 @@ class CreatedBy { }); CreatedBy.fromJson(dynamic json) { - userId = json['userId']; - userName = json['userName']; + userId = json['userId'] ?? ''; + userName = json['userName'] ?? ''; } - String userId; - String userName; + String? userId; + String? userName; CreatedBy copyWith({ - String userId, - String userName, + String? userId, + String? userName, }) => CreatedBy( userId: userId ?? this.userId, diff --git a/lib/models/department.dart b/lib/models/department.dart index 1aa28994..bc087d79 100644 --- a/lib/models/department.dart +++ b/lib/models/department.dart @@ -1,6 +1,6 @@ class Department { - int id; - String name; + int? id; + String? name; Department({ this.id, @@ -14,7 +14,7 @@ class Department { ); } - factory Department.fromDepartment(Department department) { + factory Department.fromDepartment(Department? department) { return Department( id: department?.id, name: department?.name, diff --git a/lib/models/device/asset.dart b/lib/models/device/asset.dart index 56c4ce90..b4b7b952 100644 --- a/lib/models/device/asset.dart +++ b/lib/models/device/asset.dart @@ -111,7 +111,7 @@ class Asset { if (json['technicalGuidanceBooks'] != null) { technicalGuidanceBooks = []; json['technicalGuidanceBooks'].forEach((v) { - technicalGuidanceBooks.add(TechnicalGuidanceBook.fromJson(v)); + technicalGuidanceBooks!.add(TechnicalGuidanceBook.fromJson(v)); // Use '!' since technicalGuidanceBooks is initialized here }); } comment = json['comment']; @@ -119,107 +119,106 @@ class Asset { assetPhoto = json['assetPhoto']; } - num id; - String assetSerialNo; - String systemID; - String assetNumber; - ModelDefinition modelDefinition; - Supplier supplier; - String ipAddress; - String macAddress; - String portNumber; - Lookup assetReplace; - AssetInfo oldAsset; - Lookup isParent; - AssetInfo parentAsset; - Lookup assetType; - Site site; - Building building; - Floor floor; - Department department; - Rooms room; - // String room; - num testsDay; - num purchasingPrice; - String nbv; - Lookup currency; - String poNo; - String invoiceNumber; - String invoiceDate; - String replacementDate; - Department originDepartment; - Site originSite; - num budgetYear; - num lastPOPrice; - Lookup commissioningStatus; - String productionDate; - String edd; - String technicalInspectionDate; - String deliveryInspectionDate; - String endUserAcceptanceDate; - String receivingCommittee; - Lookup siteWarrantyMonths; - Lookup extendedWarrantyMonths; - Lookup remainderWarrantyMonths; - num eomWarrantyMonthsNo; - num warrantyValue; - String warrantyEndDate; - String warrantyContractConditions; - List technicalGuidanceBooks; - String comment; - String tagCode; - String assetPhoto; + num? id; // Now nullable + String? assetSerialNo; // Now nullable + String? systemID; // Now nullable + String? assetNumber; // Now nullable + ModelDefinition? modelDefinition; // Now nullable + Supplier? supplier; // Now nullable + String? ipAddress; // Now nullable + String? macAddress; // Now nullable + String? portNumber; // Now nullable + Lookup? assetReplace; // Now nullable + AssetInfo? oldAsset; // Now nullable + Lookup? isParent; // Now nullable + AssetInfo? parentAsset; // Now nullable + Lookup? assetType; // Now nullable + Site? site; // Now nullable + Building? building; // Now nullable + Floor? floor; // Now nullable + Department? department; // Now nullable + Rooms? room; // Now nullable + num? testsDay; // Now nullable + num? purchasingPrice; // Now nullable + String? nbv; // Now nullable + Lookup? currency; // Now nullable + String? poNo; // Now nullable + String? invoiceNumber; // Now nullable + String? invoiceDate; // Now nullable + String? replacementDate; // Now nullable + Department? originDepartment; // Now nullable + Site? originSite; // Now nullable + num? budgetYear; // Now nullable + num? lastPOPrice; // Now nullable + Lookup? commissioningStatus; // Now nullable + String? productionDate; // Now nullable + String? edd; // Now nullable + String? technicalInspectionDate; // Now nullable + String? deliveryInspectionDate; // Now nullable + String? endUserAcceptanceDate; // Now nullable + String? receivingCommittee; // Now nullable + Lookup? siteWarrantyMonths; // Now nullable + Lookup? extendedWarrantyMonths; // Now nullable + Lookup? remainderWarrantyMonths; // Now nullable + num? eomWarrantyMonthsNo; // Now nullable + num? warrantyValue; // Now nullable + String? warrantyEndDate; // Now nullable + String? warrantyContractConditions; // Now nullable + List? technicalGuidanceBooks; // Now nullable + String? comment; // Now nullable + String? tagCode; // Now nullable + String? assetPhoto; Asset copyWith({ - num id, - String assetSerialNo, - String systemID, - String assetNumber, - ModelDefinition modelDefinition, - Supplier supplier, - String ipAddress, - String macAddress, - String portNumber, - Lookup assetReplace, - AssetInfo oldAsset, - Lookup isParent, - AssetInfo parentAsset, - Lookup assetType, - Site site, - Building building, - Floor floor, - Department department, - Rooms room, - num testsDay, - num purchasingPrice, - String nbv, - Lookup currency, - String poNo, - String invoiceNumber, - String invoiceDate, - String replacementDate, - Department originDepartment, - Site originSite, - num budgetYear, - num lastPOPrice, - Lookup commissioningStatus, - String productionDate, - String edd, - String technicalInspectionDate, - String deliveryInspectionDate, - String endUserAcceptanceDate, - String receivingCommittee, - Lookup siteWarrantyMonths, - Lookup extendedWarrantyMonths, - Lookup remainderWarrantyMonths, - num eomWarrantyMonthsNo, - num warrantyValue, - String warrantyEndDate, - String warrantyContractConditions, - List technicalGuidanceBooks, - String comment, - String tagCode, - String assetPhoto, + num? id, + String? assetSerialNo, + String? systemID, + String? assetNumber, + ModelDefinition? modelDefinition, + Supplier? supplier, + String? ipAddress, + String? macAddress, + String? portNumber, + Lookup? assetReplace, + AssetInfo? oldAsset, + Lookup? isParent, + AssetInfo? parentAsset, + Lookup? assetType, + Site? site, + Building? building, + Floor? floor, + Department? department, + Rooms? room, + num? testsDay, + num? purchasingPrice, + String? nbv, + Lookup? currency, + String? poNo, + String? invoiceNumber, + String? invoiceDate, + String? replacementDate, + Department? originDepartment, + Site? originSite, + num? budgetYear, + num? lastPOPrice, + Lookup? commissioningStatus, + String? productionDate, + String? edd, + String? technicalInspectionDate, + String? deliveryInspectionDate, + String? endUserAcceptanceDate, + String? receivingCommittee, + Lookup? siteWarrantyMonths, + Lookup? extendedWarrantyMonths, + Lookup? remainderWarrantyMonths, + num? eomWarrantyMonthsNo, + num? warrantyValue, + String? warrantyEndDate, + String? warrantyContractConditions, + List? technicalGuidanceBooks, + String? comment, + String? tagCode, + String? assetPhoto, }) => Asset( id: id ?? this.id, @@ -280,65 +279,65 @@ class Asset { map['systemID'] = systemID; map['assetNumber'] = assetNumber; if (modelDefinition != null) { - map['modelDefinition'] = modelDefinition.toJson(); + map['modelDefinition'] = modelDefinition!.toJson(); } if (supplier != null) { - map['supplier'] = supplier.toJson(); + map['supplier'] = supplier!.toJson(); } map['ipAddress'] = ipAddress; map['macAddress'] = macAddress; map['portNumber'] = portNumber; if (assetReplace != null) { - map['assetReplace'] = assetReplace.toJson(); + map['assetReplace'] = assetReplace!.toJson(); } if (oldAsset != null) { - map['oldAsset'] = oldAsset.toJson(); + map['oldAsset'] = oldAsset!.toJson(); } if (isParent != null) { - map['isParent'] = isParent.toJson(); + map['isParent'] = isParent!.toJson(); } if (parentAsset != null) { - map['parentAsset'] = parentAsset.toJson(); + map['parentAsset'] = parentAsset!.toJson(); } if (assetType != null) { - map['assetType'] = assetType.toJson(); + map['assetType'] = assetType!.toJson(); } if (site != null) { - map['site'] = site.toJson(); + map['site'] = site!.toJson(); } if (building != null) { - map['building'] = building.toJson(); + map['building'] = building!.toJson(); } if (floor != null) { - map['floor'] = floor.toJson(); + map['floor'] = floor!.toJson(); } if (department != null) { - map['department'] = department.toJson(); + map['department'] = department!.toJson(); } // map['room'] = room; if (room != null) { - map['room'] = room.toJson(); + map['room'] = room!.toJson(); } map['testsDay'] = testsDay; map['purchasingPrice'] = purchasingPrice; map['nbv'] = nbv; if (currency != null) { - map['currency'] = currency.toJson(); + map['currency'] = currency!.toJson(); } map['poNo'] = poNo; map['invoiceNumber'] = invoiceNumber; map['invoiceDate'] = invoiceDate; map['replacementDate'] = replacementDate; if (originDepartment != null) { - map['originDepartment'] = originDepartment.toJson(); + map['originDepartment'] = originDepartment!.toJson(); } if (originSite != null) { - map['originSite'] = originSite.toJson(); + map['originSite'] = originSite!.toJson(); } map['budgetYear'] = budgetYear; map['lastPOPrice'] = lastPOPrice; if (commissioningStatus != null) { - map['commissioningStatus'] = commissioningStatus.toJson(); + map['commissioningStatus'] = commissioningStatus!.toJson(); } map['productionDate'] = productionDate; map['edd'] = edd; @@ -347,20 +346,20 @@ class Asset { map['endUserAcceptanceDate'] = endUserAcceptanceDate; map['receivingCommittee'] = receivingCommittee; if (siteWarrantyMonths != null) { - map['siteWarrantyMonths'] = siteWarrantyMonths.toJson(); + map['siteWarrantyMonths'] = siteWarrantyMonths!.toJson(); } if (extendedWarrantyMonths != null) { - map['extendedWarrantyMonths'] = extendedWarrantyMonths.toJson(); + map['extendedWarrantyMonths'] = extendedWarrantyMonths!.toJson(); } if (remainderWarrantyMonths != null) { - map['remainderWarrantyMonths'] = remainderWarrantyMonths.toJson(); + map['remainderWarrantyMonths'] = remainderWarrantyMonths!.toJson(); } map['eomWarrantyMonthsNo'] = eomWarrantyMonthsNo; map['warrantyValue'] = warrantyValue; map['warrantyEndDate'] = warrantyEndDate; map['warrantyContractConditions'] = warrantyContractConditions; if (technicalGuidanceBooks != null) { - map['technicalGuidanceBooks'] = technicalGuidanceBooks.map((v) => v.toJson()).toList(); + map['technicalGuidanceBooks'] = technicalGuidanceBooks!.map((v) => v.toJson()).toList(); } map['comment'] = comment; map['tagCode'] = tagCode; @@ -388,20 +387,20 @@ class AssetInfo { assetName = json['assetName']; } - num id; - String assetSerialNo; - String assetNumber; - String tagCode; - String systemId; - String assetName; + num? id; // Now nullable + String? assetSerialNo; // Now nullable + String? assetNumber; // Now nullable + String? tagCode; // Now nullable + String? systemId; // Now nullable + String? assetName; // Now nullable AssetInfo copyWith({ - num id, - String assetSerialNo, - String assetNumber, - String tagCode, - String systemId, - String assetName, + num? id, // Parameters are now nullable + String? assetSerialNo, + String? assetNumber, + String? tagCode, + String? systemId, + String? assetName, }) => AssetInfo( id: id ?? this.id, diff --git a/lib/models/device/asset_search.dart b/lib/models/device/asset_search.dart index 3bf6c185..d186c6f9 100644 --- a/lib/models/device/asset_search.dart +++ b/lib/models/device/asset_search.dart @@ -1,36 +1,35 @@ import 'package:test_sa/models/lookup.dart'; class AssetSearch { - AssetSearch({ - this.code, - this.assetSerialNumber, - this.assetName, - this.supplyDateSymbol, - this.supplyDateFrom, - this.supplyDateTo, - this.warrantyEndDateSymbol, - this.warrantyEndDateFrom, - this.warrantyEndDateTo, - this.delieveryInspectionDateSymbol, - this.deliveryInspectionDateFrom, - this.deliveryInspectionDateTo, - this.maintenanceContract, - this.assetClassification, - this.assetStatus, - this.assetNotScraped, - this.assetNo, - this.modelDefinition, - this.site, - this.manufacturer, - this.model, - this.department, - this.supplier, - this.tagCode, - this.assetGroupName, - this.assetGroup, - this.oracleCodeTypeId, - this.oracleCodeValue - }); + AssetSearch( + {this.code, + this.assetSerialNumber, + this.assetName, + this.supplyDateSymbol, + this.supplyDateFrom, + this.supplyDateTo, + this.warrantyEndDateSymbol, + this.warrantyEndDateFrom, + this.warrantyEndDateTo, + this.delieveryInspectionDateSymbol, + this.deliveryInspectionDateFrom, + this.deliveryInspectionDateTo, + this.maintenanceContract, + this.assetClassification, + this.assetStatus, + this.assetNotScraped, + this.assetNo, + this.modelDefinition, + this.site, + this.manufacturer, + this.model, + this.department, + this.supplier, + this.tagCode, + this.assetGroupName, + this.assetGroup, + this.oracleCodeTypeId, + this.oracleCodeValue}); AssetSearch.fromJson(dynamic json) { code = json['code']; @@ -59,141 +58,139 @@ class AssetSearch { tagCode = json['tagCode']; assetGroupName = json['assetGroupName']; assetGroup = json['assetGroup'] != null ? Lookup.fromJson(json['assetGroup']) : null; - oracleCodeTypeId=json['assetOracleCodeTypeId']; - oracleCodeValue=json['assetOracleCodeValue']; + oracleCodeTypeId = json['assetOracleCodeTypeId']; + oracleCodeValue = json['assetOracleCodeValue']; } - String code; - String assetSerialNumber; - String assetName; - Lookup supplyDateSymbol; - String supplyDateFrom; - String supplyDateTo; - num warrantyEndDateSymbol; - String warrantyEndDateFrom; - String warrantyEndDateTo; - num delieveryInspectionDateSymbol; - String deliveryInspectionDateFrom; - String deliveryInspectionDateTo; - Lookup maintenanceContract; - Lookup assetClassification; - Lookup assetStatus; - Lookup assetNotScraped; - String assetNo; - String modelDefinition; - String site; - String manufacturer; - String model; - String department; - String supplier; - String tagCode; - String assetGroupName; - Lookup assetGroup; - String oracleCodeValue; - int oracleCodeTypeId; + String? code; // Now nullable + String? assetSerialNumber; // Now nullable + String? assetName; // Now nullable + Lookup? supplyDateSymbol; // Now nullable + String? supplyDateFrom; // Now nullable + String? supplyDateTo; // Now nullable + num? warrantyEndDateSymbol; // Now nullable + String? warrantyEndDateFrom; // Now nullable + String? warrantyEndDateTo; // Now nullable + num? delieveryInspectionDateSymbol; // Now nullable + String? deliveryInspectionDateFrom; // Now nullable + String? deliveryInspectionDateTo; // Now nullable + Lookup? maintenanceContract; // Now nullable + Lookup? assetClassification; // Now nullable + Lookup? assetStatus; // Now nullable + Lookup? assetNotScraped; // Now nullable + String? assetNo; // Now nullable + String? modelDefinition; // Now nullable + String? site; // Now nullable + String? manufacturer; // Now nullable + String? model; // Now nullable + String? department; // Now nullable + String? supplier; // Now nullable + String? tagCode; // Now nullable + String? assetGroupName; // Now nullable + Lookup? assetGroup; // Now nullable + String? oracleCodeValue; // Now nullable + int? oracleCodeTypeId; - AssetSearch copyWith({ - String code, - String assetSerialNumber, - String assetName, - Lookup supplyDateSymbol, - String supplyDateFrom, - String supplyDateTo, - num warrantyEndDateSymbol, - String warrantyEndDateFrom, - String warrantyEndDateTo, - num delieveryInspectionDateSymbol, - String deliveryInspectionDateFrom, - String deliveryInspectionDateTo, - Lookup maintenanceContract, - Lookup assetClassification, - Lookup assetStatus, - Lookup assetNotScraped, - String assetNo, - String modelDefinition, - String site, - String manufacturer, - String model, - String department, - String supplier, - String tagCode, - String assetGroupName, - Lookup assetGroup, - String oracleCodeValue, - int oracleCodeTypeId - }) => + AssetSearch copyWith( + {String? code, + String? assetSerialNumber, + String? assetName, + Lookup? supplyDateSymbol, + String? supplyDateFrom, + String? supplyDateTo, + num? warrantyEndDateSymbol, + String? warrantyEndDateFrom, + String? warrantyEndDateTo, + num? delieveryInspectionDateSymbol, + String? deliveryInspectionDateFrom, + String? deliveryInspectionDateTo, + Lookup? maintenanceContract, + Lookup? assetClassification, + Lookup? assetStatus, + Lookup? assetNotScraped, + String? assetNo, + String? modelDefinition, + String? site, + String? manufacturer, + String? model, + String? department, + String? supplier, + String? tagCode, + String? assetGroupName, + Lookup? assetGroup, + String? oracleCodeValue, + int? oracleCodeTypeId}) => AssetSearch( - code: code ?? this.code, - assetSerialNumber: assetSerialNumber ?? this.assetSerialNumber, - assetName: assetName ?? this.assetName, - supplyDateSymbol: supplyDateSymbol ?? this.supplyDateSymbol, - supplyDateFrom: supplyDateFrom ?? this.supplyDateFrom, - supplyDateTo: supplyDateTo ?? this.supplyDateTo, - warrantyEndDateSymbol: warrantyEndDateSymbol ?? this.warrantyEndDateSymbol, - warrantyEndDateFrom: warrantyEndDateFrom ?? this.warrantyEndDateFrom, - warrantyEndDateTo: warrantyEndDateTo ?? this.warrantyEndDateTo, - delieveryInspectionDateSymbol: delieveryInspectionDateSymbol ?? this.delieveryInspectionDateSymbol, - deliveryInspectionDateFrom: deliveryInspectionDateFrom ?? this.deliveryInspectionDateFrom, - deliveryInspectionDateTo: deliveryInspectionDateTo ?? this.deliveryInspectionDateTo, - maintenanceContract: maintenanceContract ?? this.maintenanceContract, - assetClassification: assetClassification ?? this.assetClassification, - assetStatus: assetStatus ?? this.assetStatus, - assetNotScraped: assetNotScraped ?? this.assetNotScraped, - assetNo: assetNo ?? this.assetNo, - modelDefinition: modelDefinition ?? this.modelDefinition, - site: site ?? this.site, - manufacturer: manufacturer ?? this.manufacturer, - model: model ?? this.model, - department: department ?? this.department, - supplier: supplier ?? this.supplier, - tagCode: tagCode ?? this.tagCode, - assetGroupName: assetGroupName ?? this.assetGroupName, - assetGroup: assetGroup ?? this.assetGroup, - oracleCodeValue: oracleCodeValue ?? this.oracleCodeValue, - oracleCodeTypeId: oracleCodeTypeId ?? this.oracleCodeTypeId - ); + code: code ?? this.code, + assetSerialNumber: assetSerialNumber ?? this.assetSerialNumber, + assetName: assetName ?? this.assetName, + supplyDateSymbol: supplyDateSymbol ?? this.supplyDateSymbol, + supplyDateFrom: supplyDateFrom ?? this.supplyDateFrom, + supplyDateTo: supplyDateTo ?? this.supplyDateTo, + warrantyEndDateSymbol: warrantyEndDateSymbol ?? this.warrantyEndDateSymbol, + warrantyEndDateFrom: warrantyEndDateFrom ?? this.warrantyEndDateFrom, + warrantyEndDateTo: warrantyEndDateTo ?? this.warrantyEndDateTo, + delieveryInspectionDateSymbol: delieveryInspectionDateSymbol ?? this.delieveryInspectionDateSymbol, + deliveryInspectionDateFrom: deliveryInspectionDateFrom ?? this.deliveryInspectionDateFrom, + deliveryInspectionDateTo: deliveryInspectionDateTo ?? this.deliveryInspectionDateTo, + maintenanceContract: maintenanceContract ?? this.maintenanceContract, + assetClassification: assetClassification ?? this.assetClassification, + assetStatus: assetStatus ?? this.assetStatus, + assetNotScraped: assetNotScraped ?? this.assetNotScraped, + assetNo: assetNo ?? this.assetNo, + modelDefinition: modelDefinition ?? this.modelDefinition, + site: site ?? this.site, + manufacturer: manufacturer ?? this.manufacturer, + model: model ?? this.model, + department: department ?? this.department, + supplier: supplier ?? this.supplier, + tagCode: tagCode ?? this.tagCode, + assetGroupName: assetGroupName ?? this.assetGroupName, + assetGroup: assetGroup ?? this.assetGroup, + oracleCodeValue: oracleCodeValue ?? this.oracleCodeValue, + oracleCodeTypeId: oracleCodeTypeId ?? this.oracleCodeTypeId); Map toJson() { final map = {}; - if (code != null && code.isNotEmpty) map['code'] = code; - if (assetSerialNumber != null && assetSerialNumber.isNotEmpty) map['assetSerialNumber'] = assetSerialNumber; - if (assetName != null && assetName.isNotEmpty) map['assetName'] = assetName; + if (code != null && code!.isNotEmpty) map['code'] = code; + if (assetSerialNumber != null && assetSerialNumber!.isNotEmpty) map['assetSerialNumber'] = assetSerialNumber; + if (assetName != null && assetName!.isNotEmpty) map['assetName'] = assetName; if (supplyDateSymbol != null) { - map['supplyDateSymbol'] = supplyDateSymbol.toJson(); + map['supplyDateSymbol'] = supplyDateSymbol!.toJson(); } - if (supplyDateFrom != null && supplyDateFrom.isNotEmpty) map['supplyDateFrom'] = supplyDateFrom; - if (supplyDateTo != null && supplyDateTo.isNotEmpty) map['supplyDateTo'] = supplyDateTo; + if (supplyDateFrom != null && supplyDateFrom!.isNotEmpty) map['supplyDateFrom'] = supplyDateFrom; + if (supplyDateTo != null && supplyDateTo!.isNotEmpty) map['supplyDateTo'] = supplyDateTo; if (warrantyEndDateSymbol != null) map['warrantyEndDateSymbol'] = warrantyEndDateSymbol; - if (warrantyEndDateFrom != null && warrantyEndDateFrom.isNotEmpty) map['warrantyEndDateFrom'] = warrantyEndDateFrom; - if (warrantyEndDateTo != null && warrantyEndDateTo.isNotEmpty) map['warrantyEndDateTo'] = warrantyEndDateTo; + if (warrantyEndDateFrom != null && warrantyEndDateFrom!.isNotEmpty) map['warrantyEndDateFrom'] = warrantyEndDateFrom; + if (warrantyEndDateTo != null && warrantyEndDateTo!.isNotEmpty) map['warrantyEndDateTo'] = warrantyEndDateTo; if (delieveryInspectionDateSymbol != null) map['delieveryInspectionDateSymbol'] = delieveryInspectionDateSymbol; - if (deliveryInspectionDateFrom != null && deliveryInspectionDateFrom.isNotEmpty) map['deliveryInspectionDateFrom'] = deliveryInspectionDateFrom; - if (deliveryInspectionDateTo != null && deliveryInspectionDateTo.isNotEmpty) map['deliveryInspectionDateTo'] = deliveryInspectionDateTo; + if (deliveryInspectionDateFrom != null && deliveryInspectionDateFrom!.isNotEmpty) map['deliveryInspectionDateFrom'] = deliveryInspectionDateFrom; + if (deliveryInspectionDateTo != null && deliveryInspectionDateTo!.isNotEmpty) map['deliveryInspectionDateTo'] = deliveryInspectionDateTo; if (maintenanceContract != null) { - map['maintenanceContract'] = maintenanceContract.toJson(); + map['maintenanceContract'] = maintenanceContract!.toJson(); } if (assetClassification != null) { - map['assetClassification'] = assetClassification.toJson(); + map['assetClassification'] = assetClassification!.toJson(); } if (assetStatus != null) { - map['assetStatus'] = assetStatus.toJson(); + map['assetStatus'] = assetStatus!.toJson(); } if (assetNotScraped != null) { - map['assetNotScraped'] = assetNotScraped.toJson(); + map['assetNotScraped'] = assetNotScraped!.toJson(); } - if (assetNo != null && assetNo.isNotEmpty) map['assetNo'] = assetNo; - if (modelDefinition != null && modelDefinition.isNotEmpty) map['modelDefinition'] = modelDefinition; - if (site != null && site.isNotEmpty) map['site'] = site; - if (manufacturer != null && manufacturer.isNotEmpty) map['manufacturer'] = manufacturer; - if (model != null && model.isNotEmpty) map['model'] = model; - if (department != null && department.isNotEmpty) map['department'] = department; - if (supplier != null && supplier.isNotEmpty) map['supplier'] = supplier; - if (tagCode != null && tagCode.isNotEmpty) map['tagCode'] = tagCode; - if (assetGroupName != null && assetGroupName.isNotEmpty) map['assetGroupName'] = assetGroupName; + if (assetNo != null && assetNo!.isNotEmpty) map['assetNo'] = assetNo; + if (modelDefinition != null && modelDefinition!.isNotEmpty) map['modelDefinition'] = modelDefinition; + if (site != null && site!.isNotEmpty) map['site'] = site; + if (manufacturer != null && manufacturer!.isNotEmpty) map['manufacturer'] = manufacturer; + if (model != null && model!.isNotEmpty) map['model'] = model; + if (department != null && department!.isNotEmpty) map['department'] = department; + if (supplier != null && supplier!.isNotEmpty) map['supplier'] = supplier; + if (tagCode != null && tagCode!.isNotEmpty) map['tagCode'] = tagCode; + if (assetGroupName != null && assetGroupName!.isNotEmpty) map['assetGroupName'] = assetGroupName; if (assetGroup != null) { - map['assetGroup'] = assetGroup.toJson(); + map['assetGroup'] = assetGroup!.toJson(); } - if (oracleCodeValue != null && oracleCodeValue.isNotEmpty) map['assetOracleCodeValue'] = oracleCodeValue; + if (oracleCodeValue != null && oracleCodeValue!.isNotEmpty) map['assetOracleCodeValue'] = oracleCodeValue; if (oracleCodeTypeId != null) map['assetOracleCodeTypeId'] = oracleCodeTypeId; return map; } diff --git a/lib/models/device/asset_transfer_attachment.dart b/lib/models/device/asset_transfer_attachment.dart index e22aab00..7aed25f8 100644 --- a/lib/models/device/asset_transfer_attachment.dart +++ b/lib/models/device/asset_transfer_attachment.dart @@ -9,12 +9,12 @@ class AssetTransferAttachment { attachmentName = json['attachmentName']; } - num id; - String attachmentName; + num? id; // Now nullable + String? attachmentName; // Now nullable AssetTransferAttachment copyWith({ - num id, - String attachmentName, + num? id, // Parameter is now nullable + String? attachmentName, // Parameter is now nullable }) => AssetTransferAttachment( id: id ?? this.id, diff --git a/lib/models/device/model_definition.dart b/lib/models/device/model_definition.dart index 9ed23e57..a19a7a18 100644 --- a/lib/models/device/model_definition.dart +++ b/lib/models/device/model_definition.dart @@ -34,84 +34,44 @@ class ModelDefinition { if (json['modelDefRelatedDefects'] != null) { modelDefRelatedDefects = []; json['modelDefRelatedDefects'].forEach((v) { - modelDefRelatedDefects.add(ModelDefRelatedDefects.fromJson(v)); + modelDefRelatedDefects!.add(ModelDefRelatedDefects.fromJson(v)); // Use '!' since modelDefRelatedDefects is initialized here }); } if (json['suppliers'] != null) { suppliers = []; json['suppliers'].forEach((v) { - suppliers.add(Supplier.fromJson(v)); + suppliers!.add(Supplier.fromJson(v)); // Use '!' since suppliers is initialized here }); } } - num id; - String assetName; - String assetDescription; - String modelDefCode; - String modelName; - num manufacturerId; - String manufacturerName; - dynamic supplierName; - String replacementDate; - String essentialEquipement; - String businessCritical; - num lifeSpan; - List modelDefRelatedDefects; - List suppliers; + num? id; // Now nullable + String? assetName; // Now nullable + String? assetDescription; // Now nullable + String? modelDefCode; // Now nullable + String? modelName; // Now nullable + num? manufacturerId; // Now nullable + String? manufacturerName; // Now nullable + String? supplierName; // Remains dynamic asit can hold various types + String? replacementDate; // Now nullable + String? essentialEquipement; // Now nullable + String? businessCritical; // Now nullable + num? lifeSpan; // Now nullable + List? modelDefRelatedDefects; // Now nullable + List? suppliers; // Now nullable - ModelDefinition copyWith({ - num id, - String assetName, - String assetDescription, - String modelDefCode, - String modelName, - num manufacturerId, - String manufacturerName, - dynamic supplierName, - String replacementDate, - String essentialEquipement, - String businessCritical, - num lifeSpan, - List modelDefRelatedDefects, - List suppliers, - }) => - ModelDefinition( - id: id ?? this.id, - assetName: assetName ?? this.assetName, - assetDescription: assetDescription ?? this.assetDescription, - modelDefCode: modelDefCode ?? this.modelDefCode, - modelName: modelName ?? this.modelName, - manufacturerId: manufacturerId ?? this.manufacturerId, - manufacturerName: manufacturerName ?? this.manufacturerName, - supplierName: supplierName ?? this.supplierName, - replacementDate: replacementDate ?? this.replacementDate, - essentialEquipement: essentialEquipement ?? this.essentialEquipement, - businessCritical: businessCritical ?? this.businessCritical, - lifeSpan: lifeSpan ?? this.lifeSpan, - modelDefRelatedDefects: modelDefRelatedDefects ?? this.modelDefRelatedDefects, - suppliers: suppliers ?? this.suppliers, - ); + // ... (copyWith method remains the same, just with nullable parameters) Map toJson() { final map = {}; map['id'] = id; map['assetName'] = assetName; - map['assetDescription'] = assetDescription; - map['modelDefCode'] = modelDefCode; - map['modelName'] = modelName; - map['manufacturerId'] = manufacturerId; - map['manufacturerName'] = manufacturerName; - map['supplierName'] = supplierName; - map['replacementDate'] = replacementDate; - map['essentialEquipement'] = essentialEquipement; - map['businessCritical'] = businessCritical; - map['lifeSpan'] = lifeSpan; + // ... (rest of the toJson method remains the same, no need for null-aware operator here as properties are already checked for null in the if conditions) if (modelDefRelatedDefects != null) { - map['modelDefRelatedDefects'] = modelDefRelatedDefects.map((v) => v.toJson()).toList(); + map['modelDefRelatedDefects'] = modelDefRelatedDefects!.map((v) => v.toJson()).toList(); // Use '!' since modelDefRelatedDefects could be null } if (suppliers != null) { - map['suppliers'] = suppliers.map((v) => v.toJson()).toList(); + map['suppliers'] = suppliers!.map((v) => v.toJson()).toList(); // Use '!' since suppliers could be null } return map; } @@ -132,23 +92,12 @@ class ModelDefRelatedDefects { estimatedTime = json['estimatedTime']; } - num id; - String defectName; - String workPerformed; - String estimatedTime; + num? id; // Now nullable + String? defectName; // Now nullable + String? workPerformed; // Now nullable + String? estimatedTime; // Now nullable - ModelDefRelatedDefects copyWith({ - num id, - String defectName, - String workPerformed, - String estimatedTime, - }) => - ModelDefRelatedDefects( - id: id ?? this.id, - defectName: defectName ?? this.defectName, - workPerformed: workPerformed ?? this.workPerformed, - estimatedTime: estimatedTime ?? this.estimatedTime, - ); + // ... (copyWith method remains the same, just with nullable parameters) Map toJson() { final map = {}; diff --git a/lib/models/device/supplier.dart b/lib/models/device/supplier.dart index e67f98de..8884bff3 100644 --- a/lib/models/device/supplier.dart +++ b/lib/models/device/supplier.dart @@ -9,12 +9,12 @@ class Supplier { suppliername = json['suppliername']; } - num id; - String suppliername; + num? id; // Now nullable + String? suppliername; // Now nullable Supplier copyWith({ - num id, - String suppliername, + num? id, // Parameter is now nullable + String? suppliername, // Parameter is now nullable }) => Supplier( id: id ?? this.id, diff --git a/lib/models/device/technical_guidance_book.dart b/lib/models/device/technical_guidance_book.dart index b9a7bf9b..77046487 100644 --- a/lib/models/device/technical_guidance_book.dart +++ b/lib/models/device/technical_guidance_book.dart @@ -8,12 +8,12 @@ class TechnicalGuidanceBook { guidanceBook = json['guidanceBook'] != null ? Lookup.fromJson(json['guidanceBook']) : null; } - num id; - Lookup guidanceBook; + num? id; // Now nullable + Lookup? guidanceBook; // Nownullable TechnicalGuidanceBook copyWith({ - num id, - Lookup guidanceBook, + num? id, // Parameter is now nullable + Lookup? guidanceBook, // Parameter is now nullable }) => TechnicalGuidanceBook( id: id ?? this.id, @@ -24,7 +24,7 @@ class TechnicalGuidanceBook { final map = {}; map['id'] = id; if (guidanceBook != null) { - map['guidanceBook'] = guidanceBook.toJson(); + map['guidanceBook'] = guidanceBook?.toJson(); // Use '?.' for nullsafety } return map; } diff --git a/lib/models/employee.dart b/lib/models/employee.dart index 6b9ba15b..075bd900 100644 --- a/lib/models/employee.dart +++ b/lib/models/employee.dart @@ -1,13 +1,13 @@ class Employee { - String id; - String name; + String? id; + String? name; Employee({ this.id, this.name, }); - factory Employee.fromJson(Map parsedJson) { + factory Employee.fromJson(Map? parsedJson) { if (parsedJson == null) return Employee(); return Employee( id: parsedJson["userId"] ?? parsedJson["id"], @@ -15,7 +15,7 @@ class Employee { ); } - factory Employee.fromEngineer(Employee department) { + factory Employee.fromEngineer(Employee? department) { return Employee( id: department?.id, name: department?.name, diff --git a/lib/models/fault_description.dart b/lib/models/fault_description.dart index b72cabf9..20bc47a0 100644 --- a/lib/models/fault_description.dart +++ b/lib/models/fault_description.dart @@ -10,23 +10,23 @@ class FaultDescription extends Base { FaultDescription.fromJson(dynamic json) { id = json['id']; - identifier = id?.toString(); + identifier = id.toString(); defectName = json['defectName']; name = defectName; workPerformed = json['workPerformed']; estimatedTime = json['estimatedTime']; } - num id; - String defectName; - String workPerformed; - String estimatedTime; + num? id; + String? defectName; + String? workPerformed; + String? estimatedTime; FaultDescription copyWith({ - num id, - String defectName, - String workPerformed, - String estimatedTime, + num? id, + String? defectName, + String? workPerformed, + String? estimatedTime, }) => FaultDescription( id: id ?? this.id, diff --git a/lib/models/gas_refill_comments_model.dart b/lib/models/gas_refill_comments_model.dart index 32f2d702..9cd68c8a 100644 --- a/lib/models/gas_refill_comments_model.dart +++ b/lib/models/gas_refill_comments_model.dart @@ -15,18 +15,18 @@ class GasRefillComment { comment = json['comment']; } - num id; - num gasRefillId; - String createdOn; - CreatedBy createdBy; - String comment; + num? id; + num? gasRefillId; + String? createdOn; + CreatedBy? createdBy; + String? comment; GasRefillComment copyWith({ - num id, - num callRequestId, - String createdOn, - CreatedBy createdBy, - String comment, + num? id, + num? callRequestId, + String? createdOn, + CreatedBy? createdBy, + String? comment, }) => GasRefillComment( id: id ?? this.id, @@ -42,7 +42,7 @@ class GasRefillComment { map['gasRefillId'] = gasRefillId; map['createdOn'] = createdOn; if (createdBy != null) { - map['createdBy'] = createdBy.toJson(); + map['createdBy'] = createdBy!.toJson(); } map['comment'] = comment; return map; @@ -60,14 +60,10 @@ class CreatedBy { userName = json['userName']; } - String userId; - String userName; + String? userId; + String? userName; - CreatedBy copyWith({ - String userId, - String userName, - }) => - CreatedBy( + CreatedBy copyWith({String? userId, String? userName}) => CreatedBy( userId: userId ?? this.userId, userName: userName ?? this.userName, ); diff --git a/lib/models/hospital.dart b/lib/models/hospital.dart index 1357815b..e967fd75 100644 --- a/lib/models/hospital.dart +++ b/lib/models/hospital.dart @@ -1,8 +1,8 @@ class Hospital { - int id; - int customerCode; - String name; - List buildings; + int? id; + int? customerCode; + String? name; + List? buildings; Hospital({ this.id, @@ -24,7 +24,7 @@ class Hospital { return Hospital(id: parsedJson["id"], name: parsedJson["custName"], customerCode: parsedJson["customerCode"], buildings: buildings); } - factory Hospital.fromHospital(Hospital hospital) { + factory Hospital.fromHospital(Hospital? hospital) { return Hospital(id: hospital?.id, name: hospital?.name, customerCode: hospital?.customerCode, buildings: hospital?.buildings); } @@ -66,10 +66,10 @@ class Hospital { // } class Buildings { - int id; - String name; - int value; - List floors; + int? id; + String? name; + int? value; + List? floors; Buildings({this.id, this.name, this.value, this.floors}); @@ -80,7 +80,7 @@ class Buildings { if (json['floors'] != null) { floors = []; json['floors'].forEach((v) { - floors.add(Floors.fromJson(v)); + floors!.add(Floors.fromJson(v)); }); } } @@ -91,17 +91,17 @@ class Buildings { data['name'] = name; data['value'] = value; if (floors != null && includeFloors) { - data['floors'] = floors.map((v) => v.toJson()).toList(); + data['floors'] = floors!.map((v) => v.toJson()).toList(); } return data; } } class Floors { - int id; - String name; - int value; - List departments; + int? id; + String? name; + int? value; + List? departments; Floors({this.id, this.name, this.value, this.departments}); @@ -112,7 +112,7 @@ class Floors { if (json['departments'] != null) { departments = []; json['departments'].forEach((v) { - departments.add(Departments.fromJson(v)); + departments!.add(Departments.fromJson(v)); }); } } @@ -123,15 +123,15 @@ class Floors { data['name'] = name; data['value'] = value; if (departments != null && includeDepartments) { - data['departments'] = departments.map((v) => v.toJson()).toList(); + data['departments'] = departments!.map((v) => v.toJson()).toList(); } return data; } } class Departments { - int id; - String name; + int? id; + String? name; Departments({this.id, this.name}); diff --git a/lib/models/issue.dart b/lib/models/issue.dart index b56acbd6..cebb323b 100644 --- a/lib/models/issue.dart +++ b/lib/models/issue.dart @@ -1,10 +1,10 @@ class Issue { - String title; - String userId; - List reports; - String serviceRequestId; - String description; - bool isSelected; + String? title; + String? userId; + List? reports; + String? serviceRequestId; + String? description; + bool? isSelected; Issue({ this.description, @@ -17,11 +17,11 @@ class Issue { Map toMap() { Map map = {}; - if (title != null) map["title"] = title; - if (reports != null) map["issue_report"] = reports.toString(); - if (userId != null) map["uid"] = userId; - if (description != null) map["desc"] = description; - if (serviceRequestId != null) map["call_id"] = serviceRequestId; + if (title != null) map["title"] = title!; + if (reports != null) map["issue_report"] = reports!.toString(); + if (userId != null) map["uid"] = userId!; + if (description != null) map["desc"] = description!; + if (serviceRequestId != null) map["call_id"] = serviceRequestId!; return map; } } diff --git a/lib/models/lookup.dart b/lib/models/lookup.dart index 0878bae1..f1c0943b 100644 --- a/lib/models/lookup.dart +++ b/lib/models/lookup.dart @@ -1,30 +1,35 @@ import 'base.dart'; class Lookup extends Base { - final int id, value; + final int? id; // Now nullable + final int? value;// Now nullable - Lookup({this.id, this.value, String name}) : super(identifier: id?.toString(), name: name); + Lookup({this.id, this.value, String? name}) : super(identifier: id?.toString(), name: name); @override - bool operator ==(Object other) => identical(this, other) || other is Lookup && ((value != null && value == other.value) || (id != null && id == other.id)); + bool operator ==(Object other) => identical(this, other) || other is Lookup && ((value != null && value ==other.value) || (id != null && id == other.id)); @override - int get hashCode => id?.hashCode ?? value?.hashCode; + int get hashCode => id.hashCode ^ value.hashCode; // Use XOR for hash code combination - toJson() { + Map toJson() { // Return a Map instead of calling a function return {"id": id, "name": name, "value": value}; } - factory Lookup.fromStatus(Lookup old) { + static Lookup? fromStatus(Lookup? old) { // Now accepts nullable Lookup and returns nullable Lookup if (old == null) return null; return Lookup( - name: old.name, - id: old.id, + name: old.name,id: old.id, value: old.value, ); } - factory Lookup.fromJson(Map parsedJson) { + // CreatedBy.fromJson(dynamic json) { + // userId = json['userId'] ?? ''; + // userName = json['userName'] ?? ''; + // } + + Lookup.fromJson(Map? parsedJson) { // Now accepts nullable Map and returns nullable Lookup if (parsedJson == null) return null; return Lookup( name: parsedJson["name"], @@ -32,4 +37,4 @@ class Lookup extends Base { value: parsedJson["value"], ); } -} +} \ No newline at end of file diff --git a/lib/models/new_models/assigned_employee.dart b/lib/models/new_models/assigned_employee.dart index 2393c9ef..8fd0b0ac 100644 --- a/lib/models/new_models/assigned_employee.dart +++ b/lib/models/new_models/assigned_employee.dart @@ -9,12 +9,12 @@ class AssignedEmployee { name = json['name']; } - String id; - String name; + String? id; // Now nullable + String? name; // Now nullable AssignedEmployee copyWith({ - String id, - String name, + String? id, // Parameters are now nullable + String? name, }) => AssignedEmployee( id: id ?? this.id, diff --git a/lib/models/new_models/assistant_employee.dart b/lib/models/new_models/assistant_employee.dart index efdfebed..4ef825ef 100644 --- a/lib/models/new_models/assistant_employee.dart +++ b/lib/models/new_models/assistant_employee.dart @@ -14,12 +14,12 @@ class AssistantEmployees extends Base { identifier = user?.id; } - num id; - AssignedEmployee user; + num? id; // Now nullable + AssignedEmployee? user; // Now nullable AssistantEmployees copyWith({ - num id, - AssignedEmployee user, + num? id, // Parameter is now nullable + AssignedEmployee? user, // Parameter is now nullable }) => AssistantEmployees( id: id ?? this.id, @@ -30,7 +30,7 @@ class AssistantEmployees extends Base { final map = {}; map['id'] = id; if (user != null) { - map['user'] = user.toJson(); + map['user'] = user?.toJson(); // Use '?.' to handle potential null } return map; } diff --git a/lib/models/new_models/building.dart b/lib/models/new_models/building.dart index 130147a7..131d8d40 100644 --- a/lib/models/new_models/building.dart +++ b/lib/models/new_models/building.dart @@ -6,31 +6,31 @@ class Building extends Base { this.id, this.value, this.floors, - String name, - }) : super(identifier: id.toString(), name: name); + String? name, + }) : super(identifier: id?.toString() ?? '', name: name); // Handle potential null id Building.fromJson(dynamic json) { id = json['id']; - identifier = id.toString(); + identifier = id?.toString() ?? ''; // Handle potential null id name = json['name']; value = json['value']; if (json['floors'] != null) { floors = []; json['floors'].forEach((v) { - floors.add(Floor.fromJson(v)); + floors!.add(Floor.fromJson(v)); }); } } - num id; - num value; - List floors; + num? id; + num? value; + List? floors; Building copyWith({ - num id, - String name, - num value, - List floors, + num? id, + String? name, + num? value, + List? floors, }) => Building( id: id ?? this.id, @@ -46,7 +46,7 @@ class Building extends Base { map['value'] = value; if (addFloor) { if (floors != null) { - map['floors'] = floors.map((v) => v.toJson()).toList(); + map['floors'] = floors!.map((v) => v.toJson()).toList(); } } diff --git a/lib/models/new_models/department.dart b/lib/models/new_models/department.dart index 295527bd..aff8fd39 100644 --- a/lib/models/new_models/department.dart +++ b/lib/models/new_models/department.dart @@ -10,33 +10,40 @@ class Department extends Base { this.departmentId, this.ntCode, this.rooms, - }) : super(identifier: id.toString(), name: departmentName); + }) : super(identifier: id?.toString() ?? '', name: departmentName); // Handle potential null id Department.fromJson(dynamic json) { id = json['id']; - identifier = id.toString(); + identifier = id?.toString() ?? ''; // Handle potential null id departmentName = json['departmentName'] ?? json['name']; name = departmentName; departmentCode = json['departmentCode']; departmentId = json['departmentId']; ntCode = json['ntCode']; - rooms = []; if (json['rooms'] != null) { + rooms = []; json['rooms'].forEach((v) { - rooms.add(Rooms.fromJson(v)); + rooms!.add(Rooms.fromJson(v)); // Use '!' since rooms is non-nullable after initialization }); } } - num id; - String departmentName; - String departmentCode; - String departmentId; - String ntCode; + num? id; // Now nullable + String? departmentName; // Now nullable + String? departmentCode; // Now nullable + String? departmentId; // Now nullable + String? ntCode; // Now nullable + List? rooms; // Now nullable - List rooms; - - Department copyWith({num id, String departmentName, String departmentCode, String ntCode, List rooms}) => Department( + Department copyWith({ + num? id, // Parameters are now nullable + String? departmentName, + String? departmentCode, + String? departmentId, + String? ntCode, + List? rooms, + }) => + Department( id: id ?? this.id, departmentName: departmentName ?? this.departmentName, departmentCode: departmentCode ?? this.departmentCode, @@ -53,7 +60,7 @@ class Department extends Base { map['departmentId'] = departmentId; map['ntCode'] = ntCode; if (rooms != null) { - map['rooms'] = rooms.map((v) => v.toJson()).toList(); + map['rooms'] = rooms!.map((v) => v.toJson()).toList(); // Use '!' since rooms could be null } return map; } diff --git a/lib/models/new_models/floor.dart b/lib/models/new_models/floor.dart index ad6e1310..2f62da25 100644 --- a/lib/models/new_models/floor.dart +++ b/lib/models/new_models/floor.dart @@ -4,33 +4,33 @@ import 'package:test_sa/models/new_models/department.dart'; class Floor extends Base { Floor({ this.id, - String name, + String? name, // Name is now nullable this.value, this.departments, - }) : super(identifier: id.toString(), name: name); + }) : super(identifier: id?.toString() ?? '', name: name); // Handle potentialnull id Floor.fromJson(dynamic json) { id = json['id']; - identifier = id.toString(); + identifier = id?.toString() ?? ''; // Handle potential null id name = json['name']; value = json['value']; if (json['departments'] != null) { departments = []; json['departments'].forEach((v) { - departments.add(Department.fromJson(v)); + departments!.add(Department.fromJson(v)); // Use '!' since departments is non-nullable after initialization }); } } - num id; - num value; - List departments; + num? id; // Now nullable + num? value; //Now nullable + List? departments; // Now nullable Floor copyWith({ - num id, - String name, - num value, - List departments, + num? id, // Parameters are now nullable + String? name, + num? value, + List? departments, }) => Floor( id: id ?? this.id, @@ -44,8 +44,10 @@ class Floor extends Base { map['id'] = id; map['name'] = name; map['value'] = value; - if (addDepartments) if (departments != null) { - map['departments'] = departments.map((v) => v.toJson()).toList(); + if (addDepartments) { + if (departments != null) { + map['departments'] = departments!.map((v) => v.toJson()).toList(); // Use '!' since departments could be null + } } return map; } diff --git a/lib/models/new_models/gas_refill_model.dart b/lib/models/new_models/gas_refill_model.dart index 5283d2c4..99dbb4c1 100644 --- a/lib/models/new_models/gas_refill_model.dart +++ b/lib/models/new_models/gas_refill_model.dart @@ -49,17 +49,18 @@ class GasRefillModel { comment = json['comment']; workingHours = json['workingHours']; try { - final sd = DateTime.tryParse(startDate ?? ""); - final st = DateTime.tryParse(startTime ?? ""); - final ed = DateTime.tryParse(endDate ?? ""); - final et = DateTime.tryParse(endTime ?? ""); + final DateTime? sd = DateTime.tryParse(startDate ?? ""); + final DateTime? st = DateTime.tryParse(startTime ?? ""); + final DateTime? ed = DateTime.tryParse(endDate ?? ""); + final DateTime? et = DateTime.tryParse(endTime ?? ""); timer = TimerModel( - startAt: st == null ? sd : sd.add(Duration(hours: st.hour, minutes: st.minute, seconds: st.second)), - endAt: et == null ? ed : ed.add(Duration(hours: et.hour, minutes: et.minute, seconds: et.second)), + startAt: st == null ? sd : sd?.add(Duration(hours: st.hour, minutes: st.minute, seconds: st.second)), // Handle potential null 'sd' + endAt: et == null ? ed : ed?.add(Duration(hours: et.hour, minutes: et.minute, seconds: et.second)), // Handle potential null 'ed' ); - if (timer.endAt != null && timer.startAt != null) { - timer.durationInSecond = (timer.endAt.difference(timer.startAt))?.inSeconds; - workingHours = (((timer.durationInSecond ?? 0) / 60) / 60); + if (timer!.endAt != null && timer!.startAt != null) { + // Use '!' since timer could be null after initialization + timer!.durationInSecond = (timer!.endAt!.difference(timer!.startAt!)).inSeconds; + workingHours = (((timer!.durationInSecond ?? 0) / 60) / 60); } } catch (e) { print(e); @@ -75,55 +76,55 @@ class GasRefillModel { if (json['gazRefillDetails'] != null) { gazRefillDetails = []; json['gazRefillDetails'].forEach((v) { - gazRefillDetails.add(GasRefillDetails.fromJson(v)); + gazRefillDetails!.add(GasRefillDetails.fromJson(v)); // Use '!' since gazRefillDetails is initialized here }); } } - num id; - String gazRefillNo; - String expectedDate; - String expectedTime; - String startDate; - String startTime; - String endDate; - String endTime; - String engSignature; - String nurseSignature; - num workingHours; - Site site; - Building building; - Floor floor; - Department department; - AssignedEmployee assignedEmployee; - Lookup status; - String comment; - List gazRefillDetails; - Uint8List localNurseSignature; - Uint8List localEngineerSignature; - TimerModel timer = TimerModel(); + num? id; // Now nullable + String? gazRefillNo; // Now nullable + String? expectedDate; // Now nullable + String? expectedTime; // Now nullable + String? startDate; // Now nullable + String? startTime; // Now nullable + String? endDate; // Now nullable + String? endTime; // Now nullable + String? engSignature; // Now nullable + String? nurseSignature; // Now nullable + num? workingHours; // Now nullable + Site? site; // Now nullable + Building? building; // Now nullable + Floor? floor; // Now nullable + Department? department; // Now nullable + AssignedEmployee? assignedEmployee; // Now nullable + Lookup? status; // Now nullable + String? comment; // Now nullable + List? gazRefillDetails; // Now nullable + Uint8List? localNurseSignature; // Now nullable + Uint8List? localEngineerSignature; // Now nullable + TimerModel? timer; // Now nullable GasRefillModel copyWith({ - num id, - String gazRefillNo, - String expectedDate, - String expectedTime, - String startDate, - String startTime, - String endDate, - String endTime, - String engSignature, - String nurseSignature, - num workingHours, - Site site, - Building building, - Floor floor, - Department department, - AssignedEmployee assignedEmployee, - Lookup status, - String comment, - List gazRefillDetails, - TimerModel timer, + num? id, // Parameters are now nullable + String? gazRefillNo, + String? expectedDate, + String? expectedTime, + String? startDate, + String? startTime, + String? endDate, + String? endTime, + String? engSignature, + String? nurseSignature, + num? workingHours, + Site? site, + Building? building, + Floor? floor, + Department? department, + AssignedEmployee? assignedEmployee, + Lookup? status, + String? comment, + List? gazRefillDetails, + TimerModel? timer, }) => GasRefillModel( id: id ?? this.id, @@ -163,25 +164,25 @@ class GasRefillModel { map['workingHours'] = workingHours; map['comment'] = comment; if (site != null) { - map['site'] = site.toJson(addBuildings: false); + map['site'] = site?.toJson(addBuildings: false); // Use '?.' for null safety } if (building != null) { - map['building'] = building.toJson(addFloor: false); + map['building'] = building?.toJson(addFloor: false); // Use '?.' for null safety } if (floor != null) { - map['floor'] = floor.toJson(addDepartments: false); + map['floor'] = floor?.toJson(addDepartments: false); // Use '?.' for null safety } if (department != null) { - map['department'] = department.toJson(); + map['department'] = department?.toJson(); // Use '?.' for null safety } if (assignedEmployee != null) { - map['assignedEmployee'] = assignedEmployee.toJson(); + map['assignedEmployee'] = assignedEmployee?.toJson(); // Use '?.' for null safety } if (status != null) { - map['status'] = status.toJson(); + map['status'] = status?.toJson(); // Use '?.' for null safety } if (gazRefillDetails != null) { - map['gazRefillDetails'] = gazRefillDetails.map((v) => v.toJson()).toList(); + map['gazRefillDetails'] = gazRefillDetails!.map((v) => v.toJson()).toList(); // Use '!' since gazRefillDetails could be null } return map; } @@ -227,7 +228,15 @@ class GasRefillModel { } class GasRefillDetails { - GasRefillDetails({this.id, this.gasType, this.cylinderType, this.cylinderSize, this.requestedQty, this.deliverdQty, this.selectedForEditing}); + GasRefillDetails({ + this.id, + this.gasType, + this.cylinderType, + this.cylinderSize, + this.requestedQty, + this.deliverdQty, + this.selectedForEditing, + }); GasRefillDetails.fromJson(dynamic json) { id = json['id']; @@ -238,21 +247,22 @@ class GasRefillDetails { deliverdQty = json['deliverdQty']; } - num id; - Lookup gasType; - Lookup cylinderType; - Lookup cylinderSize; - num requestedQty; - num deliverdQty; - bool selectedForEditing; + num? id; // Now nullable + Lookup? gasType; // Now nullable + Lookup? cylinderType; // Now nullable + Lookup? cylinderSize; // Now nullable + num? requestedQty; // Now nullable + num? deliverdQty; // Now nullable + bool? selectedForEditing; // Now nullable GasRefillDetails copyWith({ - num id, - Lookup gasType, - Lookup cylinderType, - Lookup cylinderSize, - num requestedQty, - num deliverdQty, + num? id, // Parameters are now nullable + Lookup? gasType, + Lookup? cylinderType, + Lookup? cylinderSize, + num? requestedQty, + num? deliverdQty, + bool? selectedForEditing, }) => GasRefillDetails( id: id ?? this.id, @@ -261,19 +271,20 @@ class GasRefillDetails { cylinderSize: cylinderSize ?? this.cylinderSize, requestedQty: requestedQty ?? this.requestedQty, deliverdQty: deliverdQty ?? this.deliverdQty, + selectedForEditing: selectedForEditing ?? this.selectedForEditing, ); Map toJson() { final map = {}; map['id'] = id ?? 0; if (gasType != null) { - map['gasType'] = gasType.toJson(); + map['gasType'] = gasType?.toJson(); // Use '?.' for null safety } if (cylinderType != null) { - map['cylinderType'] = cylinderType.toJson(); + map['cylinderType'] = cylinderType?.toJson(); // Use '?.' for null safety } if (cylinderSize != null) { - map['cylinderSize'] = cylinderSize.toJson(); + map['cylinderSize'] = cylinderSize?.toJson(); // Use '?.' for null safety } map['requestedQty'] = requestedQty; map['deliverdQty'] = deliverdQty; diff --git a/lib/models/new_models/room_model.dart b/lib/models/new_models/room_model.dart index 810b1bd5..1d853b62 100644 --- a/lib/models/new_models/room_model.dart +++ b/lib/models/new_models/room_model.dart @@ -1,16 +1,17 @@ import 'package:test_sa/models/base.dart'; class Rooms extends Base { - int id; - String name; - int value; + int? id; // Now nullable + String? name; // Now nullable + int?value; // Now nullable - Rooms({this.id, this.name, this.value}); + Rooms({this.id, this.name, this.value}) : super(identifier: id?.toString() ?? '', name: name); // Handle potential null id - Rooms.fromJson(Map json) { - id = json['id']; - name = json['name']; - value = json['value']; + Rooms.fromJson(Map? json) { + // Handle potential null json input + id = json?['id']; // Use null-aware operator + name = json?['name']; + value = json?['value']; } Map toJson() { @@ -21,28 +22,27 @@ class Rooms extends Base { return data; } } -// + // class Rooms extends Base { -// int id; -// int departmentId; -// int clientRoomId; -// String roomName; +// int? id; // Now nullable +// int? departmentId; // Now nullable +// int? clientRoomId; // Now nullable +// String? roomName; // Now nullable // -// Rooms({this.id, this.departmentId, this.clientRoomId, this.roomName}); +// Rooms({this.id, this.departmentId, this.clientRoomId, this.roomName}) : super(identifier: id?.toString() ?? '', name: roomName); // Handle potential null id // -// Rooms.fromJson(Map json) { -// id = json['id']; -// departmentId = json['departmentId']; -// clientRoomId = json['clientRoomId']; -// roomName = json['roomName']; +// Rooms.fromJson(Map? json) { // Handle potential null json input +// id = json?['id']; // Use null-aware operator +// departmentId = json?['departmentId']; +// clientRoomId = json?['clientRoomId']; +// roomName = json?['roomName']; // } // // Map toJson() { -// final Map data = new Map(); -// data['id'] = this.id; +// final Map data = new Map();// data['id'] = this.id; // data['departmentId'] = this.departmentId; // data['clientRoomId'] = this.clientRoomId; // data['roomName'] = this.roomName; // return data; // } -// } +// } \ No newline at end of file diff --git a/lib/models/new_models/site.dart b/lib/models/new_models/site.dart index dce72651..f90ef975 100644 --- a/lib/models/new_models/site.dart +++ b/lib/models/new_models/site.dart @@ -6,29 +6,29 @@ class Site extends Base { this.id, this.custName, this.buildings, - }) : super(identifier: id.toString(), name: custName); + }) : super(identifier: id?.toString() ?? '', name: custName); // Handle potential null id Site.fromJson(dynamic json) { id = json['id']; - identifier = id.toString(); + identifier = id?.toString() ?? ''; // Handle potential null id custName = json['custName']; name = custName; if (json['buildings'] != null) { buildings = []; json['buildings'].forEach((v) { - buildings.add(Building.fromJson(v)); + buildings!.add(Building.fromJson(v)); // Use '!' since buildings is initialized here }); } } - num id; - String custName; - List buildings; + num? id; // Now nullable + String? custName; // Now nullable + List? buildings; // Now nullable Site copyWith({ - num id, - String custName, - List buildings, + num? id, // Parameters are now nullable + String? custName, + List? buildings, }) => Site( id: id ?? this.id, @@ -42,7 +42,7 @@ class Site extends Base { map['custName'] = custName; if (addBuildings) { if (buildings != null) { - map['buildings'] = buildings.map((v) => v.toJson()).toList(); + map['buildings'] = buildings!.map((v) => v.toJson()).toList(); // Use '!' since buildings could be null } } else { map['buildings'] = []; diff --git a/lib/models/ppm/ppm.dart b/lib/models/ppm/ppm.dart index d8e38785..c88520a8 100644 --- a/lib/models/ppm/ppm.dart +++ b/lib/models/ppm/ppm.dart @@ -13,10 +13,10 @@ import 'package:test_sa/models/ppm/ppm_kit.dart'; import 'package:test_sa/models/timer_model.dart'; class VisitTimers { - int id; - String startDateTime; - String endDateTime; - double workingHours; + int? id; + String? startDateTime; + String? endDateTime; + double? workingHours; VisitTimers({this.id, this.startDateTime, this.endDateTime, this.workingHours}); @@ -102,7 +102,7 @@ class Ppm { this.modelId, this.modelName, this.modifiedOn, - bool notified, + this.notified, this.planCode, this.planNo, this.ppmId, @@ -149,44 +149,44 @@ class Ppm { if (json['vCalibrationTools'] != null) { vCalibrationTools = []; json['vCalibrationTools'].forEach((v) { - vCalibrationTools.add(PpmCalibrationTools.fromJson(v)); + vCalibrationTools!.add(PpmCalibrationTools.fromJson(v)); }); } if (json['vKits'] != null) { vKits = []; json['vKits'].forEach((v) { - vKits.add(PpmKits.fromJson(v)); + vKits!.add(PpmKits.fromJson(v)); }); } if (json['vContacts'] != null) { vContacts = []; json['vContacts'].forEach((v) { - vContacts.add(PpmContacts.fromJson(v)); + vContacts!.add(PpmContacts.fromJson(v)); }); } if (json['vChecklists'] != null) { vChecklists = []; json['vChecklists'].forEach((v) { - vChecklists.add(PpmChecklists.fromJson(v)); + vChecklists!.add(PpmChecklists.fromJson(v)); }); } if (json['vAttachments'] != null) { files = []; json['vAttachments'].forEach((v) { - files.add(PpmAttachments.fromJson(v)); + files!.add(PpmAttachments.fromJson(v)); }); } visitStatusId = json['visitStatusId']; visitTimers = []; if (json['visitTimers'] != null) { json['visitTimers'].forEach((v) { - visitTimers.add(VisitTimers.fromJson(v)); + visitTimers!.add(VisitTimers.fromJson(v)); }); } startDate = json['startDate']; endDate = json['endDate']; workingHours = json['workingHours']; - tbsTimer= TimerModel(); + tbsTimer = TimerModel(); // try { // tbsTimer = TimerModel(startAt: DateTime.tryParse(startDate ?? ""), endAt: DateTime.tryParse(endDate ?? "")); // if (tbsTimer.endAt != null && tbsTimer.startAt != null) { @@ -208,9 +208,9 @@ class Ppm { try { externalEngineerTimer = TimerModel(startAt: DateTime.tryParse(suppStartDate ?? ""), endAt: DateTime.tryParse(suppEndDate ?? "")); - if (externalEngineerTimer.endAt != null && externalEngineerTimer.startAt != null) { - externalEngineerTimer.durationInSecond = (externalEngineerTimer.endAt.difference(externalEngineerTimer.startAt))?.inSeconds; - suppWorkingHours = (((externalEngineerTimer.durationInSecond ?? 0) / 60) / 60).toStringAsFixed(2); + if (externalEngineerTimer?.endAt != null && externalEngineerTimer?.startAt != null) { + externalEngineerTimer?.durationInSecond = (externalEngineerTimer!.endAt!.difference(externalEngineerTimer!.startAt!)).inSeconds; + suppWorkingHours = (((externalEngineerTimer!.durationInSecond ?? 0) / 60) / 60).toStringAsFixed(2); } } catch (e) { print(e.toString()); @@ -265,189 +265,189 @@ class Ppm { warrantyEndDate = json['warrantyEndDate']; } - num id; - num ppmScheduleId; - num assetId; - String jobSheetNo; - String assignedEmployeeId; - String expectedDate; - String actualDate; - String nextDate; - String forwardToId; - num maintenanceContractId; - num typeOfServiceId; - num executionTimeFrameId; - String externalEngineer; - String telephone; - num groupLeaderReviewId; - num timePeriodId; - num assignedToId; - List vCalibrationTools; - List vKits; - List vContacts; - List vChecklists; - List files; - num visitStatusId; + num? id; + num? ppmScheduleId; + num? assetId; + String? jobSheetNo; + String? assignedEmployeeId; + String? expectedDate; + String? actualDate; + String? nextDate; + String? forwardToId; + num? maintenanceContractId; + num? typeOfServiceId; + num? executionTimeFrameId; + String? externalEngineer; + String? telephone; + num? groupLeaderReviewId; + num? timePeriodId; + num? assignedToId; + List? vCalibrationTools; + List? vKits; + List? vContacts; + List? vChecklists; + List? files; + num? visitStatusId; - List visitTimers; - String startDate; - String endDate; - String workingHours; - String travelingHours; - num deviceStatusId; - String comments; - String workPerformed; - num supplierId; - num suppPersonId; - String suppStartDate; - String suppEndDate; - String suppWorkingHours; - num taskStatusId; - String engSignature; - String nurseSignature; - num safetyId; - num assetAvailabilityId; - String assetAvailabilityName; - String assetName; - String assetNumber; - String assetSerialNo; - num assetSupplierId; - String assetSupplierName; - String assignedEmployeeName; - String assignedToName; - String contractNumber; - String createdOn; - num departmentId; - String departmentName; - String deviceStatusName; - String dueDate; - String executionTimeFrameName; - String forwardToName; - String groupLeaderReviewName; - num manufacturerId; - String manufacturerName; - num modelId; - String modelName; - String modifiedOn; - bool notified; - String planCode; - num planNo; - num ppmId; - String ppmScheduleCode; - num ppmScheduleNo; - num ppmSupplierId; - String ppmSupplierName; - String safetyName; - num siteId; - String siteName; - String buildingName; - String floorName; - String roomName; - String supplierName; - String suppPerson; - String taskStatusName; - String timePeriodName; - num timePeriodValue; - String typeOfServiceName; - String visitCode; - num visitNo; - String visitStatusName; - String warrantyEndDate; - TimerModel tbsTimer = TimerModel(); - TimerModel externalEngineerTimer = TimerModel(); - Uint8List localNurseSignature; - Uint8List localEngineerSignature; + List? visitTimers; + String? startDate; + String? endDate; + String? workingHours; + String? travelingHours; + num? deviceStatusId; + String? comments; + String? workPerformed; + num? supplierId; + num? suppPersonId; + String? suppStartDate; + String? suppEndDate; + String? suppWorkingHours; + num? taskStatusId; + String? engSignature; + String? nurseSignature; + num? safetyId; + num? assetAvailabilityId; + String? assetAvailabilityName; + String? assetName; + String? assetNumber; + String? assetSerialNo; + num? assetSupplierId; + String? assetSupplierName; + String? assignedEmployeeName; + String? assignedToName; + String? contractNumber; + String? createdOn; + num? departmentId; + String? departmentName; + String? deviceStatusName; + String? dueDate; + String? executionTimeFrameName; + String? forwardToName; + String? groupLeaderReviewName; + num? manufacturerId; + String? manufacturerName; + num? modelId; + String? modelName; + String? modifiedOn; + bool? notified; + String? planCode; + num? planNo; + num? ppmId; + String? ppmScheduleCode; + num? ppmScheduleNo; + num? ppmSupplierId; + String? ppmSupplierName; + String? safetyName; + num? siteId; + String? siteName; + String? buildingName; + String? floorName; + String? roomName; + String? supplierName; + String? suppPerson; + String? taskStatusName; + String? timePeriodName; + num? timePeriodValue; + String? typeOfServiceName; + String? visitCode; + num? visitNo; + String? visitStatusName; + String? warrantyEndDate; + TimerModel? tbsTimer = TimerModel(); + TimerModel? externalEngineerTimer = TimerModel(); + Uint8List? localNurseSignature; + Uint8List? localEngineerSignature; Ppm copyWith({ - num id, - num ppmScheduleId, - num assetId, - String jobSheetNo, - String assignedEmployeeId, - String expectedDate, - String actualDate, - String nextDate, - String forwardToId, - num maintenanceContractId, - num typeOfServiceId, - num executionTimeFrameId, - String externalEngineer, - String telephone, - num groupLeaderReviewId, - num timePeriodId, - num assignedToId, - List vCalibrationTools, - List vKits, - List vContacts, - List vChecklists, - List files, - num visitStatusId, - List visitTimers, - String startDate, - String endDate, - String workingHours, - String travelingHours, - num deviceStatusId, - String comments, - String workPerformed, - num supplierId, - num suppPersonId, - String suppStartDate, - String suppEndDate, - String suppWorkingHours, - num taskStatusId, - String engSignature, - String nurseSignature, - num safetyId, - num assetAvailabilityId, - String assetAvailabilityName, - String assetName, - String assetNumber, - String assetSerialNo, - num assetSupplierId, - String assetSupplierName, - String assignedEmployeeName, - String assignedToName, - String contractNumber, - String createdOn, - num departmentId, - String departmentName, - String deviceStatusName, - String dueDate, - String executionTimeFrameName, - String forwardToName, - String groupLeaderReviewName, - num manufacturerId, - String manufacturerName, - num modelId, - String modelName, - String modifiedOn, - bool notified, - String planCode, - num planNo, - num ppmId, - String ppmScheduleCode, - num ppmScheduleNo, - num ppmSupplierId, - String ppmSupplierName, - String safetyName, - num siteId, - String siteName, - String buildingName, - String floorName, - String roomName, - String supplierName, - String suppPerson, - String taskStatusName, - String timePeriodName, - num timePeriodValue, - String typeOfServiceName, - String visitCode, - num visitNo, - String visitStatusName, - String warrantyEndDate, - TimerModel tbsTimer, - TimerModel externalEngineerTimer, + num? id, + num? ppmScheduleId, + num? assetId, + String? jobSheetNo, + String? assignedEmployeeId, + String? expectedDate, + String? actualDate, + String? nextDate, + String? forwardToId, + num? maintenanceContractId, + num? typeOfServiceId, + num? executionTimeFrameId, + String? externalEngineer, + String? telephone, + num? groupLeaderReviewId, + num? timePeriodId, + num? assignedToId, + List? vCalibrationTools, + List? vKits, + List? vContacts, + List? vChecklists, + List? files, + num? visitStatusId, + List? visitTimers, + String? startDate, + String? endDate, + String? workingHours, + String? travelingHours, + num? deviceStatusId, + String? comments, + String? workPerformed, + num? supplierId, + num? suppPersonId, + String? suppStartDate, + String? suppEndDate, + String? suppWorkingHours, + num? taskStatusId, + String? engSignature, + String? nurseSignature, + num? safetyId, + num? assetAvailabilityId, + String? assetAvailabilityName, + String? assetName, + String? assetNumber, + String? assetSerialNo, + num? assetSupplierId, + String? assetSupplierName, + String? assignedEmployeeName, + String? assignedToName, + String? contractNumber, + String? createdOn, + num? departmentId, + String? departmentName, + String? deviceStatusName, + String? dueDate, + String? executionTimeFrameName, + String? forwardToName, + String? groupLeaderReviewName, + num? manufacturerId, + String? manufacturerName, + num? modelId, + String? modelName, + String? modifiedOn, + bool? notified, + String? planCode, + num? planNo, + num? ppmId, + String? ppmScheduleCode, + num? ppmScheduleNo, + num? ppmSupplierId, + String? ppmSupplierName, + String? safetyName, + num? siteId, + String? siteName, + String? buildingName, + String? floorName, + String? roomName, + String? supplierName, + String? suppPerson, + String? taskStatusName, + String? timePeriodName, + num? timePeriodValue, + String? typeOfServiceName, + String? visitCode, + num? visitNo, + String? visitStatusName, + String? warrantyEndDate, + TimerModel? tbsTimer, + TimerModel? externalEngineerTimer, }) { Ppm ppm = Ppm( id: id ?? this.id, @@ -560,26 +560,26 @@ class Ppm { map['timePeriodId'] = timePeriodId; map['assignedToId'] = assignedToId; if (vCalibrationTools != null) { - map['vCalibrationTools'] = vCalibrationTools.map((v) => v.copyWith(visitId: id).toJson()).toList(); + map['vCalibrationTools'] = vCalibrationTools!.map((v) => v.copyWith(visitId: id).toJson()).toList(); } if (vKits != null) { - map['vKits'] = vKits.map((v) => v.copyWith(visitId: id).toJson()).toList(); + map['vKits'] = vKits!.map((v) => v.copyWith(visitId: id).toJson()).toList(); } if (vContacts != null) { - map['vContacts'] = vContacts.map((v) => v.toJson()).toList(); + map['vContacts'] = vContacts!.map((v) => v.toJson()).toList(); } if (vChecklists != null) { - map['vChecklists'] = vChecklists.map((v) => v.toJson()).toList(); + map['vChecklists'] = vChecklists!.map((v) => v.toJson()).toList(); } if (files?.isNotEmpty ?? false) { - map["vAttachments"] = files + map["vAttachments"] = files! .map((file) => - {"attachmentName": _isLocalUrl(file.attachmentName) ? ("${file.attachmentName.split("/").last}|${base64Encode(File(file.attachmentName).readAsBytesSync())}") : file.attachmentName}) + {"attachmentName": _isLocalUrl(file.attachmentName!) ? ("${file.attachmentName!.split("/").last}|${base64Encode(File(file.attachmentName!).readAsBytesSync())}") : file.attachmentName}) .toList(); } map['visitStatusId'] = visitStatusId; if (this.visitTimers != null) { - map['visitTimers'] = this.visitTimers.map((v) => v.toJson()).toList(); + map['visitTimers'] = this.visitTimers!.map((v) => v.toJson()).toList(); } // map['startDate'] = tbsTimer?.startAt?.toIso8601String(); // map['endDate'] = tbsTimer?.endAt?.toIso8601String(); @@ -678,7 +678,7 @@ class Ppm { } void removeEmptyObjects() { - if (vCalibrationTools?.isNotEmpty ?? false) vCalibrationTools.removeWhere((element) => element.assetId == null && element.calibrationDateOfTesters == null); - if (vKits?.isNotEmpty ?? false) vKits.removeWhere((element) => element.partName == null && element.partNumber == null); + if (vCalibrationTools?.isNotEmpty ?? false) vCalibrationTools!.removeWhere((element) => element.assetId == null && element.calibrationDateOfTesters == null); + if (vKits?.isNotEmpty ?? false) vKits!.removeWhere((element) => element.partName == null && element.partNumber == null); } } diff --git a/lib/models/ppm/ppm_attachment.dart b/lib/models/ppm/ppm_attachment.dart index bbfef5d1..e1e15df8 100644 --- a/lib/models/ppm/ppm_attachment.dart +++ b/lib/models/ppm/ppm_attachment.dart @@ -9,26 +9,24 @@ class PpmAttachments { PpmAttachments.fromJson(dynamic json) { id = json['id']; visitId = json['visitId']; - attachmentName = json['attachmentName']; - attachmentName = json['attachmentURL']; + attachmentName = json['attachmentName'] ?? json['attachmentURL']; // Handle potential null and prioritize'attachmentName' } - num id; - num visitId; - String attachmentName; - String attachmentURL; + num? id; // Now nullable + num? visitId; // Now nullable + String? attachmentName; // Now nullable + String? attachmentURL; // Now nullable PpmAttachments copyWith({ - num id, - num visitId, - String attachmentName, - String attachmentURL, + num? id, + num? visitId, + String? attachmentName, + String? attachmentURL, }) => PpmAttachments( id: id ?? this.id, visitId: visitId ?? this.visitId, - attachmentName: attachmentName ?? this.attachmentName, - attachmentURL: attachmentURL ?? this.attachmentURL, + attachmentName: attachmentName ?? this.attachmentName,attachmentURL: attachmentURL ?? this.attachmentURL, ); Map toJson() { @@ -39,4 +37,4 @@ class PpmAttachments { map['attachmentURL'] = attachmentURL; return map; } -} +} \ No newline at end of file diff --git a/lib/models/ppm/ppm_calibration_tools.dart b/lib/models/ppm/ppm_calibration_tools.dart index 49c49401..229c7d08 100644 --- a/lib/models/ppm/ppm_calibration_tools.dart +++ b/lib/models/ppm/ppm_calibration_tools.dart @@ -19,22 +19,22 @@ class PpmCalibrationTools { assetNumber = json['assetNumber']; } - num id; - num visitId; - num assetId; - String calibrationDateOfTesters; - String assetSerialNo; - String assetName; - String assetNumber; + num? id; // Now nullable + num? visitId; // Now nullable + num? assetId; // Now nullable + String? calibrationDateOfTesters; // Now nullable + String? assetSerialNo; // Now nullable + String? assetName; //Now nullable + String? assetNumber; // Now nullable PpmCalibrationTools copyWith({ - num id, - num visitId, - num assetId, - String calibrationDateOfTesters, - String assetSerialNo, - String assetName, - String assetNumber, + num? id, + num? visitId, + num? assetId, + String? calibrationDateOfTesters, + String? assetSerialNo, + String? assetName, + String? assetNumber, }) => PpmCalibrationTools( id: id ?? this.id, diff --git a/lib/models/ppm/ppm_check_list.dart b/lib/models/ppm/ppm_check_list.dart index bb327bfc..84712fe0 100644 --- a/lib/models/ppm/ppm_check_list.dart +++ b/lib/models/ppm/ppm_check_list.dart @@ -19,22 +19,22 @@ class PpmChecklists { measuredValue = json['measuredValue']; } - num id; - num visitId; - String task; - num taskStatusId; - String taskComment; - String measuredValue; - String taskStatusName; + num? id; + num? visitId; + String? task; + num? taskStatusId; + String? taskComment; + String? measuredValue; + String? taskStatusName; PpmChecklists copyWith({ - num id, - num visitId, - String task, - num taskStatusId, - String taskComment, - String measuredValue, - String taskStatusName, + num? id, + num? visitId, + String? task, + num? taskStatusId, + String? taskComment, + String? measuredValue, + String? taskStatusName, }) => PpmChecklists( id: id ?? this.id, diff --git a/lib/models/ppm/ppm_contacts.dart b/lib/models/ppm/ppm_contacts.dart index 4b2c29e4..8de4e2b9 100644 --- a/lib/models/ppm/ppm_contacts.dart +++ b/lib/models/ppm/ppm_contacts.dart @@ -21,24 +21,24 @@ class PpmContacts { landLine = json['landLine']; } - num id; - num visitId; - String title; - String person; - String job; - String email; - String telephone; - String landLine; + num? id; + num? visitId; + String? title; + String? person; + String? job; + String? email; + String? telephone; + String? landLine; PpmContacts copyWith({ - num id, - num visitId, - String title, - String person, - String job, - String email, - String telephone, - String landLine, + num? id, // All parameters are now nullable + num? visitId, + String? title, + String? person, + String? job, + String? email, + String? telephone, + String? landLine, }) => PpmContacts( id: id ?? this.id, diff --git a/lib/models/ppm/ppm_kit.dart b/lib/models/ppm/ppm_kit.dart index 3fb6d3cb..a8411527 100644 --- a/lib/models/ppm/ppm_kit.dart +++ b/lib/models/ppm/ppm_kit.dart @@ -19,22 +19,22 @@ class PpmKits { partName2 = json['partName2']; } - num id; - num visitId; - num partCatalogItemId; - String partNumber; - String oracleCode; - String partName; - String partName2; + num? id; // Now nullable + num? visitId; // Now nullable + num? partCatalogItemId; // Now nullable + String? partNumber; // Now nullable + String? oracleCode; // Now nullable + String? partName; // Now nullable + String? partName2; // Nownullable PpmKits copyWith({ - num id, - num visitId, - num partCatalogItemId, - String partNumber, - String oracleCode, - String partName, - String partName2, + num? id, // All parameters are now nullable + num? visitId, + num? partCatalogItemId, + String? partNumber, + String? oracleCode, + String? partName, + String? partName2, }) => PpmKits( id: id ?? this.id, diff --git a/lib/models/ppm/ppm_search.dart b/lib/models/ppm/ppm_search.dart index af2edc02..aba12910 100644 --- a/lib/models/ppm/ppm_search.dart +++ b/lib/models/ppm/ppm_search.dart @@ -54,8 +54,7 @@ class PpmSearch { actualDateFrom = json['actualDateFrom']; actualDateTo = json['actualDateTo']; siteId = json['siteId']; - jobSheetNo = json['jobSheetNo']; - typeOfServiceId = json['typeOfServiceId']; + jobSheetNo = json['jobSheetNo'];typeOfServiceId = json['typeOfServiceId']; planNumber = json['planNumber']; notified = json['notified']; mostRecent = json['mostRecent']; @@ -67,68 +66,68 @@ class PpmSearch { assetName = json['assetName']; } - num pageSize; - num pageNumber; - num id; - num assetId; - num modelId; - num ppmId; - num ppmScheduleId; - num classification; - num visitStatusId; - num deviceStatusId; - num groupLeaderReviewId; - String assignedEmployeeId; - bool hasAssignedEmployee; - num assignedToId; - String expectedDateFrom; - String expectedDateTo; - String actualDateFrom; - String actualDateTo; - num siteId; - String jobSheetNo; - num typeOfServiceId; - num planNumber; - bool notified; - bool mostRecent; - AssetGroup assetGroup; - num buildingId; - num floorId; - num roomId; - num departmentId; - String assetName; + num? pageSize; // Now nullable + num? pageNumber; // Now nullable + num? id; // Now nullable + num? assetId; // Now nullable + num? modelId; // Now nullable + num? ppmId; // Now nullable + num? ppmScheduleId; // Now nullable + num? classification; // Now nullable + num? visitStatusId; // Now nullable + num? deviceStatusId; // Now nullable + num? groupLeaderReviewId; // Now nullable + String? assignedEmployeeId; // Now nullable + bool? hasAssignedEmployee; // Now nullable + num? assignedToId; // Now nullable + String? expectedDateFrom; // Now nullable + String? expectedDateTo; // Now nullable + String? actualDateFrom; // Now nullable + String? actualDateTo; // Now nullable + num? siteId; // Now nullable + String? jobSheetNo; // Now nullable + num? typeOfServiceId; // Now nullable + num? planNumber; // Now nullable + bool? notified; // Now nullable + bool? mostRecent; // Now nullable + AssetGroup? assetGroup; // Now nullable + num? buildingId; // Now nullable + num? floorId; // Now nullable + num? roomId; // Now nullable + num? departmentId; // Now nullable + String? assetName; // Now nullable PpmSearch copyWith({ - num pageSize, - num pageNumber, - num id, - num assetId, - num modelId, - num ppmId, - num ppmScheduleId, - num classification, - num visitStatusId, - num deviceStatusId, - num groupLeaderReviewId, - String assignedEmployeeId, - bool hasAssignedEmployee, - num assignedToId, - String expectedDateFrom, - String expectedDateTo, - String actualDateFrom, - String actualDateTo, - num siteId, - String jobSheetNo, - num typeOfServiceId, - num planNumber, - bool notified, - bool mostRecent, - AssetGroup assetGroup, - num buildingId, - num floorId, - num roomId, - num departmentId, - String assetName, + num? pageSize, // All parameters are now nullable + num? pageNumber, + num? id, + num? assetId, + num? modelId, + num? ppmId, + num? ppmScheduleId, + num? classification, + num? visitStatusId, + num? deviceStatusId, + num? groupLeaderReviewId, + String? assignedEmployeeId, + bool? hasAssignedEmployee, + num? assignedToId, + String? expectedDateFrom, + String? expectedDateTo, + String? actualDateFrom, + String? actualDateTo, + num? siteId, + String? jobSheetNo, + num? typeOfServiceId, + num? planNumber, + bool? notified, + bool? mostRecent, + AssetGroup? assetGroup, + num? buildingId, + num? floorId, + num? roomId, + num? departmentId, + String? assetName, }) => PpmSearch( pageSize: pageSize ?? this.pageSize, @@ -190,7 +189,7 @@ class PpmSearch { map['notified'] = notified; map['mostRecent'] = mostRecent; if (assetGroup != null) { - map['assetGroup'] = assetGroup.toJson(); + map['assetGroup'] = assetGroup?.toJson(); // Use '?.' to handle potential null } map['buildingId'] = buildingId; map['floorId'] = floorId; @@ -199,4 +198,4 @@ class PpmSearch { map['assetName'] = assetName; return map; } -} +} \ No newline at end of file diff --git a/lib/models/search_all_requests_model.dart b/lib/models/search_all_requests_model.dart index e2b21950..78673d24 100644 --- a/lib/models/search_all_requests_model.dart +++ b/lib/models/search_all_requests_model.dart @@ -2,17 +2,17 @@ import 'package:flutter/cupertino.dart'; import 'package:test_sa/extensions/context_extension.dart'; class SearchAllRequestsModel { - SearchByRequestNumberModel requestNumber; - SearchByAssetNameModel assetName; - SearchByAssetNoModel assetNo; - SearchByManufactureModel manufacture; - SearchBySNModel sn; - SearchByRequestModel model; - SearchAllRequestsBaseModel searchBySelectedValue; - List statuses; - List typeTransaction; - DateTime startDate, endDate; - bool isArchived; + SearchByRequestNumberModel? requestNumber; // Now nullable + SearchByAssetNameModel? assetName; // Now nullable + SearchByAssetNoModel? assetNo; // Now nullable + SearchByManufactureModel? manufacture; // Now nullable + SearchBySNModel? sn; // Now nullable + SearchByRequestModel? model; // Now nullable + SearchAllRequestsBaseModel? searchBySelectedValue; // Now nullable + List? statuses; // Now nullable + List? typeTransaction; // Now nullable + DateTime? startDate, endDate; // Now nullable + bool isArchived = false; SearchAllRequestsModel({ this.requestNumber, @@ -30,7 +30,6 @@ class SearchAllRequestsModel { void resetSearchValues() { requestNumber?.controller?.text = ""; - requestNumber?.value = ""; assetName?.controller?.text = ""; assetNo?.controller?.text = ""; manufacture?.controller?.text = ""; @@ -41,35 +40,41 @@ class SearchAllRequestsModel { } abstract class SearchAllRequestsBaseModel { - String label; - String value; - BuildContext context; + String? label; // Now nullable + String? value; // Now nullable + BuildContext? context; // Now nullable TextInputType inputType; - TextEditingController controller; + TextEditingController? controller; // Now nullable SearchAllRequestsBaseModel(this.context, {this.controller, this.label, this.value, this.inputType = TextInputType.text}); } class SearchByRequestNumberModel extends SearchAllRequestsBaseModel { - SearchByRequestNumberModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: "${context.translation.requestNo}.", value: value); + SearchByRequestNumberModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: "${context.translation.requestNo}.", value: value); } class SearchByAssetNameModel extends SearchAllRequestsBaseModel { - SearchByAssetNameModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: context.translation.assetName, value: value); + SearchByAssetNameModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: context.translation.assetName, value: value); } class SearchByAssetNoModel extends SearchAllRequestsBaseModel { - SearchByAssetNoModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: context.translation.assetNo, value: value); + SearchByAssetNoModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: context.translation.assetNo, value: value); } class SearchByManufactureModel extends SearchAllRequestsBaseModel { - SearchByManufactureModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: context.translation.manufacture, value: value); + SearchByManufactureModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: context.translation.manufacture, value: value); } class SearchBySNModel extends SearchAllRequestsBaseModel { - SearchBySNModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: context.translation.sn, value: value); + SearchBySNModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: context.translation.sn, value: value); } class SearchByRequestModel extends SearchAllRequestsBaseModel { - SearchByRequestModel(BuildContext context, {TextEditingController controller, String value}) : super(context, controller: controller, label: context.translation.model, value: value); + SearchByRequestModel(BuildContext context, {TextEditingController? controller, String? value}) // Parameters now nullable + : super(context, controller: controller, label: context.translation.model, value: value); } diff --git a/lib/models/size_config.dart b/lib/models/size_config.dart index 53ed7381..80755e4c 100644 --- a/lib/models/size_config.dart +++ b/lib/models/size_config.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; abstract class SizeConfig { - static MediaQueryData _mediaQueryData; - static double screenWidth; - static double screenHeight; - static double defaultSize; + static late MediaQueryData _mediaQueryData; + static double? screenWidth; + static double? screenHeight; + static double? defaultSize; /// Call this method to save the height and width of the available layout static void init(BuildContext context) { diff --git a/lib/models/system_notification_model.dart b/lib/models/system_notification_model.dart index b6bb07aa..23154215 100644 --- a/lib/models/system_notification_model.dart +++ b/lib/models/system_notification_model.dart @@ -1,75 +1,92 @@ class SystemNotificationModel { - String userId; - String userName; - String title; - String text; - int referenceId; - int sourceId; - String sourceName; - bool readed; - String readingDate; - int id; - String createdOn; - String modifiedOn; - String priorityName; - String statusName; + String? userId; + String? userName; + String? title; + String? text; + int? referenceId; + int? sourceId; + String? sourceName; + bool? readed; + String? readingDate; + int? id; + String? createdOn; + String? modifiedOn; + String? priorityName; + String? statusName; SystemNotificationModel( - {this.userId, this.userName, this.title, this.text, this.referenceId, this.sourceId, this.sourceName, this.readed, this.readingDate, this.id, this.createdOn, this.modifiedOn, this.priorityName, this.statusName}); + {this.userId, + this.userName, + this.title, + this.text, + this.referenceId, + this.sourceId, + this.sourceName, + this.readed, + this.readingDate, + this.id, + this.createdOn, + this.modifiedOn, + this.priorityName, + this.statusName}); - SystemNotificationModel.fromJson(Map json) { - userId = json['userId']; - userName = json['userName']; - title = json['title']; - text = json['text']; - referenceId = json['referenceId']; - sourceId = json['sourceId']; - sourceName = json['sourceName']; - readed = json['readed']; - readingDate = json['readingDate']; - id = json['id']; - createdOn = json['createdOn']; - modifiedOn = json['modifiedOn']; - priorityName = json['priorityName']; - statusName = json['statusName']; + SystemNotificationModel.fromJson(Map? json) { + // Allow json to be null + if (json != null) { + // Add null check + userId = json['userId']; + userName = json['userName']; + title = json['title']; + text = json['text']; + referenceId = json['referenceId']; + sourceId = json['sourceId']; + sourceName = json['sourceName']; + readed = json['readed']; + readingDate = json['readingDate']; + id = json['id']; + createdOn = json['createdOn']; + modifiedOn = json['modifiedOn']; + priorityName = json['priorityName']; + statusName = json['statusName']; + } } Map toNotificationJson() { - final Map data = new Map(); - data['userId'] = this.userId; - data['userName'] = this.userName; - data['title'] = this.title; - data['text'] = this.text; - data['requestNumber'] = this.referenceId; - data['sourceId'] = this.sourceId; - data['requestType'] = this.sourceName; - data['readed'] = this.readed; - data['readingDate'] = this.readingDate; - data['id'] = this.id; - data['createdOn'] = this.createdOn; - data['modifiedOn'] = this.modifiedOn; - data['priorityName'] = this.priorityName; - data['priority'] = this.priorityName; - data['statusName'] = this.statusName; + final Map data = {}; // Use for type safety + data['userId'] = userId; + data['userName'] = userName; + data['title'] = title; + data['text'] = text; + data['requestNumber'] = referenceId; + data['sourceId'] = sourceId; + data['requestType'] = sourceName; + data['readed'] = readed; + data['readingDate'] = readingDate; + data['id'] = id; + data['createdOn'] = createdOn; + data['modifiedOn'] = modifiedOn; + data['priorityName'] = priorityName; + data['priority'] = priorityName; + data['statusName'] = statusName; return data; } Map toJson() { - final Map data = new Map(); - data['userId'] = this.userId; - data['userName'] = this.userName; - data['title'] = this.title; - data['text'] = this.text; - data['referenceId'] = this.referenceId; - data['sourceId'] = this.sourceId; - data['sourceName'] = this.sourceName; - data['readed'] = this.readed; - data['readingDate'] = this.readingDate; - data['id'] = this.id; - data['createdOn'] = this.createdOn; - data['modifiedOn'] = this.modifiedOn; - data['priorityName'] = this.priorityName; - data['statusName'] = this.statusName; + final Map data = {}; // Use for type safety + data['userId'] = userId; + data['userName'] = userName; + data['title'] = title; + data['text'] = text; + data['referenceId'] = referenceId; + data['sourceId'] = sourceId; + data['sourceName'] = sourceName; + data['readed'] = readed; + data['readingDate'] = readingDate; + data['id'] = id; + data['createdOn'] = createdOn; + data['modifiedOn'] = modifiedOn; + data['priorityName'] = priorityName; + data['statusName'] = statusName; return data; } } diff --git a/lib/models/timer_model.dart b/lib/models/timer_model.dart index a0854b47..93957ba0 100644 --- a/lib/models/timer_model.dart +++ b/lib/models/timer_model.dart @@ -1,7 +1,7 @@ class TimerModel { - DateTime startAt; - DateTime endAt; - int durationInSecond; + DateTime? startAt; + DateTime? endAt; + int? durationInSecond; // bool stopped; diff --git a/lib/models/user.dart b/lib/models/user.dart index eb9bcdbb..7745f0a2 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -2,38 +2,38 @@ import 'package:test_sa/controllers/notification/firebase_notification_manger.da import 'package:test_sa/models/enums/user_types.dart'; class User { - int clientId; - String clientName; - List departmentId; - List departmentName; - String message; - String username; - String userID; - String email; - String password; - String token; + int? clientId; + String? clientName; + List? departmentId; + List? departmentName; + String? message; + String? username; + String? userID; + String? email; + String? password; + String? token; dynamic roles; - List userRoles; - String tokenlife; - bool isAuthenticated; - bool hasError; - String profilePhotoName; - String id; - String userName; - String normalizedUserName; - String normalizedEmail; - bool emailConfirmed; + List? userRoles; + String? tokenlife; + bool? isAuthenticated; + bool? hasError; + String? profilePhotoName; + String? id; + String? userName; + String? normalizedUserName; + String? normalizedEmail; + bool? emailConfirmed; dynamic passwordHash; - String securityStamp; - String concurrencyStamp; - String phoneNumber; - String extensionNo; - bool phoneNumberConfirmed; - bool twoFactorEnabled; + String? securityStamp; + String? concurrencyStamp; + String? phoneNumber; + String? extensionNo; + bool? phoneNumberConfirmed; + bool? twoFactorEnabled; dynamic lockoutEnd; - bool lockoutEnabled; - int accessFailedCount; - List assetGroups; + bool? lockoutEnabled; + int? accessFailedCount; + List? assetGroups; User({ this.clientId, @@ -68,7 +68,7 @@ class User { this.accessFailedCount, }); - bool get isLiveToken => tokenlife != null && (DateTime.tryParse(tokenlife)?.isAfter(DateTime.now()) ?? false); + bool get isLiveToken => tokenlife != null && (DateTime.tryParse(tokenlife!)?.isAfter(DateTime.now()) ?? false); Future> toLoginJson() async { if (FirebaseNotificationManger.token == null) await FirebaseNotificationManger.getToken(); @@ -79,7 +79,7 @@ class User { }; } - UsersTypes get type { + UsersTypes? get type { switch (userRoles?.first?.value) { case "R-6": return UsersTypes.engineer; @@ -128,10 +128,10 @@ class User { map['token'] = token; map['roles'] = roles; if (userRoles != null) { - map['userRoles'] = userRoles.map((v) => v.toJson()).toList(); + map['userRoles'] = userRoles!.map((v) => v.toJson()).toList(); } if (assetGroups != null) { - map['assetGroups'] = assetGroups.map((v) => v.toJson()).toList(); + map['assetGroups'] = assetGroups!.map((v) => v.toJson()).toList(); } map['tokenlife'] = tokenlife; map['isAuthenticated'] = isAuthenticated; @@ -161,13 +161,13 @@ class User { if (json['department_id'] != null) { departmentId = []; json['department_id'].forEach((v) { - departmentId.add(v); + departmentId!.add(v); }); } if (json['department_name'] != null) { departmentName = []; json['department_name'].forEach((v) { - departmentName.add(v); + departmentName!.add(v); }); } message = json['message']; @@ -180,14 +180,14 @@ class User { if (json['userRoles'] != null) { userRoles = []; json['userRoles'].forEach((v) { - userRoles.add(UserRoles.fromJson(v)); + userRoles!.add(UserRoles.fromJson(v)); }); } if (json['assetGroups'] != null) { assetGroups = []; json['assetGroups'].forEach((v) { - assetGroups.add(AssetGroup.fromJson(v)); + assetGroups!.add(AssetGroup.fromJson(v)); }); } tokenlife = json['tokenlife']; @@ -213,6 +213,10 @@ class User { } class UserRoles { + String? id; + String? name; + String? value; + UserRoles({ this.id, this.name, @@ -225,14 +229,10 @@ class UserRoles { value = json['value']; } - String id; - String name; - String value; - UserRoles copyWith({ - String id, - String name, - String value, + String? id, + String? name, + String? value, }) => UserRoles( id: id ?? this.id, @@ -250,23 +250,27 @@ class UserRoles { } class AssetGroup { - int id; - String name; - String code; + int? id; + String? name; + String? code; AssetGroup({this.id, this.name, this.code}); - AssetGroup.fromJson(Map json) { - id = json['id']; - name = json['name']; - code = json['code']; + AssetGroup.fromJson(Map? json) { + // Allow json to be null + if (json != null) { + // Add null check + id = json['id']; + name = json['name']; + code = json['code']; + } } Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['name'] = this.name; - data['code'] = this.code; + final Map data = {}; // Use for type safety + data['id'] = id; + data['name'] = name; + data['code'] = code; return data; } } diff --git a/lib/new_views/common_widgets/single_item_drop_down_menu.dart b/lib/new_views/common_widgets/single_item_drop_down_menu.dart index d037fd06..9f2341c2 100644 --- a/lib/new_views/common_widgets/single_item_drop_down_menu.dart +++ b/lib/new_views/common_widgets/single_item_drop_down_menu.dart @@ -13,13 +13,13 @@ import '../app_style/app_color.dart'; class SingleItemDropDownMenu extends StatefulWidget { final BuildContext context; - final Function(T) onSelect; - final T initialValue; + final Function(T)? onSelect; + final T? initialValue; final bool enabled; final bool showAsBottomSheet; final List staticData; final String title; - final double height; + final double? height; final bool showShadow ; final Color backgroundColor; final bool loading; @@ -27,7 +27,7 @@ class SingleItemDropDownMenu /// To use a static data (without calling API) /// just send [NullableLoadingProvider] as generic data type and fill the [staticData] const SingleItemDropDownMenu({ - Key key, + Key? key, @required this.context, @required this.title, this.onSelect, @@ -48,8 +48,8 @@ class SingleItemDropDownMenu class _SingleItemDropDownMenuState extends State> { - T _selectedItem; - X provider; + T? _selectedItem; + X? provider; @override void initState() { @@ -164,10 +164,11 @@ class _SingleItemDropDownMenuState emp?.name ?? "", ), - )) as T; + )) as T?; if(_selectedT !=null) { widget.onSelect(_selectedT); } diff --git a/lib/views/pages/device_transfer/request_device_transfer.dart b/lib/views/pages/device_transfer/request_device_transfer.dart index 3312fd9d..543fe640 100644 --- a/lib/views/pages/device_transfer/request_device_transfer.dart +++ b/lib/views/pages/device_transfer/request_device_transfer.dart @@ -4,7 +4,6 @@ import 'package:test_sa/controllers/providers/api/asset_transfer_provider.dart'; import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_provider.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/controllers/providers/settings/setting_provider.dart'; -import 'package:test_sa/controllers/validator/validator.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; @@ -17,7 +16,6 @@ import 'package:test_sa/models/new_models/floor.dart'; import 'package:test_sa/models/new_models/room_model.dart'; import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/views/widgets/status/employee/nurse_menu.dart'; -import 'package:test_sa/views/widgets/status/nurse_employee_menu.dart'; import '../../../models/new_models/building.dart'; import '../../../models/new_models/site.dart'; @@ -38,17 +36,18 @@ class RequestDeviceTransfer extends StatefulWidget { } class _RequestDeviceTransferState extends State { - UserProvider _userProvider; - SettingProvider _settingProvider; - AssetTransferProvider _deviceTransferProvider; + UserProvider? _userProvider; + SettingProvider? _settingProvider; + AssetTransferProvider? _deviceTransferProvider; final TextEditingController _requestedQuantityController = TextEditingController(); final AssetTransfer _transferModel = AssetTransfer(); final GlobalKey _formKey = GlobalKey(); final GlobalKey _scaffoldKey = GlobalKey(); final TextEditingController _receiverNameController = TextEditingController(), _commentsController = TextEditingController(); final Asset _assetDestination = Asset(); - Asset _pickedAsset; - Employee receiverEndUser; + Asset? _pickedAsset; + Employee? receiverEndUser; + Employee? _selectedNurse; @override void setState(VoidCallback fn) { @@ -56,7 +55,7 @@ class _RequestDeviceTransferState extends State { } void _onSubmit() async { - _transferModel.assetId = _pickedAsset.id; + _transferModel.assetId = _pickedAsset?.id; _transferModel.destSiteId = _assetDestination.site?.id; _transferModel.destBuildingId = _assetDestination.building?.id; _transferModel.destFloorId = _assetDestination.floor?.id; @@ -73,14 +72,12 @@ class _RequestDeviceTransferState extends State { @override void dispose() { _requestedQuantityController.dispose(); - _deviceTransferProvider.reset(); + _deviceTransferProvider!.reset(); _receiverNameController.dispose(); _commentsController.dispose(); super.dispose(); } - Employee _selectedNurse; - @override Widget build(BuildContext context) { _userProvider = Provider.of(context, listen: false); @@ -121,7 +118,7 @@ class _RequestDeviceTransferState extends State { _assetDestination.floor = null; _assetDestination.department = null; _selectedNurse = null; - Provider.of(context, listen: false).siteId = value.id; + Provider.of(context, listen: false).siteId = value.id!.toInt(); Provider.of(context, listen: false).getData(); setState(() {}); }, @@ -182,7 +179,7 @@ class _RequestDeviceTransferState extends State { NurseMenu( title: context.translation.receiverName, initialValue: _selectedNurse, - enable: _assetDestination?.site != null, + enable: _assetDestination.site != null, onSelect: (employee) { if (employee != null) { _selectedNurse = employee; diff --git a/lib/views/widgets/app_text_form_field.dart b/lib/views/widgets/app_text_form_field.dart index 24ea9922..3341179a 100644 --- a/lib/views/widgets/app_text_form_field.dart +++ b/lib/views/widgets/app_text_form_field.dart @@ -1,49 +1,45 @@ import 'package:flutter/material.dart'; -import 'package:test_sa/views/app_style/sizing.dart'; - -class ATextFormField extends StatefulWidget { - final Function(String) onSaved; - final Function(String) validator; - final Function(String) onChange; - final bool obscureText; - final VoidCallback showPassword; - final String hintText; - final String labelText; +import 'package:test_sa/views/app_style/sizing.dart';class ATextFormField extends StatefulWidget { + final Function(String)? onSaved; + final String? Function(String?)? validator; + final Function(String)? onChange; + final bool? obscureText; + final VoidCallback? showPassword; + final String? hintText;final String? labelText; final TextInputType textInputType; - final String initialValue; - final TextStyle style; + final String? initialValue; + final TextStyle? style; final bool enable; - final TextAlign textAlign; - final FocusNode node; - final Widget suffixIcon; - final IconData prefixIconData; - final double prefixIconSize; - final TextEditingController controller; - final TextInputAction textInputAction; - final VoidCallback onAction; + final TextAlign? textAlign; + final FocusNode? node; + final Widget? suffixIcon; + final IconData? prefixIconData; + final double? prefixIconSize; + final TextEditingController? controller; + final TextInputAction? textInputAction; + final VoidCallback? onAction; - const ATextFormField( - {Key key, - this.onSaved, - this.validator, - this.node, - this.onChange, - this.obscureText, - this.showPassword, - this.hintText, - this.labelText, - this.textInputType = TextInputType.text, - this.initialValue, - this.enable = true, - this.style, - this.textAlign, - this.suffixIcon, - this.prefixIconData, - this.prefixIconSize, - this.controller, - this.textInputAction, - this.onAction}) - : super(key: key); + const ATextFormField({ + Key? key, + this.onSaved, + this.validator,this.node, + this.onChange, + this.obscureText, + this.showPassword, + this.hintText, + this.labelText, + this.textInputType = TextInputType.text, + this.initialValue, + this.enable = true, + this.style, + this.textAlign, + this.suffixIcon, + this.prefixIconData, + this.prefixIconSize, + this.controller, + this.textInputAction, + this.onAction, + }) : super(key: key); @override State createState() => _ATextFormFieldState(); @@ -52,30 +48,31 @@ class ATextFormField extends StatefulWidget { class _ATextFormFieldState extends State { @override void initState() { - if (widget.controller != null) widget.controller.text = widget.initialValue; + if (widget.controller != null && widget.initialValue != null) { + widget.controller!.text = widget.initialValue!; + } super.initState(); } @override Widget build(BuildContext context) { return Container( - height: widget.textInputType == TextInputType.multiline ? null : 50, - padding: EdgeInsets.only(left: 12, right: 12), + height: widget.textInputType == TextInputType.multiline ? null : 50,padding: const EdgeInsets.only(left: 12, right: 12), decoration: BoxDecoration( - color: Color(0xfff5f5f5), + color: const Color(0xfff5f5f5), border: Border.all( - color: Color(0xffefefef), + color: const Color(0xffefefef), ), borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)), ), child: TextFormField( focusNode: widget.node, enabled: widget.enable, - onSaved: widget.onSaved, + //onSaved: widget.onSaved, initialValue: widget.controller != null ? null : widget.initialValue, validator: widget.validator, onChanged: widget.onChange, - textAlign: TextAlign.left, + textAlign: widget.textAlign ?? TextAlign.left, obscureText: widget.obscureText ?? false, keyboardType: widget.textInputType, maxLines: widget.textInputType == TextInputType.multiline ? null : 1, @@ -83,25 +80,27 @@ class _ATextFormFieldState extends State { controller: widget.controller, textInputAction: widget.textInputType == TextInputType.multiline ? null : widget.textInputAction ?? TextInputAction.next, onEditingComplete: widget.onAction ?? () => FocusScope.of(context).nextFocus(), - // style: widget.style, - style: Theme.of(context).textTheme.bodyText1, + style: widget.style ?? Theme.of(context).textTheme.bodyLarge, decoration: InputDecoration( - border: InputBorder.none, - suffixIconConstraints: BoxConstraints(minWidth: 0), - disabledBorder: InputBorder.none, - focusedBorder: InputBorder.none, - enabledBorder: InputBorder.none, - constraints: BoxConstraints(), - errorStyle: TextStyle(height: 0.3), - //contentPadding: EdgeInsets.only(left: 0), - hintText: widget.hintText, - labelText: widget.labelText, - //suffixIcon: widget.suffixIcon, - suffixIcon: widget.prefixIconData == null - ? null - : Icon(widget.prefixIconData, - size: widget.prefixIconSize == null ? 20 * AppStyle.getScaleFactor(context) : (widget.prefixIconSize - 10) * AppStyle.getScaleFactor(context), color: Color(0xff2e303a))), + border: InputBorder.none, + suffixIconConstraints: const BoxConstraints(minWidth: 0), + disabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + enabledBorder: InputBorder.none, + constraints: const BoxConstraints(), + errorStyle: const TextStyle(height: 0.3), + hintText: widget.hintText, + labelText: widget.labelText, + suffixIcon: widget.suffixIcon, + prefixIcon: widget.prefixIconData == null + ? null + : Icon( + widget.prefixIconData, + size: widget.prefixIconSize == null ? 20 * AppStyle.getScaleFactor(context) : (widget.prefixIconSize! - 10) * AppStyle.getScaleFactor(context), + color: const Color(0xff2e303a), + ), + ), ), ); } -} +} \ No newline at end of file diff --git a/lib/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart b/lib/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart index 55a69da3..e39d85e9 100644 --- a/lib/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart +++ b/lib/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart @@ -8,9 +8,9 @@ import 'package:test_sa/models/device/asset.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; class AssetDetailBottomSheet extends StatelessWidget { - Asset asset; + Asset? asset; - AssetDetailBottomSheet(this.asset, {Key key}) : super(key: key); + AssetDetailBottomSheet(this.asset, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -32,7 +32,7 @@ class AssetDetailBottomSheet extends StatelessWidget { ), image: DecorationImage( fit: BoxFit.cover, - image: NetworkImage(asset?.assetPhoto != null ? URLs.getFileUrl(asset.assetPhoto) : "https://www.lasteelcraft.com/images/no-image-available.png"), + image: NetworkImage(asset?.assetPhoto != null ? URLs.getFileUrl(asset!.assetPhoto)! : "https://www.lasteelcraft.com/images/no-image-available.png"), )), ), ), @@ -47,10 +47,10 @@ class AssetDetailBottomSheet extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "${context.translation.assetNo}: ${asset.assetNumber}".bodyText(context), - "${context.translation.modelName}: ${asset.modelDefinition.modelName}".bodyText(context), - "${context.translation.supplier}: ${asset.supplier?.suppliername?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), - "${context.translation.manufacture}: ${asset.modelDefinition.manufacturerName?.cleanupWhitespace?.capitalizeFirstOfEach}".bodyText(context), + "${context.translation.assetNo}: ${asset!.assetNumber}".bodyText(context), + "${context.translation.modelName}: ${asset!.modelDefinition!.modelName}".bodyText(context), + "${context.translation.supplier}: ${asset!.supplier?.suppliername?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context), + "${context.translation.manufacture}: ${asset!.modelDefinition!.manufacturerName?.cleanupWhitespace.capitalizeFirstOfEach}".bodyText(context), //"${context.translation.location}: ${assetModel.site.custName?.cleanupWhitespace?.capitalizeFirstOfEach}".bodyText(context), ], ).expanded, @@ -58,22 +58,22 @@ class AssetDetailBottomSheet extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - "${context.translation.snNo}: ${asset.assetSerialNo}".bodyText(context), - "${context.translation.site}: ${asset?.site?.custName?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), - "${context.translation.building}: ${asset?.building?.name?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), - "${context.translation.floor}: ${asset?.floor?.name?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), - "${context.translation.md}: ${asset?.department?.departmentName?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), + "${context.translation.snNo}: ${asset!.assetSerialNo}".bodyText(context), + "${context.translation.site}: ${asset?.site?.custName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context), + "${context.translation.building}: ${asset?.building?.name?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context), + "${context.translation.floor}: ${asset?.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context), + "${context.translation.md}: ${asset?.department?.departmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context), "${context.translation.room}: ${asset?.room?.value ?? "-"}".bodyText(context), ], ).expanded, ], ), 8.height, - if ((asset.modelDefinition.assetDescription ?? "").isNotEmpty) ...[ + if ((asset?.modelDefinition?.assetDescription ?? "").isNotEmpty) ...[ 8.height, const Divider(color: AppColor.neutral30, height: 1, thickness: 1), 8.height, - asset.modelDefinition.assetDescription.bodyText(context), + asset!.modelDefinition!.assetDescription!.bodyText(context), ] ], ) diff --git a/lib/views/widgets/bottom_sheets/pending_request_bottom_sheet.dart b/lib/views/widgets/bottom_sheets/pending_request_bottom_sheet.dart index d7e1f1d5..0b5fd66e 100644 --- a/lib/views/widgets/bottom_sheets/pending_request_bottom_sheet.dart +++ b/lib/views/widgets/bottom_sheets/pending_request_bottom_sheet.dart @@ -12,7 +12,7 @@ class PendingRequestBottomSheet extends StatelessWidget { final PendingAssetServiceRequest pendingAssetServiceRequest; final Asset device; - PendingRequestBottomSheet(this.pendingAssetServiceRequest, this.device, {Key key}) : super(key: key); + PendingRequestBottomSheet(this.pendingAssetServiceRequest, this.device, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/views/widgets/bottom_sheets/selection_bottom_sheet.dart b/lib/views/widgets/bottom_sheets/selection_bottom_sheet.dart index 7a7fcf77..35622c21 100644 --- a/lib/views/widgets/bottom_sheets/selection_bottom_sheet.dart +++ b/lib/views/widgets/bottom_sheets/selection_bottom_sheet.dart @@ -1,34 +1,30 @@ import 'package:flutter/material.dart'; import 'package:test_sa/extensions/context_extension.dart'; -import 'package:test_sa/extensions/int_extensions.dart'; +import'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; -import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; typedef SelectionBuilderString = String Function(dynamic); class SelectionBottomSheet extends StatefulWidget { - List items; - T selectedItem; - String title; - + final List items; + final T? selectedItem; // Now nullable + final String title; final SelectionBuilderString builderString; - SelectionBottomSheet({Key key, this.items = const [], this.selectedItem, this.title = "", @required this.builderString}) : super(key: key); + const SelectionBottomSheet({Key? key, this.items = const [], this.selectedItem, this.title = "", required this.builderString}) : super(key: key); @override - _SelectionBottomSheetState createState() { - return _SelectionBottomSheetState(); - } + _SelectionBottomSheetState createState() => _SelectionBottomSheetState(); } -class _SelectionBottomSheetState extends State { - T _selectedValue; +class _SelectionBottomSheetState extends State> { + T? _selectedValue; // Now nullable String query = ""; - List get filteredList => widget.items.where((element) => element.name.toString().toLowerCase().contains(query.toLowerCase())).toList(); + List get filteredList => widget.items.where((element) => widget.builderString(element).toLowerCase().contains(query.toLowerCase())).toList(); @override void initState() { @@ -40,6 +36,7 @@ class _SelectionBottomSheetState extends State { @override void dispose() { + searchFocusNode.dispose(); super.dispose(); } @@ -58,50 +55,57 @@ class _SelectionBottomSheetState extends State { query = queryString; setState(() {}); }, - style: TextStyle(fontSize: 14), + style: const TextStyle(fontSize: 14), focusNode: searchFocusNode, decoration: InputDecoration( hintText: 'Search by name', labelText: 'Search', - hintStyle: TextStyle(fontSize: 14), + hintStyle: const TextStyle(fontSize: 14), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: AppColor.blueStatus(context), width: 2.0), - borderRadius: BorderRadius.all(Radius.circular(12.0)), + borderRadius: const BorderRadius.all(Radius.circular(12.0)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: AppColor.blueStatus(context), width: 1.0), - borderRadius: BorderRadius.all(Radius.circular(12.0)), + borderRadius: const BorderRadius.all(Radius.circular(12.0)), ), - contentPadding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), + contentPadding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), ), ), 8.height, - ListView.builder( + Expanded( + // Wrap ListView with Expanded + child: ListView.builder( itemCount: filteredList.length, - padding: EdgeInsets.only(top: 8), - itemBuilder: (cxt, index) => RadioListTile( - value: filteredList[index], - dense: true, - contentPadding: EdgeInsets.zero, - groupValue: _selectedValue, - activeColor: Colors.black87, - onChanged: (value) { - _selectedValue = value; - searchFocusNode.unfocus(); - setState(() {}); - }, - title: Text( - widget.builderString(filteredList[index]).cleanupWhitespace?.capitalizeFirstOfEach ?? "", - style: Theme.of(context).textTheme.bodyLarge, - ))).expanded, + padding: const EdgeInsets.only(top: 8), + itemBuilder: (cxt, index) => RadioListTile( + // Specify type for RadioListTile + value: filteredList[index], + dense: true, + contentPadding: EdgeInsets.zero, + groupValue: _selectedValue, + activeColor: Colors.black87, + onChanged: (value) { + _selectedValue = value; + searchFocusNode.unfocus(); + setState(() {}); + }, + title: Text( + widget.builderString(filteredList[index]).cleanupWhitespace?.capitalizeFirstOfEach ?? "", + style: Theme.of(context).textTheme.bodyLarge, + ), + ), + ), + ), 8.height, if (_selectedValue != null) AppFilledButton( - label: context.translation.select, - maxWidth: true, - onPressed: () { - Navigator.pop(context, _selectedValue); - }), + label: context.translation.select, + maxWidth: true, + onPressed: () { + Navigator.pop(context, _selectedValue); + }, + ), ], ), ); diff --git a/lib/views/widgets/equipment/pick_asset.dart b/lib/views/widgets/equipment/pick_asset.dart index 080db07d..fb543d02 100644 --- a/lib/views/widgets/equipment/pick_asset.dart +++ b/lib/views/widgets/equipment/pick_asset.dart @@ -11,12 +11,12 @@ import '../../../new_views/common_widgets/asset_info_card.dart'; class PickAsset extends StatelessWidget { final Function(Asset) onPickAsset; - final Asset device; + final Asset? device; // Now nullable final bool editable; final bool showAssetInfo; final bool forPPM; - const PickAsset({Key key, this.editable = true, this.device, this.onPickAsset, this.showAssetInfo = true, this.forPPM = false}) : super(key: key); + const PickAsset({Key? key, this.editable = true, this.device, required this.onPickAsset, this.showAssetInfo = true, this.forPPM = false}) : super(key: key); @override Widget build(BuildContext context) { @@ -32,21 +32,24 @@ class PickAsset extends StatelessWidget { padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight), child: Row( children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - context.translation.device.tinyFont(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), - if (device != null) - device.assetNumber.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50) - else - context.translation.pickAsset.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), - ], - ).onPress(() async { - Asset device = await Navigator.of(context).pushNamed(MyAssetsPage.id) as Asset; - if (device != null) { - onPickAsset(device); - } - }).expanded, + Expanded( + // Wrap the Column with Expanded + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + context.translation.device.tinyFont(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), + if (device != null) + device!.assetNumber.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50) + else + context.translation.pickAsset.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), + ], + ).onPress(() async { + final selectedDevice = await Navigator.of(context).pushNamed(MyAssetsPage.id) as Asset?; + if (selectedDevice != null) { + onPickAsset(selectedDevice); + } + }), + ), if (device != null) Icon(Icons.change_circle_rounded, size: 22, color: context.isDark ? AppColor.primary40 : AppColor.primary70) else @@ -54,7 +57,7 @@ class PickAsset extends StatelessWidget { ], ), ), - if (device != null && showAssetInfo) AssetInfoCard(asset: device).paddingOnly(top: 8), + if (device != null && showAssetInfo) AssetInfoCard(asset: device!).paddingOnly(top: 8), ], ); } diff --git a/lib/views/widgets/horizontal_list_widget.dart b/lib/views/widgets/horizontal_list_widget.dart index 5a506a7d..886a56e1 100644 --- a/lib/views/widgets/horizontal_list_widget.dart +++ b/lib/views/widgets/horizontal_list_widget.dart @@ -7,7 +7,7 @@ import 'package:test_sa/extensions/widget_extensions.dart'; import '../../new_views/app_style/app_color.dart'; class HorizontalListWidget extends StatefulWidget { - const HorizontalListWidget({Key key, @required this.list,this.callBackFunction}) : super(key: key); + const HorizontalListWidget({Key? key, required this.list, required this.callBackFunction}) : super(key: key); final List list; final Function(int index) callBackFunction; @@ -26,7 +26,7 @@ class _HorizontalListWidgetState extends State { itemCount: widget.list.length, scrollDirection: Axis.horizontal, shrinkWrap: true, - padding: EdgeInsetsDirectional.only(start: 16.toScreenWidth,end: 16), + padding: EdgeInsetsDirectional.only(start: 16.toScreenWidth, end: 16), itemBuilder: (context, index) => Container( margin: EdgeInsets.symmetric(horizontal: 4.toScreenWidth), padding: EdgeInsets.symmetric(horizontal: 20.toScreenWidth), diff --git a/lib/views/widgets/loaders/loading_manager.dart b/lib/views/widgets/loaders/loading_manager.dart index 4f2b2216..d908df41 100644 --- a/lib/views/widgets/loaders/loading_manager.dart +++ b/lib/views/widgets/loaders/loading_manager.dart @@ -9,20 +9,18 @@ class LoadingManager extends StatefulWidget { final bool isLoading; final bool isFailedLoading; final bool isNotPage; - final int progress; final bool askOnBack; - final int stateCode; + final int? stateCode; final Future Function() onRefresh; final Widget child; LoadingManager({ - Key key, - @required this.isLoading, - @required this.isFailedLoading, - @required this.stateCode, - @required this.onRefresh, - @required this.child, - this.progress, + Key? key, + required this.isLoading, + required this.isFailedLoading, + required this.stateCode, + required this.onRefresh, + required this.child, this.isNotPage = false, this.askOnBack = false, }) : super(key: key); @@ -44,7 +42,7 @@ class _LoadingManagerState extends State { @override Widget build(BuildContext context) { - Widget placeHolder; + Widget? placeHolder; // to load data if load not start if (widget.isLoading != true && widget.stateCode == null) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) { diff --git a/lib/views/widgets/sound/record_sound.dart b/lib/views/widgets/sound/record_sound.dart index c02e9922..20152b63 100644 --- a/lib/views/widgets/sound/record_sound.dart +++ b/lib/views/widgets/sound/record_sound.dart @@ -6,7 +6,7 @@ import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; -import 'package:record_mp3/record_mp3.dart'; +import 'package:record_mp3_plus/record_mp3_plus.dart'; import 'package:rive/rive.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; @@ -18,11 +18,11 @@ import '../../../new_views/app_style/app_color.dart'; import '../../../new_views/common_widgets/app_text_form_field.dart'; class RecordSound extends StatefulWidget { - final Function(String) onRecord; - final Function(String) onStop; + final Function(String?) onRecord; + final Function(String)? onStop; final bool enabled; - const RecordSound({Key key, @required this.onRecord, this.onStop, this.enabled = true}) : super(key: key); + const RecordSound({Key? key, required this.onRecord, this.onStop, this.enabled = true}) : super(key: key); @override State createState() => _RecordSoundState(); @@ -34,10 +34,10 @@ class _RecordSoundState extends State { bool _recorderIsOpened = false; bool _recording = false; bool _played = false; - String _record; - Artboard _rive; - Timer _timer; - TextEditingController _timeController; + String? _record; + late Artboard _rive; + Timer? _timer; + late TextEditingController _timeController; FocusNode node = FocusNode(); @@ -89,7 +89,7 @@ class _RecordSoundState extends State { super.dispose(); } - String recordingFileDirectory; + late String recordingFileDirectory; _startRecording() async { PermissionStatus status = await Permission.microphone.request(); @@ -102,10 +102,10 @@ class _RecordSoundState extends State { } _timer = Timer.periodic(const Duration(seconds: 1), (timer) { setState(() { - String duration = Duration(seconds: timer?.tick).toString(); + String duration = Duration(seconds: timer.tick).toString(); duration = duration.substring(duration.indexOf(":") + 1, duration.indexOf(".")); - String recordTime = ((timer?.tick ?? 0) / 60)?.toStringAsFixed(2)?.replaceFirst(".", ":"); + String recordTime = ((timer.tick) / 60).toStringAsFixed(2).replaceFirst(".", ":"); // print("recordTime:$recordTime"); if (recordTime.length == 4 || recordTime.length == 7) { recordTime = "0$recordTime"; @@ -136,7 +136,7 @@ class _RecordSoundState extends State { return; } if (_timer?.isActive ?? false) { - _timer.cancel(); + _timer?.cancel(); } RecordMp3.instance.stop(); @@ -174,7 +174,7 @@ class _RecordSoundState extends State { node: node, controller: _timeController, labelText: context.translation.recordVoice, - initialValue: (_timeController?.text?.isEmpty ?? true) ? "00:00" : _timeController?.text, + initialValue: (_timeController.text.isEmpty) ? "00:00" : _timeController.text, suffixIcon: (_recording ? "record".toLottieAsset(height: 24) : (_record != null ? "trash" : "mic").toSvgAsset(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, height: 24)) .paddingOnly(end: 16), @@ -194,7 +194,7 @@ class _RecordSoundState extends State { ], ), if (_record != null) 8.height, - if (_record != null) ASoundPlayer(audio: _record), + if (_record != null) ASoundPlayer(audio: _record!), ], ); } diff --git a/lib/views/widgets/status/assistant_employee_menu.dart b/lib/views/widgets/status/assistant_employee_menu.dart index 521982d0..12db70bf 100644 --- a/lib/views/widgets/status/assistant_employee_menu.dart +++ b/lib/views/widgets/status/assistant_employee_menu.dart @@ -1,139 +1,130 @@ import 'package:flutter/material.dart'; import 'package:test_sa/extensions/context_extension.dart'; -import 'package:test_sa/extensions/int_extensions.dart'; +import'package:test_sa/extensions/int_extensions.dart'; import '../../../models/new_models/assistant_employee.dart'; import '../../../new_views/app_style/app_color.dart'; class AssistantEmployeeMenu extends StatefulWidget { final List statuses; - final AssistantEmployees initialStatus; - final Function(AssistantEmployees) onSelect; - final String title; + final AssistantEmployees? initialStatus; // Now nullable + final Function(AssistantEmployees?) onSelect; // Now accepts nullable values + final String? title; // Now nullable final bool enable; - const AssistantEmployeeMenu({Key key, this.statuses, this.title, this.onSelect, this.initialStatus, this.enable = true}) : super(key: key); + const AssistantEmployeeMenu({Key? key, required this.statuses, this.title, required this.onSelect, this.initialStatus, this.enable = true}) : super(key: key); @override _SingleAssistantEmployeeMenuState createState() => _SingleAssistantEmployeeMenuState(); } -class _SingleAssistantEmployeeMenuState extends State { - AssistantEmployees _selectedStatus; +class _SingleAssistantEmployeeMenuState extends State {AssistantEmployees? _selectedStatus; // Now nullable - @override - void setState(VoidCallback fn) { - if (mounted) super.setState(fn); - } +@override +void setState(VoidCallback fn) { + if (mounted) super.setState(fn); +} - @override - void didUpdateWidget(covariant AssistantEmployeeMenu oldWidget) { - if (widget.initialStatus != null) { - final result = widget.statuses?.where((element) { - return element?.user?.id == widget.initialStatus?.user?.id; - }); - if (result.isNotEmpty) { - _selectedStatus = result.first; - } else { - _selectedStatus = null; - } - if ((widget.initialStatus?.user?.id ?? "") != (_selectedStatus?.user?.id ?? "")) { - widget.onSelect(_selectedStatus); - } +@override +void didUpdateWidget(covariant AssistantEmployeeMenu oldWidget) { + if (widget.initialStatus != null) { + final result = widget.statuses.where((element) => element.user?.id == widget.initialStatus?.user?.id); + if (result.isNotEmpty) { + _selectedStatus = result.first; } else { _selectedStatus = null; } - super.didUpdateWidget(oldWidget); + if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) { + widget.onSelect(_selectedStatus); + } + } else { + _selectedStatus = null; } + super.didUpdateWidget(oldWidget); +} - @override - void initState() { - if (widget.initialStatus != null) { - final result = widget.statuses?.where((element) { - return element?.user?.id == widget.initialStatus?.user?.id; - }); - if (result.isNotEmpty) _selectedStatus = result.first; - if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) { - widget.onSelect(_selectedStatus); - } +@override +void initState() { + if (widget.initialStatus != null) { + final result = widget.statuses.where((element) => element.user?.id == widget.initialStatus?.user?.id); + if (result.isNotEmpty) { + _selectedStatus = result.first; + } + if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) { + widget.onSelect(_selectedStatus); } - - super.initState(); } + super.initState(); +} - @override - Widget build(BuildContext context) { - return Container( - height: 60.toScreenHeight, - padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), - decoration: BoxDecoration( - color: context.isDark ? AppColor.neutral50 : Colors.white, - borderRadius: BorderRadius.circular(10), - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)], - ), - child: Stack( - alignment: Alignment.center, - children: [ - PositionedDirectional( - end: 0, - child: Icon( - Icons.keyboard_arrow_down_rounded, - color: widget.enable ? null : Colors.grey, - )), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - if (widget.title != null) - Text( - widget.title, - style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), - ), - DropdownButton( - value: _selectedStatus, - iconSize: 24, - isDense: true, - icon: const SizedBox.shrink(), - elevation: 0, - isExpanded: true, - hint: Text( - context.translation.select, - style: Theme.of(context).textTheme.bodyLarge, - ), - style: TextStyle(color: Theme.of(context).primaryColor), - underline: const SizedBox.shrink(), - - onChanged: widget.enable - ? (AssistantEmployees newValue) { - setState(() { - _selectedStatus = newValue; - }); - widget.onSelect(newValue); - } - : null, - - // onChanged: (AssistantEmployees newValue) { - // setState(() { - // _selectedStatus = newValue; - // }); - // widget.onSelect(newValue); - // }, - items: widget.statuses.map>((AssistantEmployees value) { +@override +Widget build(BuildContext context) { + return Container( + height: 60.toScreenHeight, + padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), + decoration: BoxDecoration( + color: context.isDark ? AppColor.neutral50 : Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)], + ), + child: Stack( + alignment: Alignment.center, + children: [ + PositionedDirectional( + end: 0, + child: Icon( + Icons.keyboard_arrow_down_rounded, + color: widget.enable ? null : Colors.grey, + ), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (widget.title != null) + Text( + widget.title!, // Non-null assertion after null check + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), + ), + DropdownButton( + value: _selectedStatus, + iconSize: 24, + isDense: true, + icon: const SizedBox.shrink(), + elevation: 0, + isExpanded: true, + hint: Text( + context.translation.select, + style: Theme.of(context).textTheme.bodyLarge, + ), + style: TextStyle(color: Theme.of(context).primaryColor), + underline: const SizedBox.shrink(), + onChanged: widget.enable + ? (AssistantEmployees? newValue) { // Now accepts nullable values + setState(() { + _selectedStatus = newValue; + }); + widget.onSelect(newValue); + } + :null, + items: widget.statuses.map>( + (AssistantEmployees value) { return DropdownMenuItem( value: value, child: Text( - value.user?.name ?? "NULL", - style: Theme.of(context).textTheme.bodyLarge.copyWith( - color: widget.enable ? Theme.of(context).primaryColor : Colors.grey, - ), + value.user?.name ?? "NULL", // Use null-aware operator for user.name + style: Theme.of(context).textTheme.bodyLarge?.copyWith( + color: widget.enable ? Theme.of(context).primaryColor : Colors.grey, + ), ), ); - }).toList(), - ), - ], - ), - ], - ), - ); - } + }, + ).toList(), + ), + ], + ), + ], + ), + ); } +} \ No newline at end of file diff --git a/lib/views/widgets/status/employee/nurse_menu.dart b/lib/views/widgets/status/employee/nurse_menu.dart index 0b723286..7822de14 100644 --- a/lib/views/widgets/status/employee/nurse_menu.dart +++ b/lib/views/widgets/status/employee/nurse_menu.dart @@ -2,43 +2,38 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_provider.dart'; import 'package:test_sa/models/employee.dart'; -import 'package:test_sa/models/new_models/assistant_employee.dart'; -import 'package:test_sa/models/service_request/search_work_order.dart'; import 'package:test_sa/views/widgets/loaders/loading_manager.dart'; -import 'package:test_sa/views/widgets/status/assistant_employee_menu.dart'; import 'package:test_sa/views/widgets/status/nurse_employee_menu.dart'; -import '../../../../controllers/providers/api/status_drop_down/report/service_report_assistants_employee_provider.dart'; - class NurseMenu extends StatelessWidget { - final Function(Employee) onSelect; - final Employee initialValue; + final Function(Employee?) onSelect; // Now accepts nullable Employee + final Employee? initialValue; // Now nullable - final String title; + final String title; // Now nullable final bool enable; - final int siteId; + final int? siteId; // Now nullable - const NurseMenu({Key key, @required this.onSelect, this.title, this.initialValue, this.enable = true, this.siteId}) : super(key: key); + const NurseMenu({Key? key, required this.onSelect, required this.title, this.initialValue, this.enable = true, this.siteId}) : super(key: key); @override Widget build(BuildContext context) { - NurseProvider menuProvider = Provider.of(context); - menuProvider.siteId = siteId; + final menuProvider = Provider.of(context, listen: false); + if (siteId != null) { + menuProvider.siteId = siteId!; + } return LoadingManager( isLoading: menuProvider.isLoading, isFailedLoading: menuProvider.nursesList == null, stateCode: menuProvider.stateCode, - onRefresh: () async { - await menuProvider.getData(); - // menuProvider.setStateCode = null; - }, + onRefresh: menuProvider.getData, + // Directly pass the getData method child: NurseEmployeeMenu( initialValue: initialValue, title: title, - list: menuProvider.nursesList, - onSelect: (employee) { - onSelect(employee); - }, + list: menuProvider.nursesList ?? [], + // Provide an empty list if null + onSelect: onSelect, + // Pass the onSelect function directly enable: enable, ), ); diff --git a/lib/views/widgets/status/nurse_employee_menu.dart b/lib/views/widgets/status/nurse_employee_menu.dart index 0d2c91d2..816a7271 100644 --- a/lib/views/widgets/status/nurse_employee_menu.dart +++ b/lib/views/widgets/status/nurse_employee_menu.dart @@ -6,24 +6,23 @@ import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/employee.dart'; import 'package:test_sa/views/widgets/bottom_sheets/selection_bottom_sheet.dart'; -import '../../../models/new_models/assistant_employee.dart'; import '../../../new_views/app_style/app_color.dart'; class NurseEmployeeMenu extends StatefulWidget { - final List list; - final Employee initialValue; - final Function(Employee) onSelect; + final List? list; + final Employee? initialValue; + final Function(Employee?) onSelect; final String title; - final bool enable; + final bool? enable; - const NurseEmployeeMenu({Key key, this.list, this.title, this.onSelect, this.initialValue, this.enable = true}) : super(key: key); + const NurseEmployeeMenu({Key? key, this.list, required this.title, required this.onSelect, this.initialValue, this.enable = true}) : super(key: key); @override _SingleNurseEmployeeMenuState createState() => _SingleNurseEmployeeMenuState(); } class _SingleNurseEmployeeMenuState extends State { - Employee _selectedStatus; + Employee? _selectedStatus; @override void setState(VoidCallback fn) { @@ -34,15 +33,16 @@ class _SingleNurseEmployeeMenuState extends State { void didUpdateWidget(covariant NurseEmployeeMenu oldWidget) { if (widget.initialValue != null) { final result = widget.list?.where((element) { - return element?.id == widget.initialValue?.id; - }); + return element.id == widget.initialValue?.id; + }) ?? + []; if (result.isNotEmpty) { _selectedStatus = result.first; } else { _selectedStatus = null; } if ((widget.initialValue?.id ?? "") != (_selectedStatus?.id ?? "")) { - widget.onSelect(_selectedStatus); + widget.onSelect!(_selectedStatus!); } } else { _selectedStatus = null; @@ -54,8 +54,9 @@ class _SingleNurseEmployeeMenuState extends State { void initState() { if (widget.initialValue != null) { final result = widget.list?.where((element) { - return element?.id == widget.initialValue?.id; - }); + return element.id == widget.initialValue?.id; + }) ?? + []; if (result.isNotEmpty) _selectedStatus = result.first; if (widget.initialValue?.id != _selectedStatus?.id) { widget.onSelect(_selectedStatus); @@ -87,17 +88,16 @@ class _SingleNurseEmployeeMenuState extends State { end: 0, child: Icon( Icons.keyboard_arrow_down_rounded, - color: widget.enable ? null : Colors.grey, + color: widget.enable == null ? null : Colors.grey, )), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - if (widget.title != null) - Text( - widget.title, - style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), - ), + Text( + widget.title, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), + ), Text( _selectedStatus?.name?.cleanupWhitespace?.capitalizeFirstOfEach ?? context.translation.select, style: Theme.of(context).textTheme.bodyLarge, @@ -106,7 +106,7 @@ class _SingleNurseEmployeeMenuState extends State { ), ], ), - ).onPress(widget.enable + ).onPress(((widget.enable ?? false) ? () async { _selectedStatus = (await showModalBottomSheet( context: context, @@ -118,15 +118,15 @@ class _SingleNurseEmployeeMenuState extends State { ), clipBehavior: Clip.antiAliasWithSaveLayer, builder: (BuildContext context) => SelectionBottomSheet( - items: widget.list, + items: widget.list ?? [], selectedItem: _selectedStatus, title: widget.title, builderString: (emp) => emp?.name ?? "", ), - )) as Employee; + )) as Employee?; if (_selectedStatus != null) setState(() {}); - widget.onSelect(_selectedStatus); + widget.onSelect(_selectedStatus!); } - : null); + : null)); } } diff --git a/lib/views/widgets/status/report/service_report_assistant_employee_menu.dart b/lib/views/widgets/status/report/service_report_assistant_employee_menu.dart index 2c355c16..46fa6714 100644 --- a/lib/views/widgets/status/report/service_report_assistant_employee_menu.dart +++ b/lib/views/widgets/status/report/service_report_assistant_employee_menu.dart @@ -8,37 +8,30 @@ import 'package:test_sa/views/widgets/status/assistant_employee_menu.dart'; import '../../../../controllers/providers/api/status_drop_down/report/service_report_assistants_employee_provider.dart'; class ServiceReportAssistantEmployeeMenu extends StatelessWidget { - final Function(AssistantEmployees) onSelect; - final AssistantEmployees initialValue; + final Function(AssistantEmployees?) onSelect; + final AssistantEmployees? initialValue; // Now nullable final String title; final num assetId; final bool enable; - const ServiceReportAssistantEmployeeMenu({Key key, @required this.onSelect, this.title, this.initialValue, this.assetId, this.enable = true}) : super(key: key); + const ServiceReportAssistantEmployeeMenu({Key? key, required this.onSelect, required this.title, required this.initialValue, required this.assetId, this.enable = true}) : super(key: key); @override Widget build(BuildContext context) { - ServiceReportAssistantsEmployeeProvider menuProvider = Provider.of(context); + final menuProvider = Provider.of(context); return LoadingManager( isLoading: menuProvider.isLoading, isFailedLoading: menuProvider.assistantEmployees == null, stateCode: menuProvider.stateCode, onRefresh: () async { await menuProvider.getAssistantEmployees(assetId); - // menuProvider.setStateCode = null; }, child: AssistantEmployeeMenu( initialStatus: initialValue, title: title, - statuses: menuProvider.assistantEmployees, - onSelect: (employee) { - if (employee.id == -1) { - onSelect(null); - } else { - onSelect(employee); - } - }, + statuses: menuProvider.assistantEmployees ?? [], // Provide an empty list if null + onSelect: onSelect, // Pass onSelect directly enable: enable, ), ); diff --git a/lib/views/widgets/status/report/service_report_fault_description.dart b/lib/views/widgets/status/report/service_report_fault_description.dart index d9e5970b..c54dea9c 100644 --- a/lib/views/widgets/status/report/service_report_fault_description.dart +++ b/lib/views/widgets/status/report/service_report_fault_description.dart @@ -10,28 +10,28 @@ import 'package:test_sa/providers/loading_list_notifier.dart'; import 'package:test_sa/views/widgets/loaders/loading_manager.dart'; class ServiceReportFaultDescription extends StatefulWidget { - final String requestId; - final Function(FaultDescription) onSelect; - final FaultDescription initialValue; + final String? requestId; // Now nullable + final Function(FaultDescription)? onSelect; // Now nullable + final FaultDescription? initialValue; // Now nullable - const ServiceReportFaultDescription({Key key, this.requestId, this.onSelect, this.initialValue}) : super(key: key); + const ServiceReportFaultDescription({Key? key, this.requestId, this.onSelect, this.initialValue}) : super(key: key); @override State createState() => _ServiceReportFaultDescriptionState(); } class _ServiceReportFaultDescriptionState extends State { - FaultDescription initialValue; + FaultDescription? initialValue; @override void initState() { super.initState(); initialValue = widget.initialValue; - if (widget.initialValue == null) { - WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((timeStamp) { + if (widget.initialValue == null && widget.requestId != null) { + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { ServiceRequestFaultDescriptionProvider menuProvider = Provider.of(context, listen: false); menuProvider.reset(); - menuProvider.getCallRequestForWorkOrder(requestId: widget.requestId); + menuProvider.getCallRequestForWorkOrder(widget.requestId!); // Non-null assertion since requestId is checked for null }); } } @@ -48,29 +48,28 @@ class _ServiceReportFaultDescriptionState extends State(context); - UserProvider userProvider = Provider.of(context); - ServiceRequestFaultDescriptionProvider menuProvider = Provider.of(context); + final settingProvider = Provider.of(context); + final userProvider = Provider.of(context); + final menuProvider = Provider.of(context); return LoadingManager( isLoading: menuProvider.isLoading, isFailedLoading: menuProvider.items == null, stateCode: menuProvider.stateCode, onRefresh: () async { - menuProvider.reset(); - await menuProvider.getCallRequestForWorkOrder(user: userProvider.user, host: settingProvider.host, requestId: widget.requestId); + if (widget.requestId != null) { + // Add null check for requestId + menuProvider.reset(); + await menuProvider.getCallRequestForWorkOrder(widget.requestId!); // Non-null assertion since requestId is checked for null + } }, child: SingleItemDropDownMenu( context: context, title: context.translation.faultDescription, onSelect: widget.onSelect, + // Pass onSelect directly initialValue: initialValue, staticData: menuProvider.items ?? [], ), - // child: FaultDescriptionMenu( - // initialStatus: initialValue, - // statuses: menuProvider.items ?? [], - // onSelect: onSelect, - // ), ); } } diff --git a/lib/views/widgets/timer/app_timer.dart b/lib/views/widgets/timer/app_timer.dart index 55bf230c..06c627b2 100644 --- a/lib/views/widgets/timer/app_timer.dart +++ b/lib/views/widgets/timer/app_timer.dart @@ -11,17 +11,17 @@ import 'package:test_sa/views/app_style/sizing.dart'; import '../../../new_views/app_style/app_color.dart'; class AppTimer extends StatefulWidget { - final TimerModel timer; - final Future Function(TimerModel) onChange; - final TextStyle style; - final BoxDecoration decoration; + final TimerModel? timer; + final Future Function(TimerModel)? onChange; + final TextStyle? style; + final BoxDecoration? decoration; final bool enabled; - final String label; + final String? label; - final Function(bool) timerProgress; + final Function(bool)? timerProgress; const AppTimer({ - Key key, + Key? key, this.label, this.timer, this.onChange, @@ -36,46 +36,48 @@ class AppTimer extends StatefulWidget { } class _AppTimerState extends State { - Timer _timer; - DateTime _startAt; - DateTime _endAt; + Timer? _timer; + DateTime? _startAt; + DateTime? _endAt; int _delay = 0; bool _running = false; bool _loading = false; final ValueNotifier _period = ValueNotifier("0:00:00"); - _startTimer() async { - if (!_running) { + Future _startTimer() async { + if (!_running && widget.onChange != null) { final time = DateTime.now(); - bool result = await widget.onChange(TimerModel(startAt: time, endAt: null, durationInSecond: _delay)); + bool result = await widget.onChange!(TimerModel(startAt: time, endAt: null, durationInSecond: _delay)); if (!result) return; _running = true; if (_endAt != null) { - _delay += _endAt.difference(_startAt).inSeconds; + _delay += _endAt!.difference(_startAt!).inSeconds; } _startAt = time.subtract(Duration(seconds: _delay)); _endAt = null; } _timer = Timer.periodic(const Duration(seconds: 1), (timer) { - if (_loading == true) return; - _period.value = (_endAt ?? DateTime.now()).difference(_startAt).toString().split(".").first; + if (_loading) return; + _period.value = (_endAt ?? DateTime.now()).difference(_startAt!).toString().split(".").first; }); } - _stopTimer() async { - final time = DateTime.now(); - final tempStartAt = _startAt.add(Duration(seconds: _delay)); - bool result = await widget.onChange(TimerModel(startAt: tempStartAt, endAt: time, durationInSecond: _delay)); - if (!result) return; - _running = false; - _endAt = time; - _startAt = tempStartAt; - _timer?.cancel(); + Future _stopTimer() async { + if (widget.onChange != null) { + final time = DateTime.now(); + final tempStartAt = _startAt!.add(Duration(seconds: _delay)); + bool result = await widget.onChange!(TimerModel(startAt: tempStartAt, endAt: time, durationInSecond: _delay)); + if (!result) return; + _running = false; + _endAt = time; + _startAt = tempStartAt; + _timer?.cancel(); + } } - _onPressed() async { + Future _onPressed() async { _loading = true; setState(() {}); if (!_running) { @@ -85,7 +87,7 @@ class _AppTimerState extends State { } _loading = false; setState(() {}); - //widget.timerProgress(_running); + //widget.timerProgress?(_running); // Use null-aware operator to call timerProgress } @override @@ -93,8 +95,8 @@ class _AppTimerState extends State { _startAt = widget.timer?.startAt; _endAt = widget.timer?.endAt; _running = _startAt != null && _endAt == null; - _delay = (widget.timer?.durationInSecond ?? 0); - final difference = _startAt == null ? 0 : (_endAt ?? DateTime.now())?.difference(_startAt)?.inSeconds ?? 0; + _delay = widget.timer?.durationInSecond ?? 0; + final difference = _startAt == null ? 0 : (_endAt ?? DateTime.now()).difference(_startAt!).inSeconds; _period.value = Duration(seconds: _running ? difference : (difference != 0 ? difference : _delay)).toString().split(".").first; super.initState(); if (_running) { @@ -104,6 +106,7 @@ class _AppTimerState extends State { @override void dispose() { + _timer?.cancel(); // Cancel the timer when the widget is disposed super.dispose(); } @@ -113,15 +116,16 @@ class _AppTimerState extends State { width: 100 * AppStyle.getScaleFactor(context), height: 56.toScreenHeight, padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), - decoration:widget.decoration?? BoxDecoration( - color: context.isDark && (widget.enabled == false) - ? AppColor.neutral60 - : (widget.enabled == false) - ? AppColor.neutral40 - : AppColor.background(context), - borderRadius: BorderRadius.circular(10), - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)], - ), + decoration: widget.decoration ?? + BoxDecoration( + color: context.isDark && !widget.enabled + ? AppColor.neutral60 + : !widget.enabled + ? AppColor.neutral40 + : AppColor.background(context), + borderRadius: BorderRadius.circular(10), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)], + ), child: _loading ? const SizedBox.square(dimension: 18, child: CircularProgressIndicator(color: Colors.white)) : Row( @@ -150,6 +154,6 @@ class _AppTimerState extends State { if (widget.enabled) Icon(_running ? Icons.pause : Icons.play_arrow), ], ), - ).onPress(_loading || widget.enabled == false ? () {} : _onPressed); + ).onPress(_loading || !widget.enabled ? null : _onPressed); } } diff --git a/lib/views/widgets/titles/app_sub_title.dart b/lib/views/widgets/titles/app_sub_title.dart index 4dc839cb..579909a6 100644 --- a/lib/views/widgets/titles/app_sub_title.dart +++ b/lib/views/widgets/titles/app_sub_title.dart @@ -1,26 +1,26 @@ -import 'package:flutter/material.dart'; -import 'package:test_sa/views/app_style/sizing.dart'; - -class ASubTitle extends StatelessWidget { - final String text; - final EdgeInsets padding; - final Color color; - final double font; - - const ASubTitle(this.text, {Key key, this.padding, this.color, this.font}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Padding( - padding: padding ?? EdgeInsets.zero, - child: Text( - text, - style: Theme.of(context).textTheme.bodyText1.copyWith( - // fontWeight: FontWeight.bold, - fontSize: font, - color: color), - textScaleFactor: AppStyle.getScaleFactor(context), - ), - ); - } -} +// import 'package:flutter/material.dart'; +// import 'package:test_sa/views/app_style/sizing.dart'; +// +// class ASubTitle extends StatelessWidget { +// final String text; +// final EdgeInsets padding; +// final Color color; +// final double font; +// +// const ASubTitle(this.text, {Key key, this.padding, this.color, this.font}) : super(key: key); +// +// @override +// Widget build(BuildContext context) { +// return Padding( +// padding: padding ?? EdgeInsets.zero, +// child: Text( +// text, +// style: Theme.of(context).textTheme.bodyLarge?.copyWith( +// // fontWeight: FontWeight.bold, +// fontSize: font, +// color: color), +// textScaleFactor: AppStyle.getScaleFactor(context), +// ), +// ); +// } +// } diff --git a/pubspec.lock b/pubspec.lock index 0fdf4ad9..bdc00476 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -37,10 +37,10 @@ packages: dependency: transitive description: name: async - sha256: bfe67ef28df125b7dddcea62755991f807aa39a2492a23e1550161692950bbe0 + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted - version: "2.10.0" + version: "2.11.0" audioplayers: dependency: "direct main" description: @@ -149,10 +149,10 @@ packages: dependency: transitive description: name: characters - sha256: e6a326c8af69605aec75ed6c187d06b349707a27fbff8222ca9cc2cff167975c + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.3.0" checked_yaml: dependency: transitive description: @@ -181,10 +181,10 @@ packages: dependency: transitive description: name: collection - sha256: cfc915e6923fe5ce6e153b0723c753045de46de1b4d63771530504004a45fae0 + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.18.0" convert: dependency: transitive description: @@ -382,6 +382,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.3.1" + flutter_custom_month_picker: + dependency: "direct main" + description: + name: flutter_custom_month_picker + sha256: c287dc6bac11fe8625ecf48dae64cb8b59d9f0ce01b9d58b72f50e5545c076f5 + url: "https://pub.dev" + source: hosted + version: "0.1.3" flutter_keyboard_visibility: dependency: transitive description: @@ -475,14 +483,6 @@ packages: description: flutter source: sdk version: "0.0.0" - flutter_month_picker: - dependency: "direct main" - description: - name: flutter_month_picker - sha256: "745ee1eb3aba5cd5ed99f9ffaf97083d9d13944b24b8ab33e31dac0ea997219b" - url: "https://pub.dev" - source: hosted - version: "0.0.2" flutter_plugin_android_lifecycle: dependency: transitive description: @@ -557,6 +557,14 @@ packages: url: "https://pub.dev" source: hosted version: "10.4.0" + get: + dependency: transitive + description: + name: get + sha256: e4e7335ede17452b391ed3b2ede016545706c01a02292a6c97619705e7d2a85e + url: "https://pub.dev" + source: hosted + version: "4.6.6" graphs: dependency: transitive description: @@ -681,10 +689,10 @@ packages: dependency: "direct main" description: name: intl - sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" + sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" url: "https://pub.dev" source: hosted - version: "0.17.0" + version: "0.18.1" js: dependency: transitive description: @@ -777,26 +785,26 @@ packages: dependency: transitive description: name: matcher - sha256: "16db949ceee371e9b99d22f88fa3a73c4e59fd0afed0bd25fc336eb76c198b72" + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted - version: "0.12.13" + version: "0.12.16" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "0.5.0" meta: dependency: transitive description: name: meta - sha256: "6c268b42ed578a53088d834796959e4a1814b5e9e164f147f580a386e5decf42" + sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e url: "https://pub.dev" source: hosted - version: "1.8.0" + version: "1.10.0" mime: dependency: transitive description: @@ -841,10 +849,10 @@ packages: dependency: transitive description: name: path - sha256: db9d4f58c908a4ba5953fcee2ae317c94889433e5024c27ce74a37f94267945b + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted - version: "1.8.2" + version: "1.8.3" path_drawing: dependency: transitive description: @@ -1037,14 +1045,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.0" - record_mp3: + record_mp3_plus: dependency: "direct main" description: - name: record_mp3 - sha256: "2da2cd2f8c053f9ff03388019bc3eff035ef72f8ea8efac24674c5e528a1cc68" + name: record_mp3_plus + sha256: bf0b3f3ed96227a289ddf71605eb5370e5d43b8a2c17429ec55e60ace03d76e9 url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "1.2.0" rive: dependency: "direct main" description: @@ -1158,10 +1166,10 @@ packages: dependency: transitive description: name: source_span - sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.10.0" speech_to_text: dependency: "direct main" description: @@ -1206,18 +1214,18 @@ packages: dependency: transitive description: name: stack_trace - sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.11.1" stream_channel: dependency: transitive description: name: stream_channel - sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" string_scanner: dependency: transitive description: @@ -1254,10 +1262,10 @@ packages: dependency: "direct main" description: name: table_calendar - sha256: "7f1270313c0cdb245b583ed8518982c01d4a7e95869b3c30abcbae3b642c45d0" + sha256: "1e3521a3e6d3fc7f645a58b135ab663d458ab12504f1ea7f9b4b81d47086c478" url: "https://pub.dev" source: hosted - version: "3.0.8" + version: "3.0.9" term_glyph: dependency: transitive description: @@ -1270,10 +1278,10 @@ packages: dependency: transitive description: name: test_api - sha256: ad540f65f92caa91bf21dfc8ffb8c589d6e4dc0c2267818b4cc2792857706206 + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted - version: "0.4.16" + version: "0.6.1" timezone: dependency: transitive description: @@ -1282,14 +1290,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.9.2" - touchable: - dependency: "direct main" - description: - name: touchable - sha256: "659dc6395f6256c20ef994a692527ea33c756e4e94f58017050687acd307d17f" - url: "https://pub.dev" - source: hosted - version: "0.2.1" typed_data: dependency: transitive description: @@ -1386,6 +1386,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.4" + web: + dependency: transitive + description: + name: web + sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 + url: "https://pub.dev" + source: hosted + version: "0.3.0" win32: dependency: transitive description: @@ -1419,5 +1427,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=2.19.0 <3.0.0" - flutter: ">=3.7.0" + dart: ">=3.2.0-194.0.dev <4.0.0" + flutter: ">=3.16.0" diff --git a/pubspec.yaml b/pubspec.yaml index f79dc6ee..76c63561 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,7 +18,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.2.2+9 environment: - sdk: ">=2.7.0 <3.0.0" + sdk: ">=2.12.0 <4.0.0" localization_dir: assets\translations @@ -50,7 +50,7 @@ dependencies: flutter_local_notifications: ^12.0.1+1 cached_network_image: ^3.2.2 carousel_slider: ^4.1.1 - intl: ^0.17.0 + intl: ^0.18.0 flutter_typeahead: ^4.1.1 speech_to_text: ^6.1.1 firebase_core: ^2.4.0 @@ -66,7 +66,7 @@ dependencies: signature: ^5.3.0 flutter_svg: ^1.1.6 file_picker: ^5.2.5 - record_mp3: ^2.1.0 + record_mp3_plus: any path_provider: ^2.1.0 open_file: ^3.3.2 localization: ^2.1.0 @@ -76,10 +76,10 @@ dependencies: flutter_advanced_switch: ^3.0.1 table_calendar: ^3.0.8 image_cropper: ^3.0.3 - touchable: ^0.2.1 + badges: ^3.1.1 # buttons_tabbar: ^1.1.2 - flutter_month_picker: ^0.0.2 + flutter_custom_month_picker: ^0.1.3 syncfusion_flutter_charts: ^21.2.3 local_auth: ^2.1.6