sdk upgrade changes.

design_3.0_demo_module
Sikander Saleem 2 years ago
parent d5ee12abbb
commit 7d0a2eb65c

@ -27,6 +27,6 @@ subprojects {
project.evaluationDependsOn(':app') project.evaluationDependsOn(':app')
} }
task clean(type: Delete) { tasks.register("clean", Delete) {
delete rootProject.buildDir delete rootProject.buildDir
} }

@ -3,10 +3,10 @@ import 'package:meta/meta.dart';
class HttpStatusManger { class HttpStatusManger {
static String getStatusMessage({ static String getStatusMessage({
@required int status, required int? status,
@required AppLocalizations subtitle, required AppLocalizations subtitle,
String messageFor400, String? messageFor400,
String messageFor200, String? messageFor200,
}) { }) {
if (status == null) if (status == null)
// no status code - code error no need for subtitle // no status code - code error no need for subtitle

@ -11,7 +11,7 @@ class URLs {
set host(String value) => _host = value; 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"); // 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 getSingleServiceRequest => "$_baseUrl/return/call/information"; // get
static get getSuppliersAutoComplete => "$_baseUrl/Supplier/GetSuppliersAutoComplete"; static get getSuppliersAutoComplete => "$_baseUrl/Supplier/GetSuppliersAutoComplete";
static get addSupplierEngineer => "$_baseUrl/Supplier/AddSupplierEngineer"; static get addSupplierEngineer => "$_baseUrl/Supplier/AddSupplierEngineer";
static get getSystemNotifications => "$_baseUrl/SystemNotification/GetSystemNotifications"; // get static get getSystemNotifications => "$_baseUrl/SystemNotification/GetSystemNotifications"; // get

@ -18,7 +18,7 @@ Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {}
class FirebaseNotificationManger { class FirebaseNotificationManger {
static FirebaseMessaging messaging = FirebaseMessaging.instance; static FirebaseMessaging messaging = FirebaseMessaging.instance;
static String token; static String? token;
static Future<String> getToken() async { static Future<String> getToken() async {
NotificationSettings settings = await messaging.requestPermission( NotificationSettings settings = await messaging.requestPermission(
@ -37,12 +37,12 @@ class FirebaseNotificationManger {
} catch (ex) {} } catch (ex) {}
} }
print("pushToken:$token"); print("pushToken:$token");
return token; return token!;
} }
static void handleMessage(context, Map<String, dynamic> messageData) { static void handleMessage(context, Map<String, dynamic> messageData) {
if (messageData["requestType"] != null && messageData["requestNumber"] != null) { if (messageData["requestType"] != null && messageData["requestNumber"] != null) {
Widget serviceClass; Widget? serviceClass;
if (messageData["requestType"] == "Service request to engineer") { if (messageData["requestType"] == "Service request to engineer") {
serviceClass = ServiceRequestDetailsPage(serviceRequest: ServiceRequest(id: messageData["requestNumber"].toString())); serviceClass = ServiceRequestDetailsPage(serviceRequest: ServiceRequest(id: messageData["requestNumber"].toString()));
@ -66,7 +66,7 @@ class FirebaseNotificationManger {
// } // }
if (serviceClass != null) { 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) { FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (Platform.isAndroid) { if (Platform.isAndroid) {
NotificationManger.showNotification( 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; return;

@ -9,7 +9,7 @@ class NotificationManger {
// private constructor to avoid create object // private constructor to avoid create object
NotificationManger._(); NotificationManger._();
static FlutterLocalNotificationsPlugin localNotificationsPlugin; //= FlutterLocalNotificationsPlugin(); static late FlutterLocalNotificationsPlugin localNotificationsPlugin; //= FlutterLocalNotificationsPlugin();
/// initialisation setting for all platform /// initialisation setting for all platform
/// onNotificationPressed action when notification pressed to open tap /// onNotificationPressed action when notification pressed to open tap
@ -31,8 +31,8 @@ class NotificationManger {
if (Platform.isIOS) { if (Platform.isIOS) {
await localNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true, badge: true, sound: true); await localNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true, badge: true, sound: true);
} else if (Platform.isAndroid) { } else if (Platform.isAndroid) {
AndroidFlutterLocalNotificationsPlugin androidImplementation = localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>(); AndroidFlutterLocalNotificationsPlugin? androidImplementation = localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
bool granted = await androidImplementation?.requestPermission(); bool? granted = await androidImplementation?.requestPermission();
granted = granted ?? false; granted = granted ?? false;
if (granted == false) { if (granted == false) {
if (kDebugMode) { if (kDebugMode) {
@ -50,7 +50,7 @@ class NotificationManger {
// push new notificationBuildContext // 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( const AndroidNotificationDetails androidChannel = AndroidNotificationDetails(
'com.hmg.atoms', 'com.hmg.atoms',
'ATOMS', 'ATOMS',

@ -11,7 +11,6 @@ import 'package:test_sa/models/device/asset_transfer.dart';
import 'package:test_sa/models/user.dart'; import 'package:test_sa/models/user.dart';
import '../../../models/hospital.dart'; import '../../../models/hospital.dart';
import '../../../models/ppm/ppm.dart';
import '../../../new_views/common_widgets/app_lazy_loading.dart'; import '../../../new_views/common_widgets/app_lazy_loading.dart';
class AssetTransferProvider extends ChangeNotifier { class AssetTransferProvider extends ChangeNotifier {
@ -37,26 +36,26 @@ class AssetTransferProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int stateCode; int? stateCode;
// true if there is next page in product list and false if not // true if there is next page in product list and false if not
bool nextPage = true; bool nextPage = true;
// list of user requests // list of user requests
List<AssetTransfer> items; List<AssetTransfer>? items;
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
Hospital hospital; Hospital? hospital;
Buildings building; Buildings? building;
Floors floor; Floors? floor;
Departments department; Departments? department;
String room; String room = "";
DateTime startDate; DateTime? startDate;
DateTime endDate; DateTime? endDate;
/// return -2 if request in progress /// return -2 if request in progress
/// return -1if error happen when sending request /// return -1if error happen when sending request
@ -64,13 +63,13 @@ class AssetTransferProvider extends ChangeNotifier {
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getRequests({ Future<int> getRequests({
@required String host, required String host,
@required User user, required User user,
}) async { }) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
if (items?.isEmpty ?? true) notifyListeners(); if (items?.isEmpty ?? true) notifyListeners();
Response response; late Response response;
try { try {
Map<String, dynamic> body = {}; Map<String, dynamic> body = {};
body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1; body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
@ -80,12 +79,12 @@ class AssetTransferProvider extends ChangeNotifier {
response = await ApiManager.instance.post(URLs.getDeviceTransfer, body: body); response = await ApiManager.instance.post(URLs.getDeviceTransfer, body: body);
stateCode = response.statusCode; stateCode = response.statusCode;
if (stateCode >= 200 && stateCode < 300) { if (stateCode! >= 200 && stateCode! < 300) {
// client's request was successfully received // client's request was successfully received
List listJson = json.decode(response.body)["data"]; List listJson = json.decode(response.body)["data"];
List<AssetTransfer> itemsPage = listJson.map((request) => AssetTransfer.fromJson(request)).toList(); List<AssetTransfer> itemsPage = listJson.map((request) => AssetTransfer.fromJson(request)).toList();
items ??= []; items ??= [];
items.addAll(itemsPage.toSet().toList()); items!.addAll(itemsPage.toSet().toList());
notifyListeners(); notifyListeners();
if (itemsPage.length == pageItemNumber) { if (itemsPage.length == pageItemNumber) {
nextPage = true; nextPage = true;
@ -104,7 +103,7 @@ class AssetTransferProvider extends ChangeNotifier {
} }
} }
Future<AssetTransfer> getRequestById({int assetTransferId}) async { Future<AssetTransfer?> getRequestById({int? assetTransferId}) async {
Response response; Response response;
try { try {
response = await ApiManager.instance.get( response = await ApiManager.instance.get(
@ -122,18 +121,18 @@ class AssetTransferProvider extends ChangeNotifier {
} }
Future<void> createRequest({ Future<void> createRequest({
@required BuildContext context, required BuildContext context,
@required AssetTransfer assetDestination, required AssetTransfer assetDestination,
@required Asset asset, required Asset asset,
}) async { }) async {
Response response; Response response;
try { 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)); response = await ApiManager.instance.post(URLs.requestDeviceTransfer, body: assetDestination.transferBody(asset: asset));
stateCode = response.statusCode; stateCode = response.statusCode;
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
if (items != null) { 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(); reset();
notifyListeners(); notifyListeners();
} }
@ -149,10 +148,10 @@ class AssetTransferProvider extends ChangeNotifier {
} }
} }
Future<int> updateRequest(BuildContext context, {@required AssetTransfer assetTransfer, @required bool isSender}) async { Future<int> updateRequest(BuildContext context, {required AssetTransfer assetTransfer, required bool isSender}) async {
Response response; Response response;
try { 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()); response = await ApiManager.instance.put(URLs.updateDeviceTransfer, body: assetTransfer.toJson());
//print(response.body); //print(response.body);
@ -185,8 +184,8 @@ class AssetTransferProvider extends ChangeNotifier {
} }
} }
bool _isLocalUrl(String url) { bool _isLocalUrl(String? url) {
if (url?.isEmpty != false) return false; if (url?.isEmpty ?? true) return false;
return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); return url!.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
} }
} }

@ -24,7 +24,7 @@ class CommentsProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
//500 service not available //500 service not available
int stateCode; int? stateCode;
// true if there is next page in product list and false if not // true if there is next page in product list and false if not
bool nextPage = true; bool nextPage = true;
@ -35,18 +35,18 @@ class CommentsProvider extends ChangeNotifier {
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
/// return -2 if request in progress /// return -2 if request in progress
/// return -1 if error happen when sending request /// return -1 if error happen when sending request
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getComments({@required String callId}) async { Future<int> getComments({required String callId}) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
response = await ApiManager.instance.get(URLs.getComments + "?callRequestId=$callId"); 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 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> addComment(BuildContext context, {@required Comment comment}) async { Future<int> addComment(BuildContext context, {required Comment comment}) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
Response response; late Response response;
try { try {
comment.id = 0; 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()); response = await ApiManager.instance.post(URLs.addComment, body: comment.toJson());
stateCode = response.statusCode; stateCode = response.statusCode;

@ -1,4 +1,3 @@
///check deleted
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
@ -17,16 +16,16 @@ class DepartmentsProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int stateCode; int? stateCode;
// contain user data // contain user data
// when user not login or register _user = null // when user not login or register _user = null
List<Department> departments; List<Department>? departments;
// when categories in-process _loading = true // when categories in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
/// return -2 if request in progress /// return -2 if request in progress
/// return -1 if error happen when sending request /// return -1 if error happen when sending request
@ -37,7 +36,7 @@ class DepartmentsProvider extends ChangeNotifier {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
response = await ApiManager.instance.post(URLs.getDepartments, body: { response = await ApiManager.instance.post(URLs.getDepartments, body: {
"pageSize": 50, "pageSize": 50,

@ -30,39 +30,40 @@ class AssetProvider extends ChangeNotifier {
bool nextPage = true; 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<Asset> _devices = []; List<Asset> _devices = [];
List<Asset> _searchDevices = []; List<Asset> _searchDevices = [];
List<Asset> get devices => _devices; List<Asset> get devices => _devices;
List<Asset> get searchDevices => _searchDevices; List<Asset> get searchDevices => _searchDevices;
// when categories in-process _loading = true // when categories in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool _loading; bool _loading = false;
bool get isLoading => _loading; bool get isLoading => _loading;
AssetByIdModel _assetById; AssetByIdModel? _assetById;
AssetByIdModel get assetById => _assetById; AssetByIdModel? get assetById => _assetById;
set isLoading(bool isLoading) { set isLoading(bool isLoading) {
_loading = isLoading; _loading = isLoading;
notifyListeners(); notifyListeners();
} }
Future<int> getAssets({AssetSearch search, bool isQr = false, bool isSearchBy = false}) async { Future<int> getAssets({AssetSearch? search, bool isQr = false, bool isSearchBy = false}) async {
if (_loading == true) return -2; if (_loading == true) return -2;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
final Map<String, dynamic> body = { final Map<String, dynamic> body = {
"pageSize": isSearchBy ? searchPageItemNumber : pageItemNumber, "pageSize": isSearchBy ? searchPageItemNumber : pageItemNumber,
@ -99,7 +100,7 @@ class AssetProvider extends ChangeNotifier {
} }
Future<AssetByIdModel> getAssetById(int assetId, AppLocalizations appLocalizations) async { Future<AssetByIdModel> getAssetById(int assetId, AppLocalizations appLocalizations) async {
Response response; late Response response;
try { try {
response = await ApiManager.instance.get(URLs.getAssetById + "$assetId"); response = await ApiManager.instance.get(URLs.getAssetById + "$assetId");
} catch (error) { } catch (error) {
@ -111,21 +112,21 @@ class AssetProvider extends ChangeNotifier {
// client's request was successfully received // client's request was successfully received
Map<String, dynamic> assetData = json.decode(response.body)["data"]; Map<String, dynamic> assetData = json.decode(response.body)["data"];
_assetById = AssetByIdModel.fromJson(assetData); _assetById = AssetByIdModel.fromJson(assetData);
return _assetById; return _assetById!;
} }
throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: appLocalizations)); throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: appLocalizations));
} }
Future<List<Asset>> getDevicesList({ Future<List<Asset>> getDevicesList({
@required String host, required String host,
@required User user, required User user,
@required int hospitalId, required int hospitalId,
// String serialNumber, // String serialNumber,
// String number, // String number,
bool addPagination = true, bool addPagination = true,
AssetSearch search, AssetSearch? search,
}) async { }) async {
Response response; late Response response;
try { try {
Map<String, dynamic> body = { Map<String, dynamic> body = {
// "pageSize": pageItemNumber, // "pageSize": pageItemNumber,
@ -162,13 +163,11 @@ class AssetProvider extends ChangeNotifier {
} }
Future<List<Lookup>> getModels({ Future<List<Lookup>> getModels({
String code, String? code,
}) async { }) async {
Response response; late Response response;
try { try {
response = await ApiManager.instance.get( response = await ApiManager.instance.get(URLs.getModels + "?code=${code ?? ""}");
URLs.getModels + "?code=$code",
);
List<Lookup> page = []; List<Lookup> page = [];
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
// client's request was successfully received // client's request was successfully received
@ -186,32 +185,4 @@ class AssetProvider extends ChangeNotifier {
return []; 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<List<Device>> 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<Device> _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 [];
// }
// }
} }

@ -22,9 +22,8 @@ class GasRefillCommentsProvider extends ChangeNotifier {
} }
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed// 500 service not available
// 500 service not available int? stateCode;
int stateCode;
// true if there is next page in product list and false if not // true if there is next page in product list and false if not
bool nextPage = true; bool nextPage = true;
@ -35,18 +34,18 @@ class GasRefillCommentsProvider extends ChangeNotifier {
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
/// return -2 if request in progress /// return -2 if request in progress
/// return -1 if error happen when sending request /// return -1 if error happen when sending request
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getComments({@required String callId}) async { Future<int> getComments({required String callId}) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
response = await ApiManager.instance.get(URLs.getGazRefillComments + "?gasRefillId=$callId"); response = await ApiManager.instance.get(URLs.getGazRefillComments + "?gasRefillId=$callId");
@ -57,7 +56,7 @@ class GasRefillCommentsProvider extends ChangeNotifier {
comments ??= []; comments ??= [];
comments.addAll(commentsPage); comments.addAll(commentsPage);
comments.sort((a, b) { comments.sort((a, b) {
return b.createdOn.compareTo(a.createdOn); return b.createdOn!.compareTo(a.createdOn!);
}); });
if (commentsPage.length == pageItemNumber) { if (commentsPage.length == pageItemNumber) {
nextPage = true; nextPage = true;
@ -82,12 +81,12 @@ class GasRefillCommentsProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> addComment(BuildContext context, {@required String comment, int id}) async { Future<int> addComment(BuildContext context, {required String comment, required int id}) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
Response response; late Response response;
try { 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}); response = await ApiManager.instance.post(URLs.addGazRefillComment, body: {"id": 0, "gasRefillId": id, "comment": comment});
stateCode = response.statusCode; stateCode = response.statusCode;

@ -31,20 +31,20 @@ class GasRefillProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int stateCode; int? stateCode;
// true if there is next page in product list and false if not // true if there is next page in product list and false if not
bool nextPage = true; bool nextPage = true;
// list of user requests // list of user requests
List<GasRefillModel> items; List<GasRefillModel>? items;
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
Future<GasRefillModel> getGasRefillObjectById(num id) async { Future<GasRefillModel?> getGasRefillObjectById(num id) async {
try { try {
Response response = await ApiManager.instance.get(URLs.getGasRefillById + "?gazRefillId=$id"); Response response = await ApiManager.instance.get(URLs.getGasRefillById + "?gazRefillId=$id");
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
@ -63,14 +63,14 @@ class GasRefillProvider extends ChangeNotifier {
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getRequests({ Future<int> getRequests({
@required String host, required String host,
@required User user, required User user,
@required bool mostRecent, required bool mostRecent,
}) async { }) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
if (items?.isEmpty ?? true) notifyListeners(); if (items?.isEmpty ?? true) notifyListeners();
Response response; late Response response;
Map<String, dynamic> body = {}; Map<String, dynamic> body = {};
body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1; body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
@ -79,12 +79,12 @@ class GasRefillProvider extends ChangeNotifier {
response = await ApiManager.instance.post(URLs.getGasRefill, body: body); response = await ApiManager.instance.post(URLs.getGasRefill, body: body);
stateCode = response.statusCode; stateCode = response.statusCode;
if (stateCode >= 200 && stateCode < 300) { if (stateCode! >= 200 && stateCode! < 300) {
// client's request was successfully received // client's request was successfully received
List requestsListJson = json.decode(response.body)["data"]; List requestsListJson = json.decode(response.body)["data"];
List<GasRefillModel> itemsPage = requestsListJson.map((request) => GasRefillModel.fromJson(request)).toList(); List<GasRefillModel> itemsPage = requestsListJson.map((request) => GasRefillModel.fromJson(request)).toList();
items ??= []; items ??= [];
items.addAll(itemsPage); items!.addAll(itemsPage);
notifyListeners(); notifyListeners();
if (itemsPage.length == pageItemNumber) { if (itemsPage.length == pageItemNumber) {
nextPage = true; nextPage = true;
@ -105,13 +105,13 @@ class GasRefillProvider extends ChangeNotifier {
} }
Future<void> createModel({ Future<void> createModel({
@required BuildContext context, required BuildContext context,
@required User user, required User user,
@required GasRefillModel model, required GasRefillModel model,
}) async { }) async {
Response response; late Response response;
try { try {
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); showDialog(context: context, barrierDismissible: false, builder: (context) => AppLazyLoading());
final Map<String, dynamic> body = { final Map<String, dynamic> body = {
"uid": user.id.toString(), "uid": user.id.toString(),
"token": user.token ?? "", "token": user.token ?? "",
@ -137,10 +137,10 @@ class GasRefillProvider extends ChangeNotifier {
} }
Future<int> updateModel({ Future<int> updateModel({
@required String host, required String host,
@required User user, required User user,
@required GasRefillModel oldModel, required GasRefillModel oldModel,
@required GasRefillModel newModel, required GasRefillModel newModel,
}) async { }) async {
Map<String, dynamic> body = { Map<String, dynamic> body = {
"id": newModel.id, "id": newModel.id,
@ -148,13 +148,12 @@ class GasRefillProvider extends ChangeNotifier {
"status": newModel.status?.toJson(), "status": newModel.status?.toJson(),
//"expectedDate": newModel.expectedDate?.toIso8601String(), //"expectedDate": newModel.expectedDate?.toIso8601String(),
"expectedTime": newModel.expectedDate, "expectedTime": newModel.expectedDate,
if (newModel.timer?.startAt != null) "startDate": newModel.timer.startAt.toIso8601String(), if (newModel.timer?.startAt != null) "startDate": newModel.timer!.startAt!.toIso8601String(),
if (newModel.timer?.startAt != null) "startTime": 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) "endDate": newModel.timer!.endAt!.toIso8601String(), if (newModel.timer?.endAt != null) "endTime": newModel.timer!.endAt!.toIso8601String(),
if (newModel.timer?.endAt != null) "endTime": newModel.timer.endAt.toIso8601String(),
// "workingHours": ((endDate?.difference(startDate)?.inMinutes ?? 0) / 60), // "workingHours": ((endDate?.difference(startDate)?.inMinutes ?? 0) / 60),
'workingHours': newModel.timer?.durationInSecond != null ? newModel.timer.durationInSecond / 60 / 60 : newModel.workingHours, 'workingHours': newModel.timer?.durationInSecond != null ? newModel.timer!.durationInSecond! / 60 / 60 : newModel.workingHours,
"assignedEmployee": oldModel?.assignedEmployee?.id == null ? null : oldModel?.assignedEmployee?.toJson(), "assignedEmployee": oldModel.assignedEmployee?.id == null ? null : oldModel.assignedEmployee?.toJson(),
"site": hospital?.toMap(), "site": hospital?.toMap(),
"building": building?.toJson(includeFloors: false), "building": building?.toJson(includeFloors: false),
"floor": floor?.toJson(includeDepartments: false), "floor": floor?.toJson(includeDepartments: false),
@ -174,7 +173,7 @@ class GasRefillProvider extends ChangeNotifier {
}) })
.toList(); .toList();
log(body.toString()); log(body.toString());
Response response; late Response response;
try { try {
response = await ApiManager.instance.put(URLs.updateGasRefill, body: body); response = await ApiManager.instance.put(URLs.updateGasRefill, body: body);
// response = await post( // response = await post(
@ -193,10 +192,10 @@ class GasRefillProvider extends ChangeNotifier {
} }
} }
Hospital hospital; Hospital? hospital;
Buildings building; Buildings? building;
Floors floor; Floors? floor;
Departments department; Departments? department;
DateTime expectedDateTime; DateTime? expectedDateTime;
//TimerModel timer; //TimerModel timer;
} }

@ -21,9 +21,9 @@ class HospitalsProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 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 page in product list and false if not
bool _nextPage = true; bool _nextPage = true;
@ -32,14 +32,14 @@ class HospitalsProvider extends ChangeNotifier {
// contain user data // contain user data
// when user not login or register _user = null // when user not login or register _user = null
List<Hospital> _hospitals; List<Hospital>? _hospitals;
List<Hospital> get hospitals => _hospitals; List<Hospital>? get hospitals => _hospitals;
// when categories in-process _loading = true // when categories in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool _loading; bool _loading = false;
bool get isLoading => _loading; bool get isLoading => _loading;
@ -53,11 +53,11 @@ class HospitalsProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getHospitals({String host, User user, String title}) async { Future<int> getHospitals({String? host, User? user, String? title}) async {
if (_loading == true) return -2; if (_loading == true) return -2;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
response = await ApiManager.instance.post(URLs.getSites, body: { response = await ApiManager.instance.post(URLs.getSites, body: {
"pageNumber": (hospitals?.length ?? 0) ~/ pageItemNumber + 1, "pageNumber": (hospitals?.length ?? 0) ~/ pageItemNumber + 1,
@ -71,7 +71,7 @@ class HospitalsProvider extends ChangeNotifier {
List<Hospital> _page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList(); List<Hospital> _page = categoriesListJson.map((category) => Hospital.fromJson(category)).toList();
if (hospitals == null) _hospitals = []; if (hospitals == null) _hospitals = [];
_hospitals.addAll(_page); _hospitals!.addAll(_page);
if (_page.length >= pageItemNumber) { if (_page.length >= pageItemNumber) {
_nextPage = true; _nextPage = true;
} else { } else {
@ -89,8 +89,8 @@ class HospitalsProvider extends ChangeNotifier {
} }
} }
Future<List<Hospital>> getHospitalsList({String host, User user, String title}) async { Future<List<Hospital>> getHospitalsList({String? host, User? user, String? title}) async {
Response response; late Response response;
try { try {
response = await ApiManager.instance.post(URLs.getSites, body: { response = await ApiManager.instance.post(URLs.getSites, body: {
"pageSize": 50, "pageSize": 50,
@ -121,7 +121,7 @@ class HospitalsProvider extends ChangeNotifier {
} }
Future<List<Hospital>> getHospitalsListByVal({String searchVal = ""}) async { Future<List<Hospital>> getHospitalsListByVal({String searchVal = ""}) async {
Response response; late Response response;
try { try {
if (searchVal.isNotEmpty) { if (searchVal.isNotEmpty) {
searchVal = "?searchText=$searchVal"; searchVal = "?searchText=$searchVal";

@ -19,12 +19,11 @@ class NotificationsProvider extends ChangeNotifier {
} }
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed// 500 service not available
// 500 service not available int? stateCode;
int stateCode;
// true if there is next page in product list and false if not // 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 of user requests
List<SystemNotificationModel> notifications = []; List<SystemNotificationModel> notifications = [];
@ -32,14 +31,14 @@ class NotificationsProvider extends ChangeNotifier {
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
/// return -2 if request in progress /// return -2 if request in progress
/// return -1 if error happen when sending request /// return -1 if error happen when sending request
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getSystemNotifications({User user, bool resetProvider = false}) async { Future<int> getSystemNotifications({required User user, bool resetProvider = false}) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
if (resetProvider) { if (resetProvider) {
@ -47,7 +46,7 @@ class NotificationsProvider extends ChangeNotifier {
} }
isLoading = true; isLoading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
final Map<String, dynamic> body = {"pageSize": pageItemNumber, "pageNumber": notifications.length ~/ pageItemNumber + 1, "userId": user.userID}; final Map<String, dynamic> body = {"pageSize": pageItemNumber, "pageNumber": notifications.length ~/ pageItemNumber + 1, "userId": user.userID};
response = await ApiManager.instance.post(URLs.getSystemNotifications, body: body); response = await ApiManager.instance.post(URLs.getSystemNotifications, body: body);
@ -56,17 +55,12 @@ class NotificationsProvider extends ChangeNotifier {
print('notifaction response is ${response}'); print('notifaction response is ${response}');
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
// client's request was successfully received // client's request was successfully received
// List requestsListJson = json.decode(utf8.decode(response.bodyBytes));
List requestsListJson = json.decode(response.body)["data"]; List requestsListJson = json.decode(response.body)["data"];
List<SystemNotificationModel> _serviceRequestsPage = requestsListJson.map((request) => SystemNotificationModel.fromJson(request)).toList(); List<SystemNotificationModel> _serviceRequestsPage = requestsListJson.map((request) => SystemNotificationModel.fromJson(request)).toList();
if (notifications == null) notifications = []; if (notifications == null) notifications = [];
notifications.addAll(_serviceRequestsPage); notifications.addAll(_serviceRequestsPage);
if (_serviceRequestsPage.length == pageItemNumber) { // Update nextPage based on response length
nextPage = true; nextPage = _serviceRequestsPage.length == pageItemNumber;
} else {
nextPage = false;
}
} }
isLoading = false; isLoading = false;
notifyListeners(); notifyListeners();
@ -85,11 +79,11 @@ class NotificationsProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<List<SystemNotificationModel>> getRecentNotifications({ Future<List<SystemNotificationModel>?> getRecentNotifications({
@required String host, required String host,
@required User user, required User user,
}) async { }) async {
Response response; late Response response;
//userId = 397.toString(); // testing id to view data //userId = 397.toString(); // testing id to view data
try { try {

@ -20,9 +20,9 @@ class PartsProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int _stateCode; int? _stateCode;
int get stateCode => _stateCode; int? get stateCode => _stateCode;
// true if there is next pagein product list and false if not // true if there is next pagein product list and false if not
bool _nextPage = true; bool _nextPage = true;
@ -31,14 +31,14 @@ class PartsProvider extends ChangeNotifier {
// contain user data // contain user data
// when user not login or register _user = null // when user not login or register _user = null
List<SparePartsWorkOrders> _parts; List<SparePartsWorkOrders>? _parts;
List<SparePartsWorkOrders> get parts => _parts; List<SparePartsWorkOrders>? get parts => _parts;
// when categories in-process _loading = true // when categories in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool _loading; bool _loading = false;
bool get isLoading => _loading; bool get isLoading => _loading;
@ -52,11 +52,11 @@ class PartsProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getParts({String title}) async { Future<int> getParts({String? title}) async {
if (_loading == true) return -2; if (_loading == true) return -2;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();
Response response; late Response response;
try { try {
response = await ApiManager.instance.post(URLs.getPartNumber, body: {if (title != null && title.isNotEmpty) "partName": title}); response = await ApiManager.instance.post(URLs.getPartNumber, body: {if (title != null && title.isNotEmpty) "partName": title});
_stateCode = response.statusCode; _stateCode = response.statusCode;
@ -65,12 +65,8 @@ class PartsProvider extends ChangeNotifier {
List categoriesListJson = json.decode(utf8.decode(response.bodyBytes)); List categoriesListJson = json.decode(utf8.decode(response.bodyBytes));
List<SparePart> _page = categoriesListJson.map((part) => SparePart.fromJson(part)).toList(); List<SparePart> _page = categoriesListJson.map((part) => SparePart.fromJson(part)).toList();
_parts ??= []; _parts ??= [];
_parts.addAll(_page.map((e) => SparePartsWorkOrders(sparePart: e)).toList()); _parts!.addAll(_page.map((e) => SparePartsWorkOrders(sparePart: e)).toList());
if (_page.length >= pageItemNumber) { _nextPage = _page.length >= pageItemNumber;
_nextPage = true;
} else {
_nextPage = false;
}
} }
_loading = false; _loading = false;
notifyListeners(); notifyListeners();
@ -88,8 +84,8 @@ class PartsProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<List<SparePart>> getPartsList({num assetId, String partNo, String partName}) async { Future<List<SparePart>> getPartsList({num? assetId, String? partNo, String? partName}) async {
Response response; late Response response;
try { try {
if (partNo != null) { if (partNo != null) {
response = await ApiManager.instance.post(URLs.getPartNumber, body: {"partNo": partNo, "assetId": assetId}); response = await ApiManager.instance.post(URLs.getPartNumber, body: {"partNo": partNo, "assetId": assetId});

@ -27,18 +27,18 @@ class PpmProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int stateCode; int? stateCode; // Now nullable
// true if there is next page in product list and false if not // true if there is next page in product list and false if not
bool nextPage = true; bool nextPage = true;
// list of user requests // list of user requests
List<Ppm> ppms; List<Ppm>? ppms; // Now nullable
// when requests in-process _loading = true // when requests in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool isLoading; bool isLoading = false;
PpmSearch visitsSearch = PpmSearch(); PpmSearch visitsSearch = PpmSearch();
@ -48,15 +48,14 @@ class PpmProvider extends ChangeNotifier {
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getVisits({ Future<int> getVisits({
@required String host, required String host,
@required User user, required User user,
//VisitsSearch visitsSearch, //VisitsSearch visitsSearch,
}) async { }) async {
if (isLoading == true) return -2; if (isLoading == true) return -2;
isLoading = true; isLoading = true;
if (ppms?.isEmpty ?? true) notifyListeners(); if (ppms?.isEmpty ?? true) notifyListeners();
Response response; late Response response; // Using 'late' for initialization later
//userId = 397.toString(); // testing id to view data
try { try {
Map<String, dynamic> body = {}; Map<String, dynamic> body = {};
@ -80,8 +79,8 @@ class PpmProvider extends ChangeNotifier {
try { try {
List requestsListJson = json.decode(response.body)["data"]; List requestsListJson = json.decode(response.body)["data"];
List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList(); List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList();
ppms ??= []; ppms ??= []; // Initialize if null
ppms.addAll(visits); ppms!.addAll(visits); // Use '!' since ppms is now non-nullable after initialization
notifyListeners(); notifyListeners();
if (visits.length == pageItemNumber) { if (visits.length == pageItemNumber) {
nextPage = true; nextPage = true;
@ -89,7 +88,7 @@ class PpmProvider extends ChangeNotifier {
nextPage = false; nextPage = false;
} }
} catch (error) { } catch (error) {
log(error ?? ""); log(error.toString()); // Convert error to string
isLoading = false; isLoading = false;
stateCode = -1; stateCode = -1;
notifyListeners(); notifyListeners();
@ -101,7 +100,8 @@ class PpmProvider extends ChangeNotifier {
return response.statusCode; return response.statusCode;
} }
Future<Ppm> getPpmById(num id) async { Future<Ppm?> getPpmById(num id) async {
// Return type is nullable
try { try {
visitsSearch.id = id; visitsSearch.id = id;
visitsSearch.pageNumber = 1; visitsSearch.pageNumber = 1;
@ -111,7 +111,7 @@ class PpmProvider extends ChangeNotifier {
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
List requestsListJson = json.decode(response.body)["data"]; List requestsListJson = json.decode(response.body)["data"];
List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList(); List<Ppm> 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; return null;
} catch (error) { } catch (error) {
@ -125,11 +125,11 @@ class PpmProvider extends ChangeNotifier {
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> updateGroupOfVisits({ Future<int> updateGroupOfVisits({
@required String host, required String host,
@required User user, required User user,
// VisitsGroup group, // VisitsGroup group,
}) async { }) async {
Response response; late Response response; // Using 'late' for initialization later
try { try {
Map<String, dynamic> body = {} /*group.toJson()*/; Map<String, dynamic> body = {} /*group.toJson()*/;
@ -154,10 +154,11 @@ class PpmProvider extends ChangeNotifier {
} }
} }
Future<Ppm> getPentry({String host, User user, int id}) async { Future<Ppm?> getPentry({required String host, required User user, required int id}) async {
// Return type is nullable
Response response; Response response;
response = await ApiManager.instance.get("${URLs.getPentry}/$id"); response = await ApiManager.instance.get("${URLs.getPentry}/$id");
Ppm pantry; Ppm? pantry; // Now nullable
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
pantry = Ppm.fromJson(json.decode(utf8.decode(response.bodyBytes))); pantry = Ppm.fromJson(json.decode(utf8.decode(response.bodyBytes)));
} }
@ -166,20 +167,20 @@ class PpmProvider extends ChangeNotifier {
Future<int> updatePentry( Future<int> updatePentry(
BuildContext context, { BuildContext context, {
@required User user, required User user,
@required Ppm ppm, required Ppm ppm,
}) async { }) async {
try { try {
ppm.visitTimers.add( ppm.visitTimers.add(
VisitTimers( VisitTimers(
id: 0, id: 0,
startDateTime: ppm.tbsTimer?.startAt?.toIso8601String(), startDateTime: ppm.tbsTimer?.startAt!.toIso8601String(), // Handle potential null
endDateTime: ppm.tbsTimer?.endAt?.toIso8601String(), endDateTime: ppm.tbsTimer?.endAt?.toIso8601String(), // Handle potential null
workingHours: ((ppm.tbsTimer?.durationInSecond ?? 0) / 60 / 60), workingHours: ((ppm.tbsTimer?.durationInSecond ?? 0) / 60 / 60),
), ),
); );
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
Response response; late Response response; // Using 'late' for initialization later
Map<String, dynamic> body = ppm.copyWith(assignedEmployeeId: user.userName, tbsTimer: ppm.tbsTimer).toJson(); Map<String, dynamic> body = ppm.copyWith(assignedEmployeeId: user.userName, tbsTimer: ppm.tbsTimer).toJson();
response = await ApiManager.instance.put(URLs.updatePentry, body: body); response = await ApiManager.instance.put(URLs.updatePentry, body: body);
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {

@ -249,9 +249,9 @@ class ServiceRequestsProvider extends ChangeNotifier {
} }
Future<int> createIssueReport({ Future<int> createIssueReport({
@required String host, required String host,
@required User user, required User user,
@required Issue issue, required Issue issue,
}) async { }) async {
Response response; Response response;
Map<String, String> body = issue.toMap(); Map<String, String> body = issue.toMap();

@ -2,11 +2,9 @@ import 'dart:convert';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/employee.dart'; import 'package:test_sa/models/employee.dart';
import 'package:test_sa/models/user.dart';
class NurseProvider extends ChangeNotifier { class NurseProvider extends ChangeNotifier {
//reset provider data //reset provider data
@ -15,17 +13,17 @@ class NurseProvider extends ChangeNotifier {
_stateCode = null; _stateCode = null;
} }
int _stateCode; int? _stateCode; // Now nullable
int get stateCode => _stateCode; int? get stateCode => _stateCode;
List<Employee> _items; List<Employee>? _items; // Now nullable
List<Employee> get nursesList => _items; List<Employee> get nursesList => _items ?? []; // Return empty list if null
bool _loading; bool _loading = false; // Initialize loading to false
bool get isLoading => _loading; bool get isLoading => _loading;
int siteId; int? siteId; // Now nullable
set isLoading(bool isLoading) { set isLoading(bool isLoading) {
_loading = isLoading; _loading = isLoading;
@ -33,10 +31,9 @@ class NurseProvider extends ChangeNotifier {
} }
Future<int> getData() async { Future<int> getData() async {
if (_loading == true) return -2; if (_loading) return -2;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();
Response response;
try { try {
if (siteId == null) { if (siteId == null) {
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
@ -44,15 +41,14 @@ class NurseProvider extends ChangeNotifier {
_loading = false; _loading = false;
notifyListeners(); notifyListeners();
_stateCode = 200; _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; _stateCode = response.statusCode;
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
// client's request was successfully received final categoriesListJson = json.decode(response.body) as List;
List categoriesListJson = json.decode(response.body);
_items = categoriesListJson.map((type) => Employee.fromJson(type)).toList(); _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; _loading = false;
notifyListeners(); notifyListeners();

@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/user.dart';
import '../../../../../models/fault_description.dart'; import '../../../../../models/fault_description.dart';
@ -19,20 +18,20 @@ class ServiceRequestFaultDescriptionProvider extends ChangeNotifier {
// state code of current request to defied error message // state code of current request to defied error message
// like 400 customer request failed // like 400 customer request failed
// 500 service not available // 500 service not available
int _stateCode; int? _stateCode;
int get stateCode => _stateCode; int? get stateCode => _stateCode;
// contain user data // contain user data
// when user not login or register _user = null // when user not login or register _user = null
List<FaultDescription> _items; List<FaultDescription>? _items;
List<FaultDescription> get items => _items; List<FaultDescription>? get items => _items;
// when categories in-process _loading = true // when categories in-process _loading = true
// done _loading = true // done _loading = true
// failed _loading = false // failed _loading = false
bool _loading; bool _loading = false; // Initialize _loading to false
bool get isLoading => _loading; bool get isLoading => _loading;
@ -46,7 +45,7 @@ class ServiceRequestFaultDescriptionProvider extends ChangeNotifier {
/// return state code if request complete may be 200, 404 or 403 /// return state code if request complete may be 200, 404 or 403
/// for more details check http state manager /// for more details check http state manager
/// lib\controllers\http_status_manger\http_status_manger.dart /// lib\controllers\http_status_manger\http_status_manger.dart
Future<int> getCallRequestForWorkOrder({String host, User user, String requestId}) async { Future<int> getCallRequestForWorkOrder(String requestId) async {
if (_loading == true) return -2; if (_loading == true) return -2;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();

@ -12,7 +12,33 @@ import 'package:test_sa/models/user.dart';
import '../settings/app_settings.dart'; import '../settings/app_settings.dart';
class SettingProvider extends ChangeNotifier { 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<void> resetSettings() async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
user = null; user = null;
_assetGroup = null; _assetGroup = null;
@ -22,12 +48,6 @@ class SettingProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
// check if setting loaded or not
bool isLoaded = false;
// contain saved user data
User user;
Future<void> setUser(User user) async { Future<void> setUser(User user) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(ASettings.user, json.encode(user.toJson())); prefs.setString(ASettings.user, json.encode(user.toJson()));
@ -56,20 +76,15 @@ class SettingProvider extends ChangeNotifier {
} }
} }
setAssetGroup(_assetGroup); setAssetGroup(_assetGroup);
// ApiManager.instance.assetGroup = _assetGroup;
} }
Future<void> setAssetGroup(AssetGroup assetGroup) async { Future<void> setAssetGroup(AssetGroup? assetGroup) async {
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString(ASettings.assetGroup, json.encode(assetGroup.toJson()));
_assetGroup = assetGroup; _assetGroup = assetGroup;
ApiManager.instance.assetGroup = _assetGroup; ApiManager.instance.assetGroup = _assetGroup!;
notifyListeners(); notifyListeners();
} }
String _host; String? get host => _host;
String get host => _host;
Future<void> setHost(String host) async { Future<void> setHost(String host) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
@ -78,16 +93,13 @@ class SettingProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
String _language; String? get language => _language;
AssetGroup _assetGroup;
String get language => _language; AssetGroup? get assetGroup => _assetGroup;
AssetGroup get assetGroup => _assetGroup; String? get theme => _theme;
bool rememberMe = false; bool get localAuth => isLocalAuthEnable;
String username = "";
String password = "";
Future<void> setLanguage(String currentLanguage) async { Future<void> setLanguage(String currentLanguage) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
@ -96,8 +108,6 @@ class SettingProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
bool isLocalAuthEnable = false;
Future<void> setAuth(bool status) async { Future<void> setAuth(bool status) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
isLocalAuthEnable = status; isLocalAuthEnable = status;
@ -105,22 +115,7 @@ class SettingProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
String _theme; String? get speechToText => _speechToText;
String get theme => _theme;
bool get localAuth => isLocalAuthEnable;
Future<void> 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;
Future<void> setSpeechToText(String currentLanguage) async { Future<void> setSpeechToText(String currentLanguage) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
@ -129,79 +124,47 @@ class SettingProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
// call loadSharedPreferences when provider initialise Future<void> setDarkTheme(bool value) async {
SettingProvider() { SharedPreferences prefs = await SharedPreferences.getInstance();
loadSharedPreferences(); _theme = value ? "dark" : "light";
prefs.setString(ASettings.theme, _theme!);
notifyListeners();
} }
LocalAuthentication auth = LocalAuthentication(); // Get app setting
// get app setting
Future<void> loadSharedPreferences() async { Future<void> loadSharedPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey(ASettings.language)) { _language = prefs.getString(ASettings.language) ?? 'en';
_language = prefs.getString(ASettings.language); _theme = prefs.getString(ASettings.theme) ?? 'light';
} else { isLocalAuthEnable = prefs.getBool(ASettings.localAuth) ?? false;
_language = 'en'; _speechToText = prefs.getString(ASettings.speechToText) ?? 'ar';
}
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';
}
if (prefs.containsKey(ASettings.user)) { if (prefs.containsKey(ASettings.user)) {
String userJson = prefs.getString(ASettings.user); String userJson = prefs.getString(ASettings.user)!;
user = User.fromJson(json.decode(userJson)); user = User.fromJson(json.decode(userJson));
selectAssetGroup(user); selectAssetGroup(user!);
} }
rememberMe = prefs.getBool(ASettings.rememberMe) ?? false; rememberMe = prefs.getBool(ASettings.rememberMe) ?? false;
username = prefs.getString(ASettings.userName) ?? ""; username = prefs.getString(ASettings.userName) ?? "";
password = prefs.getString(ASettings.password) ?? ""; password = prefs.getString(ASettings.password) ?? "";
// if (prefs.containsKey(ASettings.assetGroup)) { // _host = prefs.getString(ASettings.host) ?? URLs.host1;
// 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;
}
isLoaded = true; isLoaded = true;
notifyListeners(); notifyListeners();
} }
Future<bool> checkUserTokenValidation(String token) async { Future<bool> checkUserTokenValidation(String token) async {
Response response;
bool isValid = false;
try { try {
Map<String, dynamic> body = {}; final response = await ApiManager.instance.post(
response = await ApiManager.instance.post(URLs.checkLoginValidation + "?token=$token", body: body); "${URLs.checkLoginValidation}?token=$token",
if (response.statusCode >= 200 && response.statusCode < 300) { body: <String, dynamic>{},
isValid = true; );
} return response.statusCode >= 200 && response.statusCode < 300;
return isValid;
} catch (error) { } catch (error) {
return isValid; return false;
} }
} }
} }

@ -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/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/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/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/user.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/progress_fragment.dart';
import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/requests_fragment.dart'; import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/requests_fragment.dart';
import 'package:test_sa/utilities/request_utils.dart'; import 'package:test_sa/utilities/request_utils.dart';
@ -90,16 +87,13 @@ class _DashboardViewState extends State<DashboardView> {
void handleScroll() async { void handleScroll() async {
_scrollController = ScrollController(); _scrollController = ScrollController();
_scrollController.addListener(() async { _scrollController.addListener(() async {
if (_scrollController?.position?.pixels == if (_scrollController?.position?.pixels == _scrollController?.position?.maxScrollExtent && !allRequestsProvider.isFilterRequestLoading) {
_scrollController?.position?.maxScrollExtent &&
!allRequestsProvider.isFilterRequestLoading) {
allRequestsProvider.pageNum = allRequestsProvider.pageNum + 1; allRequestsProvider.pageNum = allRequestsProvider.pageNum + 1;
await allRequestsProvider.getFilterRequests(showLoader: false, status: allRequestsProvider.status); await allRequestsProvider.getFilterRequests(showLoader: false, status: allRequestsProvider.status);
} }
}); });
} }
@override @override
void dispose() { void dispose() {
_scrollController.dispose(); _scrollController.dispose();
@ -110,11 +104,7 @@ class _DashboardViewState extends State<DashboardView> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
// backgroundColor: AppColor.background(context), // backgroundColor: AppColor.background(context),
appBar: PreferredSize( appBar: PreferredSize(preferredSize: const Size.fromHeight(kToolbarHeight), child: AppBarWidget(onDrawerPress: widget.onDrawerPress)),
preferredSize: const Size.fromHeight(kToolbarHeight),
child: AppBarWidget(
onDrawerPress: widget.onDrawerPress,
)),
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: () async { onRefresh: () async {
getInitialData(); getInitialData();
@ -128,15 +118,7 @@ class _DashboardViewState extends State<DashboardView> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [14.height, ProgressFragment(), 25.height, SizedBox(height: 110.toScreenHeight, child: const RequestsFragment()), 16.height, const RequestCategoryFragment()],
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), ).paddingOnly(start: 16, end: 16, top: 0, bottom: 8),
), ),
), ),

@ -14,9 +14,9 @@ import '../../controllers/providers/api/user_provider.dart';
import '../../models/user.dart'; import '../../models/user.dart';
class AppBarWidget extends StatelessWidget { 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -36,23 +36,23 @@ class AppBarWidget extends StatelessWidget {
padding: const EdgeInsets.all(1), // Border radius padding: const EdgeInsets.all(1), // Border radius
child: ClipOval( child: ClipOval(
child: snapshot.profileImage != null child: snapshot.profileImage != null
? Image.file(snapshot.profileImage) ? Image.file(snapshot.profileImage!) // Added null check
: (snapshot.user.profilePhotoName?.isNotEmpty ?? false) : (snapshot.user?.profilePhotoName?.isNotEmpty ?? false)
? Image.network(snapshot.user.profilePhotoName) ? Image.network(snapshot.user!.profilePhotoName!) // Added null check
: const Icon(Icons.person, size: 24, color: Colors.white), : const Icon(Icons.person, size: 24, color: Colors.white),
), ),
), ),
).onPress(onDrawerPress), ).onPress(onDrawerPress), // Handle potential null
8.width, 8.width,
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( 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), style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600),
), ),
Text( 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), style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
), ),
], ],
@ -73,7 +73,8 @@ class AppBarWidget extends StatelessWidget {
) )
], ],
), ),
child: DropdownButton<AssetGroup>( child: DropdownButton<AssetGroup?>(
// Made AssetGroup nullable
value: settingProvider.assetGroup, value: settingProvider.assetGroup,
//iconSize: 24, //iconSize: 24,
isDense: true, isDense: true,
@ -88,19 +89,22 @@ class AppBarWidget extends StatelessWidget {
settingProvider.setAssetGroup(newValue); settingProvider.setAssetGroup(newValue);
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<AllRequestsProvider>(context, listen: false).getRequests(); Provider.of<AllRequestsProvider>(context, listen: false).getRequests();
Provider.of<NotificationsProvider>(context, listen: false).getSystemNotifications(user: Provider.of<UserProvider>(context, listen: false).user, resetProvider: true); Provider.of<NotificationsProvider>(context, listen: false)
.getSystemNotifications(user: Provider.of<UserProvider>(context, listen: false).user!, resetProvider: true); // Added null check
}); });
} }
}, },
items: Provider.of<UserProvider>(context, listen: false).user.assetGroups.map<DropdownMenuItem<AssetGroup>>((value) { items: Provider.of<UserProvider>(context, listen: false).user?.assetGroups.map<DropdownMenuItem<AssetGroup?>>((value) {
return DropdownMenuItem<AssetGroup>( // Added null check and made AssetGroup nullable
return DropdownMenuItem<AssetGroup?>(
value: value, value: value,
child: Text( child: Text(
value?.name ?? "", value?.name ?? "",
style: Theme.of(context).textTheme.bodyLarge, style: Theme.of(context).textTheme.bodyLarge,
), ),
); );
})?.toList(), })?.toList() ??
[], // Added null check and empty list default
), ),
); );
}), }),
@ -110,18 +114,7 @@ class AppBarWidget extends StatelessWidget {
children: [ children: [
Icon(Icons.notifications, color: context.isDark ? AppColor.neutral30 : AppColor.neutral20, size: 30).paddingOnly(top: 6, end: 0), 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 // todo @sikander will add count for unread notifications
// Positioned( // ... (rest of the code remains the same)
// top: 0,
// right: 0,
// child: Container(
// padding: const EdgeInsets.all(4),
// decoration: const ShapeDecoration(
// color: Color(0xFFD02127),
// shape: CircleBorder(),
// ),
// child: Text("", style: AppTextStyles.bodyText),
// ),
// )
], ],
).onPress(() { ).onPress(() {
Navigator.of(context).pushNamed(NotificationsPage.id); Navigator.of(context).pushNamed(NotificationsPage.id);

@ -6,7 +6,7 @@ import 'package:provider/provider.dart';
import '../controllers/providers/settings/setting_provider.dart'; import '../controllers/providers/settings/setting_provider.dart';
extension BuildContextExtension on BuildContext { extension BuildContextExtension on BuildContext {
AppLocalizations get translation => AppLocalizations.of(this); AppLocalizations get translation => AppLocalizations.of(this)!;
List<String> get getIssues => [translation.reason1, translation.reason2, translation.reason3, translation.reason4, translation.reason5]; List<String> get getIssues => [translation.reason1, translation.reason2, translation.reason3, translation.reason4, translation.reason5];

@ -7,13 +7,13 @@ extension StringExtensions on String {
void get showToast => Fluttertoast.showToast(msg: this); void get showToast => Fluttertoast.showToast(msg: this);
String get toServiceRequestCardFormat { 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)}"; return "${DateFormat('dd MMM, yyyy').format(dateTime)}\n${DateFormat('hh:mm a').format(dateTime)}";
} }
String get toServiceRequestDetailsFormat { String get toServiceRequestDetailsFormat {
try { try {
DateTime dateTime = DateTime.tryParse(this); DateTime dateTime = DateTime.parse(this);
return "${DateFormat('dd MMM, yyyy').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}"; return "${DateFormat('dd MMM, yyyy').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}";
} catch (e) { } catch (e) {
return ""; return "";
@ -22,7 +22,7 @@ extension StringExtensions on String {
String get toFirstActionFormat { String get toFirstActionFormat {
try { try {
DateTime dateTime = DateTime.tryParse(this); DateTime dateTime = DateTime.parse(this);
return "${DateFormat('yyyy-MM-dd').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}"; return "${DateFormat('yyyy-MM-dd').format(dateTime)} ${DateFormat('hh:mm a').format(dateTime)}";
} catch (e) { } catch (e) {
return ""; return "";
@ -31,7 +31,7 @@ extension StringExtensions on String {
String get toAssetDetailsFormat { String get toAssetDetailsFormat {
try { try {
DateTime dateTime = DateTime.tryParse(this); DateTime dateTime = DateTime.parse(this);
return DateFormat('dd MMM, yyyy').format(dateTime); return DateFormat('dd MMM, yyyy').format(dateTime);
} catch (e) { } catch (e) {
return "-"; return "-";

@ -16,6 +16,7 @@ extension TextStyles on String {
Text heading4(BuildContext context) => getTextWithStyle(this, AppTextStyles.heading4, context.isDark ? AppColor.neutral30 : AppColor.neutral50); 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 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 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); 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 { 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( return Text(
data, data!,
textAlign: align, textAlign: align,
style: style.copyWith( style: style?.copyWith(
color: color, color: color,
height: lineHeight, height: lineHeight,
letterSpacing: letterSpacing, letterSpacing: letterSpacing,
@ -87,10 +95,14 @@ abstract class AppTextStyles {
); );
static const TextStyle customHeadingText = TextStyle( static const TextStyle customHeadingText = TextStyle(
fontFamily: 'Poppins', fontFamily: 'Poppins',
fontSize: 27, // Font size in logical pixels fontSize: 27,
fontWeight: FontWeight.w500, // Equivalent to font-weight: 500 // Font size in logical pixels
height: 31 / 27, // Line height (in Flutter, it's a multiplier of font size) fontWeight: FontWeight.w500,
letterSpacing: -0.04 * 27, // Letter spacing, converted to logical pixels // 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 color: Colors.black, // Set your desired text color
); );
@ -149,24 +161,24 @@ extension CapExtension on String {
extension FilesExtension on String { extension FilesExtension on String {
SvgPicture toSvgAsset({ SvgPicture toSvgAsset({
int width, int? width,
int height, int? height,
Color color, Color? color,
BoxFit fit = BoxFit.contain, BoxFit fit = BoxFit.contain,
}) => }) =>
SvgPicture.asset("assets/images/$this.svg", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit); SvgPicture.asset("assets/images/$this.svg", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit);
Image toPngAsset({ Image toPngAsset({
int width, int? width,
int height, int? height,
Color color, Color? color,
BoxFit fit = BoxFit.contain, BoxFit fit = BoxFit.contain,
}) => }) =>
Image.asset("assets/images/$this.png", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit); Image.asset("assets/images/$this.png", width: width?.toScreenWidth, height: height?.toScreenHeight, color: color, fit: fit);
LottieBuilder toLottieAsset({ LottieBuilder toLottieAsset({
int width, int? width,
int height, int? height,
BoxFit fit = BoxFit.contain, BoxFit fit = BoxFit.contain,
bool repeat = true, bool repeat = true,
}) => }) =>

@ -6,7 +6,7 @@ import 'package:test_sa/extensions/int_extensions.dart';
import '../new_views/app_style/app_color.dart'; import '../new_views/app_style/app_color.dart';
extension WidgetExtensions on Widget { 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); Widget get expanded => Expanded(child: this);

@ -1,15 +1,23 @@
import 'dart:convert'; import 'dart:convert';
class AllRequestsAndCount { class AllRequestsAndCount {
CountServiceRequest countServiceRequest; CountServiceRequest? countServiceRequest;
CountServiceRequest countGasRefill; CountServiceRequest? countGasRefill;
CountServiceRequest countAssetTransfer; CountServiceRequest? countAssetTransfer;
CountServiceRequest countPPM; CountServiceRequest? countPPM;
DetailsStatusTotal detailsStatusTotal; DetailsStatusTotal? detailsStatusTotal;
CountServiceRequest total; CountServiceRequest? total;
List<RequestsDetails> requestsDetails; List<RequestsDetails>? requestsDetails;
AllRequestsAndCount({this.countServiceRequest, this.countGasRefill, this.countAssetTransfer, this.countPPM, this.detailsStatusTotal, this.total, this.requestsDetails}); AllRequestsAndCount({
this.countServiceRequest,
this.countGasRefill,
this.countAssetTransfer,
this.countPPM,
this.detailsStatusTotal,
this.total,
this.requestsDetails,
});
AllRequestsAndCount.fromJson(Map<String, dynamic> json) { AllRequestsAndCount.fromJson(Map<String, dynamic> json) {
countServiceRequest = json['countServiceRequest'] != null ? CountServiceRequest.fromJson(json['countServiceRequest']) : null; countServiceRequest = json['countServiceRequest'] != null ? CountServiceRequest.fromJson(json['countServiceRequest']) : null;
@ -21,7 +29,7 @@ class AllRequestsAndCount {
if (json['requestsDetails'] != null) { if (json['requestsDetails'] != null) {
requestsDetails = <RequestsDetails>[]; requestsDetails = <RequestsDetails>[];
json['requestsDetails'].forEach((v) { json['requestsDetails'].forEach((v) {
requestsDetails.add(RequestsDetails.fromJson(v)); requestsDetails!.add(RequestsDetails.fromJson(v));
}); });
} }
} }
@ -29,34 +37,32 @@ class AllRequestsAndCount {
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{}; final Map<String, dynamic> data = <String, dynamic>{};
if (countServiceRequest != null) { if (countServiceRequest != null) {
data['countServiceRequest'] = countServiceRequest.toJson(); data['countServiceRequest'] = countServiceRequest!.toJson();
} }
if (countGasRefill != null) { if (countGasRefill != null) {
data['countGasRefill'] = countGasRefill.toJson(); data['countGasRefill'] = countGasRefill!.toJson();
} }
if (countAssetTransfer != null) { if (countAssetTransfer != null) {
data['countAssetTransfer'] = countAssetTransfer.toJson(); data['countAssetTransfer'] = countAssetTransfer!.toJson();
} }
if (countPPM != null) { if (countPPM != null) {
data['countPPM'] = countPPM.toJson(); data['countPPM'] = countPPM!.toJson();
} }
if (detailsStatusTotal != null) { if (detailsStatusTotal != null) {
data['detailsStatusTotal'] = detailsStatusTotal.toJson(); data['detailsStatusTotal'] = detailsStatusTotal!.toJson();
} }
if (total != null) { if (total != null) {
data['total'] = total.toJson(); data['total'] = total!.toJson();
} }
if (requestsDetails != null) { if (requestsDetails != null) {
data['requestsDetails'] = requestsDetails.map((v) => v.toJson()).toList(); data['requestsDetails'] = requestsDetails!.map((v) => v.toJson()).toList();
} }
return data; return data;
} }
} }
class CountServiceRequest { class CountServiceRequest {
int count; int? count;
CountServiceRequest({this.count}); CountServiceRequest({this.count});
@ -72,9 +78,9 @@ class CountServiceRequest {
} }
class DetailsStatusTotal { class DetailsStatusTotal {
int open; int? open;
int inProgress; int? inProgress;
int closed; int? closed;
DetailsStatusTotal({this.open, this.inProgress, this.closed}); DetailsStatusTotal({this.open, this.inProgress, this.closed});
@ -94,30 +100,30 @@ class DetailsStatusTotal {
} }
class RequestsDetails { class RequestsDetails {
int id; int? id;
String nameOfType; String? nameOfType;
String priority; String? priority;
String status; String? status;
String assetName; String? assetName;
String assetNo; String? assetNo;
String assetSN; String? assetSN;
String model; String? model;
String supplier; String? supplier;
String manufacturer; String? manufacturer;
String requestType; String? requestType;
String requestNo; String? requestNo;
String gasType; String? gasType;
String site; String? site;
String statusReceiver; String? statusReceiver;
String assetTransferFrom; String? assetTransferFrom;
String assetTransferTo; String? assetTransferTo;
String code; String? code;
String date; String? date;
String siteTransferFrom; String? siteTransferFrom;
String siteTransferTo; String? siteTransferTo;
RequestsDetails( RequestsDetails({
{this.id, this.id,
this.nameOfType, this.nameOfType,
this.priority, this.priority,
this.status, this.status,
@ -137,7 +143,8 @@ class RequestsDetails {
this.code, this.code,
this.siteTransferFrom, this.siteTransferFrom,
this.siteTransferTo, this.siteTransferTo,
this.date}); this.date,
});
RequestsDetails.fromJson(Map<String, dynamic> json) { RequestsDetails.fromJson(Map<String, dynamic> json) {
id = json['id']; id = json['id'];
@ -190,12 +197,11 @@ class RequestsDetails {
} }
} }
class RequestQueryModel { class RequestQueryModel {
List<int> typeTransaction; List<int>? typeTransaction;
List<int> statusTransaction; List<int>? statusTransaction;
List<int> priority; List<int>? priority;
List<int> displayData; List<int>? displayData;
int pageNumber; int pageNumber;
int pageSize; int pageSize;
bool showLoader; bool showLoader;
@ -210,19 +216,18 @@ class RequestQueryModel {
this.showLoader = true, this.showLoader = true,
}); });
// Factory method to create an instance from a JSON map
factory RequestQueryModel.fromJson(Map<String, dynamic> json) { factory RequestQueryModel.fromJson(Map<String, dynamic> json) {
return RequestQueryModel( return RequestQueryModel(
typeTransaction: List<int>.from(json['typeTransaction']), typeTransaction: List<int>.from(json['typeTransaction']),
statusTransaction: List<int>.from(json['statusTransaction']), statusTransaction: List<int>.from(json['statusTransaction']),
priority: List<int>.from(json['priority']), priority: List<int>.from(json['priority']),
displayData: List<int>.from(json['displayData']), displayData: List<int>.from(json['displayData']),
pageNumber: json['pageNumber'], pageNumber: json['pageNumber'] ?? 1,
pageSize: json['pageSize'], pageSize: json['pageSize'] ?? 10,
showLoader: json['showLoader'] ?? true,
); );
} }
// Method to convert an instance to a JSON map
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'typeTransaction': typeTransaction, 'typeTransaction': typeTransaction,
@ -231,14 +236,11 @@ class RequestQueryModel {
'displayData': displayData, 'displayData': displayData,
'pageNumber': pageNumber, 'pageNumber': pageNumber,
'pageSize': pageSize, 'pageSize': pageSize,
'showLoader': showLoader,
}; };
} }
// Method to encode the model to a JSON string
String encodeToJson() => json.encode(toJson()); 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));
} }

@ -1,5 +1,5 @@
class Base { class Base {
String name, identifier; String? name, identifier;
Base({this.name, this.identifier}); Base({this.name, this.identifier});
} }

@ -10,23 +10,23 @@ class Comment {
Comment.fromJson(dynamic json) { Comment.fromJson(dynamic json) {
id = json['id']; id = json['id'];
callRequestId = json['callRequestId']; callRequestId = json['callRequestId'];
createdOn = json['createdOn']; createdOn = json['createdOn'] ?? '';
createdBy = json['createdBy'] != null ? CreatedBy.fromJson(json['createdBy']) : null; createdBy = json['createdBy'] != null ? CreatedBy.fromJson(json['createdBy']) : null;
comment = json['comment']; comment = json['comment'] ?? '';
} }
num id; num? id;
num callRequestId; num? callRequestId;
String createdOn; String? createdOn;
CreatedBy createdBy; CreatedBy? createdBy;
String comment; String? comment;
Comment copyWith({ Comment copyWith({
num id, num? id,
num callRequestId, num? callRequestId,
String createdOn, String? createdOn,
CreatedBy createdBy, CreatedBy? createdBy,
String comment, String? comment,
}) => }) =>
Comment( Comment(
id: id ?? this.id, id: id ?? this.id,
@ -42,7 +42,7 @@ class Comment {
map['callRequestId'] = callRequestId; map['callRequestId'] = callRequestId;
map['createdOn'] = createdOn; map['createdOn'] = createdOn;
if (createdBy != null) { if (createdBy != null) {
map['createdBy'] = createdBy.toJson(); map['createdBy'] = createdBy?.toJson();
} }
map['comment'] = comment; map['comment'] = comment;
return map; return map;
@ -56,16 +56,16 @@ class CreatedBy {
}); });
CreatedBy.fromJson(dynamic json) { CreatedBy.fromJson(dynamic json) {
userId = json['userId']; userId = json['userId'] ?? '';
userName = json['userName']; userName = json['userName'] ?? '';
} }
String userId; String? userId;
String userName; String? userName;
CreatedBy copyWith({ CreatedBy copyWith({
String userId, String? userId,
String userName, String? userName,
}) => }) =>
CreatedBy( CreatedBy(
userId: userId ?? this.userId, userId: userId ?? this.userId,

@ -1,6 +1,6 @@
class Department { class Department {
int id; int? id;
String name; String? name;
Department({ Department({
this.id, this.id,
@ -14,7 +14,7 @@ class Department {
); );
} }
factory Department.fromDepartment(Department department) { factory Department.fromDepartment(Department? department) {
return Department( return Department(
id: department?.id, id: department?.id,
name: department?.name, name: department?.name,

@ -111,7 +111,7 @@ class Asset {
if (json['technicalGuidanceBooks'] != null) { if (json['technicalGuidanceBooks'] != null) {
technicalGuidanceBooks = []; technicalGuidanceBooks = [];
json['technicalGuidanceBooks'].forEach((v) { json['technicalGuidanceBooks'].forEach((v) {
technicalGuidanceBooks.add(TechnicalGuidanceBook.fromJson(v)); technicalGuidanceBooks!.add(TechnicalGuidanceBook.fromJson(v)); // Use '!' since technicalGuidanceBooks is initialized here
}); });
} }
comment = json['comment']; comment = json['comment'];
@ -119,107 +119,106 @@ class Asset {
assetPhoto = json['assetPhoto']; assetPhoto = json['assetPhoto'];
} }
num id; num? id; // Now nullable
String assetSerialNo; String? assetSerialNo; // Now nullable
String systemID; String? systemID; // Now nullable
String assetNumber; String? assetNumber; // Now nullable
ModelDefinition modelDefinition; ModelDefinition? modelDefinition; // Now nullable
Supplier supplier; Supplier? supplier; // Now nullable
String ipAddress; String? ipAddress; // Now nullable
String macAddress; String? macAddress; // Now nullable
String portNumber; String? portNumber; // Now nullable
Lookup assetReplace; Lookup? assetReplace; // Now nullable
AssetInfo oldAsset; AssetInfo? oldAsset; // Now nullable
Lookup isParent; Lookup? isParent; // Now nullable
AssetInfo parentAsset; AssetInfo? parentAsset; // Now nullable
Lookup assetType; Lookup? assetType; // Now nullable
Site site; Site? site; // Now nullable
Building building; Building? building; // Now nullable
Floor floor; Floor? floor; // Now nullable
Department department; Department? department; // Now nullable
Rooms room; Rooms? room; // Now nullable
// String room; num? testsDay; // Now nullable
num testsDay; num? purchasingPrice; // Now nullable
num purchasingPrice; String? nbv; // Now nullable
String nbv; Lookup? currency; // Now nullable
Lookup currency; String? poNo; // Now nullable
String poNo; String? invoiceNumber; // Now nullable
String invoiceNumber; String? invoiceDate; // Now nullable
String invoiceDate; String? replacementDate; // Now nullable
String replacementDate; Department? originDepartment; // Now nullable
Department originDepartment; Site? originSite; // Now nullable
Site originSite; num? budgetYear; // Now nullable
num budgetYear; num? lastPOPrice; // Now nullable
num lastPOPrice; Lookup? commissioningStatus; // Now nullable
Lookup commissioningStatus; String? productionDate; // Now nullable
String productionDate; String? edd; // Now nullable
String edd; String? technicalInspectionDate; // Now nullable
String technicalInspectionDate; String? deliveryInspectionDate; // Now nullable
String deliveryInspectionDate; String? endUserAcceptanceDate; // Now nullable
String endUserAcceptanceDate; String? receivingCommittee; // Now nullable
String receivingCommittee; Lookup? siteWarrantyMonths; // Now nullable
Lookup siteWarrantyMonths; Lookup? extendedWarrantyMonths; // Now nullable
Lookup extendedWarrantyMonths; Lookup? remainderWarrantyMonths; // Now nullable
Lookup remainderWarrantyMonths; num? eomWarrantyMonthsNo; // Now nullable
num eomWarrantyMonthsNo; num? warrantyValue; // Now nullable
num warrantyValue; String? warrantyEndDate; // Now nullable
String warrantyEndDate; String? warrantyContractConditions; // Now nullable
String warrantyContractConditions; List<TechnicalGuidanceBook>? technicalGuidanceBooks; // Now nullable
List<TechnicalGuidanceBook> technicalGuidanceBooks; String? comment; // Now nullable
String comment; String? tagCode; // Now nullable
String tagCode; String? assetPhoto;
String assetPhoto;
Asset copyWith({ Asset copyWith({
num id, num? id,
String assetSerialNo, String? assetSerialNo,
String systemID, String? systemID,
String assetNumber, String? assetNumber,
ModelDefinition modelDefinition, ModelDefinition? modelDefinition,
Supplier supplier, Supplier? supplier,
String ipAddress, String? ipAddress,
String macAddress, String? macAddress,
String portNumber, String? portNumber,
Lookup assetReplace, Lookup? assetReplace,
AssetInfo oldAsset, AssetInfo? oldAsset,
Lookup isParent, Lookup? isParent,
AssetInfo parentAsset, AssetInfo? parentAsset,
Lookup assetType, Lookup? assetType,
Site site, Site? site,
Building building, Building? building,
Floor floor, Floor? floor,
Department department, Department? department,
Rooms room, Rooms? room,
num testsDay, num? testsDay,
num purchasingPrice, num? purchasingPrice,
String nbv, String? nbv,
Lookup currency, Lookup? currency,
String poNo, String? poNo,
String invoiceNumber, String? invoiceNumber,
String invoiceDate, String? invoiceDate,
String replacementDate, String? replacementDate,
Department originDepartment, Department? originDepartment,
Site originSite, Site? originSite,
num budgetYear, num? budgetYear,
num lastPOPrice, num? lastPOPrice,
Lookup commissioningStatus, Lookup? commissioningStatus,
String productionDate, String? productionDate,
String edd, String? edd,
String technicalInspectionDate, String? technicalInspectionDate,
String deliveryInspectionDate, String? deliveryInspectionDate,
String endUserAcceptanceDate, String? endUserAcceptanceDate,
String receivingCommittee, String? receivingCommittee,
Lookup siteWarrantyMonths, Lookup? siteWarrantyMonths,
Lookup extendedWarrantyMonths, Lookup? extendedWarrantyMonths,
Lookup remainderWarrantyMonths, Lookup? remainderWarrantyMonths,
num eomWarrantyMonthsNo, num? eomWarrantyMonthsNo,
num warrantyValue, num? warrantyValue,
String warrantyEndDate, String? warrantyEndDate,
String warrantyContractConditions, String? warrantyContractConditions,
List<TechnicalGuidanceBook> technicalGuidanceBooks, List<TechnicalGuidanceBook>? technicalGuidanceBooks,
String comment, String? comment,
String tagCode, String? tagCode,
String assetPhoto, String? assetPhoto,
}) => }) =>
Asset( Asset(
id: id ?? this.id, id: id ?? this.id,
@ -280,65 +279,65 @@ class Asset {
map['systemID'] = systemID; map['systemID'] = systemID;
map['assetNumber'] = assetNumber; map['assetNumber'] = assetNumber;
if (modelDefinition != null) { if (modelDefinition != null) {
map['modelDefinition'] = modelDefinition.toJson(); map['modelDefinition'] = modelDefinition!.toJson();
} }
if (supplier != null) { if (supplier != null) {
map['supplier'] = supplier.toJson(); map['supplier'] = supplier!.toJson();
} }
map['ipAddress'] = ipAddress; map['ipAddress'] = ipAddress;
map['macAddress'] = macAddress; map['macAddress'] = macAddress;
map['portNumber'] = portNumber; map['portNumber'] = portNumber;
if (assetReplace != null) { if (assetReplace != null) {
map['assetReplace'] = assetReplace.toJson(); map['assetReplace'] = assetReplace!.toJson();
} }
if (oldAsset != null) { if (oldAsset != null) {
map['oldAsset'] = oldAsset.toJson(); map['oldAsset'] = oldAsset!.toJson();
} }
if (isParent != null) { if (isParent != null) {
map['isParent'] = isParent.toJson(); map['isParent'] = isParent!.toJson();
} }
if (parentAsset != null) { if (parentAsset != null) {
map['parentAsset'] = parentAsset.toJson(); map['parentAsset'] = parentAsset!.toJson();
} }
if (assetType != null) { if (assetType != null) {
map['assetType'] = assetType.toJson(); map['assetType'] = assetType!.toJson();
} }
if (site != null) { if (site != null) {
map['site'] = site.toJson(); map['site'] = site!.toJson();
} }
if (building != null) { if (building != null) {
map['building'] = building.toJson(); map['building'] = building!.toJson();
} }
if (floor != null) { if (floor != null) {
map['floor'] = floor.toJson(); map['floor'] = floor!.toJson();
} }
if (department != null) { if (department != null) {
map['department'] = department.toJson(); map['department'] = department!.toJson();
} }
// map['room'] = room; // map['room'] = room;
if (room != null) { if (room != null) {
map['room'] = room.toJson(); map['room'] = room!.toJson();
} }
map['testsDay'] = testsDay; map['testsDay'] = testsDay;
map['purchasingPrice'] = purchasingPrice; map['purchasingPrice'] = purchasingPrice;
map['nbv'] = nbv; map['nbv'] = nbv;
if (currency != null) { if (currency != null) {
map['currency'] = currency.toJson(); map['currency'] = currency!.toJson();
} }
map['poNo'] = poNo; map['poNo'] = poNo;
map['invoiceNumber'] = invoiceNumber; map['invoiceNumber'] = invoiceNumber;
map['invoiceDate'] = invoiceDate; map['invoiceDate'] = invoiceDate;
map['replacementDate'] = replacementDate; map['replacementDate'] = replacementDate;
if (originDepartment != null) { if (originDepartment != null) {
map['originDepartment'] = originDepartment.toJson(); map['originDepartment'] = originDepartment!.toJson();
} }
if (originSite != null) { if (originSite != null) {
map['originSite'] = originSite.toJson(); map['originSite'] = originSite!.toJson();
} }
map['budgetYear'] = budgetYear; map['budgetYear'] = budgetYear;
map['lastPOPrice'] = lastPOPrice; map['lastPOPrice'] = lastPOPrice;
if (commissioningStatus != null) { if (commissioningStatus != null) {
map['commissioningStatus'] = commissioningStatus.toJson(); map['commissioningStatus'] = commissioningStatus!.toJson();
} }
map['productionDate'] = productionDate; map['productionDate'] = productionDate;
map['edd'] = edd; map['edd'] = edd;
@ -347,20 +346,20 @@ class Asset {
map['endUserAcceptanceDate'] = endUserAcceptanceDate; map['endUserAcceptanceDate'] = endUserAcceptanceDate;
map['receivingCommittee'] = receivingCommittee; map['receivingCommittee'] = receivingCommittee;
if (siteWarrantyMonths != null) { if (siteWarrantyMonths != null) {
map['siteWarrantyMonths'] = siteWarrantyMonths.toJson(); map['siteWarrantyMonths'] = siteWarrantyMonths!.toJson();
} }
if (extendedWarrantyMonths != null) { if (extendedWarrantyMonths != null) {
map['extendedWarrantyMonths'] = extendedWarrantyMonths.toJson(); map['extendedWarrantyMonths'] = extendedWarrantyMonths!.toJson();
} }
if (remainderWarrantyMonths != null) { if (remainderWarrantyMonths != null) {
map['remainderWarrantyMonths'] = remainderWarrantyMonths.toJson(); map['remainderWarrantyMonths'] = remainderWarrantyMonths!.toJson();
} }
map['eomWarrantyMonthsNo'] = eomWarrantyMonthsNo; map['eomWarrantyMonthsNo'] = eomWarrantyMonthsNo;
map['warrantyValue'] = warrantyValue; map['warrantyValue'] = warrantyValue;
map['warrantyEndDate'] = warrantyEndDate; map['warrantyEndDate'] = warrantyEndDate;
map['warrantyContractConditions'] = warrantyContractConditions; map['warrantyContractConditions'] = warrantyContractConditions;
if (technicalGuidanceBooks != null) { if (technicalGuidanceBooks != null) {
map['technicalGuidanceBooks'] = technicalGuidanceBooks.map((v) => v.toJson()).toList(); map['technicalGuidanceBooks'] = technicalGuidanceBooks!.map((v) => v.toJson()).toList();
} }
map['comment'] = comment; map['comment'] = comment;
map['tagCode'] = tagCode; map['tagCode'] = tagCode;
@ -388,20 +387,20 @@ class AssetInfo {
assetName = json['assetName']; assetName = json['assetName'];
} }
num id; num? id; // Now nullable
String assetSerialNo; String? assetSerialNo; // Now nullable
String assetNumber; String? assetNumber; // Now nullable
String tagCode; String? tagCode; // Now nullable
String systemId; String? systemId; // Now nullable
String assetName; String? assetName; // Now nullable
AssetInfo copyWith({ AssetInfo copyWith({
num id, num? id, // Parameters are now nullable
String assetSerialNo, String? assetSerialNo,
String assetNumber, String? assetNumber,
String tagCode, String? tagCode,
String systemId, String? systemId,
String assetName, String? assetName,
}) => }) =>
AssetInfo( AssetInfo(
id: id ?? this.id, id: id ?? this.id,

@ -1,8 +1,8 @@
import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/lookup.dart';
class AssetSearch { class AssetSearch {
AssetSearch({ AssetSearch(
this.code, {this.code,
this.assetSerialNumber, this.assetSerialNumber,
this.assetName, this.assetName,
this.supplyDateSymbol, this.supplyDateSymbol,
@ -29,8 +29,7 @@ class AssetSearch {
this.assetGroupName, this.assetGroupName,
this.assetGroup, this.assetGroup,
this.oracleCodeTypeId, this.oracleCodeTypeId,
this.oracleCodeValue this.oracleCodeValue});
});
AssetSearch.fromJson(dynamic json) { AssetSearch.fromJson(dynamic json) {
code = json['code']; code = json['code'];
@ -63,65 +62,64 @@ class AssetSearch {
oracleCodeValue = json['assetOracleCodeValue']; oracleCodeValue = json['assetOracleCodeValue'];
} }
String code; String? code; // Now nullable
String assetSerialNumber; String? assetSerialNumber; // Now nullable
String assetName; String? assetName; // Now nullable
Lookup supplyDateSymbol; Lookup? supplyDateSymbol; // Now nullable
String supplyDateFrom; String? supplyDateFrom; // Now nullable
String supplyDateTo; String? supplyDateTo; // Now nullable
num warrantyEndDateSymbol; num? warrantyEndDateSymbol; // Now nullable
String warrantyEndDateFrom; String? warrantyEndDateFrom; // Now nullable
String warrantyEndDateTo; String? warrantyEndDateTo; // Now nullable
num delieveryInspectionDateSymbol; num? delieveryInspectionDateSymbol; // Now nullable
String deliveryInspectionDateFrom; String? deliveryInspectionDateFrom; // Now nullable
String deliveryInspectionDateTo; String? deliveryInspectionDateTo; // Now nullable
Lookup maintenanceContract; Lookup? maintenanceContract; // Now nullable
Lookup assetClassification; Lookup? assetClassification; // Now nullable
Lookup assetStatus; Lookup? assetStatus; // Now nullable
Lookup assetNotScraped; Lookup? assetNotScraped; // Now nullable
String assetNo; String? assetNo; // Now nullable
String modelDefinition; String? modelDefinition; // Now nullable
String site; String? site; // Now nullable
String manufacturer; String? manufacturer; // Now nullable
String model; String? model; // Now nullable
String department; String? department; // Now nullable
String supplier; String? supplier; // Now nullable
String tagCode; String? tagCode; // Now nullable
String assetGroupName; String? assetGroupName; // Now nullable
Lookup assetGroup; Lookup? assetGroup; // Now nullable
String oracleCodeValue; String? oracleCodeValue; // Now nullable
int oracleCodeTypeId; int? oracleCodeTypeId;
AssetSearch copyWith({ AssetSearch copyWith(
String code, {String? code,
String assetSerialNumber, String? assetSerialNumber,
String assetName, String? assetName,
Lookup supplyDateSymbol, Lookup? supplyDateSymbol,
String supplyDateFrom, String? supplyDateFrom,
String supplyDateTo, String? supplyDateTo,
num warrantyEndDateSymbol, num? warrantyEndDateSymbol,
String warrantyEndDateFrom, String? warrantyEndDateFrom,
String warrantyEndDateTo, String? warrantyEndDateTo,
num delieveryInspectionDateSymbol, num? delieveryInspectionDateSymbol,
String deliveryInspectionDateFrom, String? deliveryInspectionDateFrom,
String deliveryInspectionDateTo, String? deliveryInspectionDateTo,
Lookup maintenanceContract, Lookup? maintenanceContract,
Lookup assetClassification, Lookup? assetClassification,
Lookup assetStatus, Lookup? assetStatus,
Lookup assetNotScraped, Lookup? assetNotScraped,
String assetNo, String? assetNo,
String modelDefinition, String? modelDefinition,
String site, String? site,
String manufacturer, String? manufacturer,
String model, String? model,
String department, String? department,
String supplier, String? supplier,
String tagCode, String? tagCode,
String assetGroupName, String? assetGroupName,
Lookup assetGroup, Lookup? assetGroup,
String oracleCodeValue, String? oracleCodeValue,
int oracleCodeTypeId int? oracleCodeTypeId}) =>
}) =>
AssetSearch( AssetSearch(
code: code ?? this.code, code: code ?? this.code,
assetSerialNumber: assetSerialNumber ?? this.assetSerialNumber, assetSerialNumber: assetSerialNumber ?? this.assetSerialNumber,
@ -150,50 +148,49 @@ class AssetSearch {
assetGroupName: assetGroupName ?? this.assetGroupName, assetGroupName: assetGroupName ?? this.assetGroupName,
assetGroup: assetGroup ?? this.assetGroup, assetGroup: assetGroup ?? this.assetGroup,
oracleCodeValue: oracleCodeValue ?? this.oracleCodeValue, oracleCodeValue: oracleCodeValue ?? this.oracleCodeValue,
oracleCodeTypeId: oracleCodeTypeId ?? this.oracleCodeTypeId oracleCodeTypeId: oracleCodeTypeId ?? this.oracleCodeTypeId);
);
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
if (code != null && code.isNotEmpty) map['code'] = code; if (code != null && code!.isNotEmpty) map['code'] = code;
if (assetSerialNumber != null && assetSerialNumber.isNotEmpty) map['assetSerialNumber'] = assetSerialNumber; if (assetSerialNumber != null && assetSerialNumber!.isNotEmpty) map['assetSerialNumber'] = assetSerialNumber;
if (assetName != null && assetName.isNotEmpty) map['assetName'] = assetName; if (assetName != null && assetName!.isNotEmpty) map['assetName'] = assetName;
if (supplyDateSymbol != null) { if (supplyDateSymbol != null) {
map['supplyDateSymbol'] = supplyDateSymbol.toJson(); map['supplyDateSymbol'] = supplyDateSymbol!.toJson();
} }
if (supplyDateFrom != null && supplyDateFrom.isNotEmpty) map['supplyDateFrom'] = supplyDateFrom; if (supplyDateFrom != null && supplyDateFrom!.isNotEmpty) map['supplyDateFrom'] = supplyDateFrom;
if (supplyDateTo != null && supplyDateTo.isNotEmpty) map['supplyDateTo'] = supplyDateTo; if (supplyDateTo != null && supplyDateTo!.isNotEmpty) map['supplyDateTo'] = supplyDateTo;
if (warrantyEndDateSymbol != null) map['warrantyEndDateSymbol'] = warrantyEndDateSymbol; if (warrantyEndDateSymbol != null) map['warrantyEndDateSymbol'] = warrantyEndDateSymbol;
if (warrantyEndDateFrom != null && warrantyEndDateFrom.isNotEmpty) map['warrantyEndDateFrom'] = warrantyEndDateFrom; if (warrantyEndDateFrom != null && warrantyEndDateFrom!.isNotEmpty) map['warrantyEndDateFrom'] = warrantyEndDateFrom;
if (warrantyEndDateTo != null && warrantyEndDateTo.isNotEmpty) map['warrantyEndDateTo'] = warrantyEndDateTo; if (warrantyEndDateTo != null && warrantyEndDateTo!.isNotEmpty) map['warrantyEndDateTo'] = warrantyEndDateTo;
if (delieveryInspectionDateSymbol != null) map['delieveryInspectionDateSymbol'] = delieveryInspectionDateSymbol; if (delieveryInspectionDateSymbol != null) map['delieveryInspectionDateSymbol'] = delieveryInspectionDateSymbol;
if (deliveryInspectionDateFrom != null && deliveryInspectionDateFrom.isNotEmpty) map['deliveryInspectionDateFrom'] = deliveryInspectionDateFrom; if (deliveryInspectionDateFrom != null && deliveryInspectionDateFrom!.isNotEmpty) map['deliveryInspectionDateFrom'] = deliveryInspectionDateFrom;
if (deliveryInspectionDateTo != null && deliveryInspectionDateTo.isNotEmpty) map['deliveryInspectionDateTo'] = deliveryInspectionDateTo; if (deliveryInspectionDateTo != null && deliveryInspectionDateTo!.isNotEmpty) map['deliveryInspectionDateTo'] = deliveryInspectionDateTo;
if (maintenanceContract != null) { if (maintenanceContract != null) {
map['maintenanceContract'] = maintenanceContract.toJson(); map['maintenanceContract'] = maintenanceContract!.toJson();
} }
if (assetClassification != null) { if (assetClassification != null) {
map['assetClassification'] = assetClassification.toJson(); map['assetClassification'] = assetClassification!.toJson();
} }
if (assetStatus != null) { if (assetStatus != null) {
map['assetStatus'] = assetStatus.toJson(); map['assetStatus'] = assetStatus!.toJson();
} }
if (assetNotScraped != null) { if (assetNotScraped != null) {
map['assetNotScraped'] = assetNotScraped.toJson(); map['assetNotScraped'] = assetNotScraped!.toJson();
} }
if (assetNo != null && assetNo.isNotEmpty) map['assetNo'] = assetNo; if (assetNo != null && assetNo!.isNotEmpty) map['assetNo'] = assetNo;
if (modelDefinition != null && modelDefinition.isNotEmpty) map['modelDefinition'] = modelDefinition; if (modelDefinition != null && modelDefinition!.isNotEmpty) map['modelDefinition'] = modelDefinition;
if (site != null && site.isNotEmpty) map['site'] = site; if (site != null && site!.isNotEmpty) map['site'] = site;
if (manufacturer != null && manufacturer.isNotEmpty) map['manufacturer'] = manufacturer; if (manufacturer != null && manufacturer!.isNotEmpty) map['manufacturer'] = manufacturer;
if (model != null && model.isNotEmpty) map['model'] = model; if (model != null && model!.isNotEmpty) map['model'] = model;
if (department != null && department.isNotEmpty) map['department'] = department; if (department != null && department!.isNotEmpty) map['department'] = department;
if (supplier != null && supplier.isNotEmpty) map['supplier'] = supplier; if (supplier != null && supplier!.isNotEmpty) map['supplier'] = supplier;
if (tagCode != null && tagCode.isNotEmpty) map['tagCode'] = tagCode; if (tagCode != null && tagCode!.isNotEmpty) map['tagCode'] = tagCode;
if (assetGroupName != null && assetGroupName.isNotEmpty) map['assetGroupName'] = assetGroupName; if (assetGroupName != null && assetGroupName!.isNotEmpty) map['assetGroupName'] = assetGroupName;
if (assetGroup != null) { 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; if (oracleCodeTypeId != null) map['assetOracleCodeTypeId'] = oracleCodeTypeId;
return map; return map;
} }

@ -9,12 +9,12 @@ class AssetTransferAttachment {
attachmentName = json['attachmentName']; attachmentName = json['attachmentName'];
} }
num id; num? id; // Now nullable
String attachmentName; String? attachmentName; // Now nullable
AssetTransferAttachment copyWith({ AssetTransferAttachment copyWith({
num id, num? id, // Parameter is now nullable
String attachmentName, String? attachmentName, // Parameter is now nullable
}) => }) =>
AssetTransferAttachment( AssetTransferAttachment(
id: id ?? this.id, id: id ?? this.id,

@ -34,84 +34,44 @@ class ModelDefinition {
if (json['modelDefRelatedDefects'] != null) { if (json['modelDefRelatedDefects'] != null) {
modelDefRelatedDefects = []; modelDefRelatedDefects = [];
json['modelDefRelatedDefects'].forEach((v) { json['modelDefRelatedDefects'].forEach((v) {
modelDefRelatedDefects.add(ModelDefRelatedDefects.fromJson(v)); modelDefRelatedDefects!.add(ModelDefRelatedDefects.fromJson(v)); // Use '!' since modelDefRelatedDefects is initialized here
}); });
} }
if (json['suppliers'] != null) { if (json['suppliers'] != null) {
suppliers = []; suppliers = [];
json['suppliers'].forEach((v) { json['suppliers'].forEach((v) {
suppliers.add(Supplier.fromJson(v)); suppliers!.add(Supplier.fromJson(v)); // Use '!' since suppliers is initialized here
}); });
} }
} }
num id; num? id; // Now nullable
String assetName; String? assetName; // Now nullable
String assetDescription; String? assetDescription; // Now nullable
String modelDefCode; String? modelDefCode; // Now nullable
String modelName; String? modelName; // Now nullable
num manufacturerId; num? manufacturerId; // Now nullable
String manufacturerName; String? manufacturerName; // Now nullable
dynamic supplierName; String? supplierName; // Remains dynamic asit can hold various types
String replacementDate; String? replacementDate; // Now nullable
String essentialEquipement; String? essentialEquipement; // Now nullable
String businessCritical; String? businessCritical; // Now nullable
num lifeSpan; num? lifeSpan; // Now nullable
List<ModelDefRelatedDefects> modelDefRelatedDefects; List<ModelDefRelatedDefects>? modelDefRelatedDefects; // Now nullable
List<Supplier> suppliers; List<Supplier>? suppliers; // Now nullable
ModelDefinition copyWith({ // ... (copyWith method remains the same, just with nullable parameters)
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> modelDefRelatedDefects,
List<Supplier> 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,
);
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
map['id'] = id; map['id'] = id;
map['assetName'] = assetName; map['assetName'] = assetName;
map['assetDescription'] = assetDescription; // ... (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)
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;
if (modelDefRelatedDefects != null) { 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) { 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; return map;
} }
@ -132,23 +92,12 @@ class ModelDefRelatedDefects {
estimatedTime = json['estimatedTime']; estimatedTime = json['estimatedTime'];
} }
num id; num? id; // Now nullable
String defectName; String? defectName; // Now nullable
String workPerformed; String? workPerformed; // Now nullable
String estimatedTime; String? estimatedTime; // Now nullable
ModelDefRelatedDefects copyWith({ // ... (copyWith method remains the same, just with nullable parameters)
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,
);
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final map = <String, dynamic>{}; final map = <String, dynamic>{};

@ -9,12 +9,12 @@ class Supplier {
suppliername = json['suppliername']; suppliername = json['suppliername'];
} }
num id; num? id; // Now nullable
String suppliername; String? suppliername; // Now nullable
Supplier copyWith({ Supplier copyWith({
num id, num? id, // Parameter is now nullable
String suppliername, String? suppliername, // Parameter is now nullable
}) => }) =>
Supplier( Supplier(
id: id ?? this.id, id: id ?? this.id,

@ -8,12 +8,12 @@ class TechnicalGuidanceBook {
guidanceBook = json['guidanceBook'] != null ? Lookup.fromJson(json['guidanceBook']) : null; guidanceBook = json['guidanceBook'] != null ? Lookup.fromJson(json['guidanceBook']) : null;
} }
num id; num? id; // Now nullable
Lookup guidanceBook; Lookup? guidanceBook; // Nownullable
TechnicalGuidanceBook copyWith({ TechnicalGuidanceBook copyWith({
num id, num? id, // Parameter is now nullable
Lookup guidanceBook, Lookup? guidanceBook, // Parameter is now nullable
}) => }) =>
TechnicalGuidanceBook( TechnicalGuidanceBook(
id: id ?? this.id, id: id ?? this.id,
@ -24,7 +24,7 @@ class TechnicalGuidanceBook {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
map['id'] = id; map['id'] = id;
if (guidanceBook != null) { if (guidanceBook != null) {
map['guidanceBook'] = guidanceBook.toJson(); map['guidanceBook'] = guidanceBook?.toJson(); // Use '?.' for nullsafety
} }
return map; return map;
} }

@ -1,13 +1,13 @@
class Employee { class Employee {
String id; String? id;
String name; String? name;
Employee({ Employee({
this.id, this.id,
this.name, this.name,
}); });
factory Employee.fromJson(Map<String, dynamic> parsedJson) { factory Employee.fromJson(Map<String, dynamic>? parsedJson) {
if (parsedJson == null) return Employee(); if (parsedJson == null) return Employee();
return Employee( return Employee(
id: parsedJson["userId"] ?? parsedJson["id"], id: parsedJson["userId"] ?? parsedJson["id"],
@ -15,7 +15,7 @@ class Employee {
); );
} }
factory Employee.fromEngineer(Employee department) { factory Employee.fromEngineer(Employee? department) {
return Employee( return Employee(
id: department?.id, id: department?.id,
name: department?.name, name: department?.name,

@ -10,23 +10,23 @@ class FaultDescription extends Base {
FaultDescription.fromJson(dynamic json) { FaultDescription.fromJson(dynamic json) {
id = json['id']; id = json['id'];
identifier = id?.toString(); identifier = id.toString();
defectName = json['defectName']; defectName = json['defectName'];
name = defectName; name = defectName;
workPerformed = json['workPerformed']; workPerformed = json['workPerformed'];
estimatedTime = json['estimatedTime']; estimatedTime = json['estimatedTime'];
} }
num id; num? id;
String defectName; String? defectName;
String workPerformed; String? workPerformed;
String estimatedTime; String? estimatedTime;
FaultDescription copyWith({ FaultDescription copyWith({
num id, num? id,
String defectName, String? defectName,
String workPerformed, String? workPerformed,
String estimatedTime, String? estimatedTime,
}) => }) =>
FaultDescription( FaultDescription(
id: id ?? this.id, id: id ?? this.id,

@ -15,18 +15,18 @@ class GasRefillComment {
comment = json['comment']; comment = json['comment'];
} }
num id; num? id;
num gasRefillId; num? gasRefillId;
String createdOn; String? createdOn;
CreatedBy createdBy; CreatedBy? createdBy;
String comment; String? comment;
GasRefillComment copyWith({ GasRefillComment copyWith({
num id, num? id,
num callRequestId, num? callRequestId,
String createdOn, String? createdOn,
CreatedBy createdBy, CreatedBy? createdBy,
String comment, String? comment,
}) => }) =>
GasRefillComment( GasRefillComment(
id: id ?? this.id, id: id ?? this.id,
@ -42,7 +42,7 @@ class GasRefillComment {
map['gasRefillId'] = gasRefillId; map['gasRefillId'] = gasRefillId;
map['createdOn'] = createdOn; map['createdOn'] = createdOn;
if (createdBy != null) { if (createdBy != null) {
map['createdBy'] = createdBy.toJson(); map['createdBy'] = createdBy!.toJson();
} }
map['comment'] = comment; map['comment'] = comment;
return map; return map;
@ -60,14 +60,10 @@ class CreatedBy {
userName = json['userName']; userName = json['userName'];
} }
String userId; String? userId;
String userName; String? userName;
CreatedBy copyWith({ CreatedBy copyWith({String? userId, String? userName}) => CreatedBy(
String userId,
String userName,
}) =>
CreatedBy(
userId: userId ?? this.userId, userId: userId ?? this.userId,
userName: userName ?? this.userName, userName: userName ?? this.userName,
); );

@ -1,8 +1,8 @@
class Hospital { class Hospital {
int id; int? id;
int customerCode; int? customerCode;
String name; String? name;
List<Buildings> buildings; List<Buildings>? buildings;
Hospital({ Hospital({
this.id, this.id,
@ -24,7 +24,7 @@ class Hospital {
return Hospital(id: parsedJson["id"], name: parsedJson["custName"], customerCode: parsedJson["customerCode"], buildings: buildings); 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); return Hospital(id: hospital?.id, name: hospital?.name, customerCode: hospital?.customerCode, buildings: hospital?.buildings);
} }
@ -66,10 +66,10 @@ class Hospital {
// } // }
class Buildings { class Buildings {
int id; int? id;
String name; String? name;
int value; int? value;
List<Floors> floors; List<Floors>? floors;
Buildings({this.id, this.name, this.value, this.floors}); Buildings({this.id, this.name, this.value, this.floors});
@ -80,7 +80,7 @@ class Buildings {
if (json['floors'] != null) { if (json['floors'] != null) {
floors = []; floors = [];
json['floors'].forEach((v) { json['floors'].forEach((v) {
floors.add(Floors.fromJson(v)); floors!.add(Floors.fromJson(v));
}); });
} }
} }
@ -91,17 +91,17 @@ class Buildings {
data['name'] = name; data['name'] = name;
data['value'] = value; data['value'] = value;
if (floors != null && includeFloors) { if (floors != null && includeFloors) {
data['floors'] = floors.map((v) => v.toJson()).toList(); data['floors'] = floors!.map((v) => v.toJson()).toList();
} }
return data; return data;
} }
} }
class Floors { class Floors {
int id; int? id;
String name; String? name;
int value; int? value;
List<Departments> departments; List<Departments>? departments;
Floors({this.id, this.name, this.value, this.departments}); Floors({this.id, this.name, this.value, this.departments});
@ -112,7 +112,7 @@ class Floors {
if (json['departments'] != null) { if (json['departments'] != null) {
departments = []; departments = [];
json['departments'].forEach((v) { json['departments'].forEach((v) {
departments.add(Departments.fromJson(v)); departments!.add(Departments.fromJson(v));
}); });
} }
} }
@ -123,15 +123,15 @@ class Floors {
data['name'] = name; data['name'] = name;
data['value'] = value; data['value'] = value;
if (departments != null && includeDepartments) { if (departments != null && includeDepartments) {
data['departments'] = departments.map((v) => v.toJson()).toList(); data['departments'] = departments!.map((v) => v.toJson()).toList();
} }
return data; return data;
} }
} }
class Departments { class Departments {
int id; int? id;
String name; String? name;
Departments({this.id, this.name}); Departments({this.id, this.name});

@ -1,10 +1,10 @@
class Issue { class Issue {
String title; String? title;
String userId; String? userId;
List<int> reports; List<int>? reports;
String serviceRequestId; String? serviceRequestId;
String description; String? description;
bool isSelected; bool? isSelected;
Issue({ Issue({
this.description, this.description,
@ -17,11 +17,11 @@ class Issue {
Map<String, String> toMap() { Map<String, String> toMap() {
Map<String, String> map = {}; Map<String, String> map = {};
if (title != null) map["title"] = title; if (title != null) map["title"] = title!;
if (reports != null) map["issue_report"] = reports.toString(); if (reports != null) map["issue_report"] = reports!.toString();
if (userId != null) map["uid"] = userId; if (userId != null) map["uid"] = userId!;
if (description != null) map["desc"] = description; if (description != null) map["desc"] = description!;
if (serviceRequestId != null) map["call_id"] = serviceRequestId; if (serviceRequestId != null) map["call_id"] = serviceRequestId!;
return map; return map;
} }
} }

@ -1,30 +1,35 @@
import 'base.dart'; import 'base.dart';
class Lookup extends Base { 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 @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 @override
int get hashCode => id?.hashCode ?? value?.hashCode; int get hashCode => id.hashCode ^ value.hashCode; // Use XOR for hash code combination
toJson() { Map<String, dynamic> toJson() { // Return a Map instead of calling a function
return {"id": id, "name": name, "value": value}; 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; if (old == null) return null;
return Lookup( return Lookup(
name: old.name, name: old.name,id: old.id,
id: old.id,
value: old.value, value: old.value,
); );
} }
factory Lookup.fromJson(Map<String, dynamic> parsedJson) { // CreatedBy.fromJson(dynamic json) {
// userId = json['userId'] ?? '';
// userName = json['userName'] ?? '';
// }
Lookup.fromJson(Map<String, dynamic>? parsedJson) { // Now accepts nullable Map and returns nullable Lookup
if (parsedJson == null) return null; if (parsedJson == null) return null;
return Lookup( return Lookup(
name: parsedJson["name"], name: parsedJson["name"],

@ -9,12 +9,12 @@ class AssignedEmployee {
name = json['name']; name = json['name'];
} }
String id; String? id; // Now nullable
String name; String? name; // Now nullable
AssignedEmployee copyWith({ AssignedEmployee copyWith({
String id, String? id, // Parameters are now nullable
String name, String? name,
}) => }) =>
AssignedEmployee( AssignedEmployee(
id: id ?? this.id, id: id ?? this.id,

@ -14,12 +14,12 @@ class AssistantEmployees extends Base {
identifier = user?.id; identifier = user?.id;
} }
num id; num? id; // Now nullable
AssignedEmployee user; AssignedEmployee? user; // Now nullable
AssistantEmployees copyWith({ AssistantEmployees copyWith({
num id, num? id, // Parameter is now nullable
AssignedEmployee user, AssignedEmployee? user, // Parameter is now nullable
}) => }) =>
AssistantEmployees( AssistantEmployees(
id: id ?? this.id, id: id ?? this.id,
@ -30,7 +30,7 @@ class AssistantEmployees extends Base {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
map['id'] = id; map['id'] = id;
if (user != null) { if (user != null) {
map['user'] = user.toJson(); map['user'] = user?.toJson(); // Use '?.' to handle potential null
} }
return map; return map;
} }

@ -6,31 +6,31 @@ class Building extends Base {
this.id, this.id,
this.value, this.value,
this.floors, this.floors,
String name, String? name,
}) : super(identifier: id.toString(), name: name); }) : super(identifier: id?.toString() ?? '', name: name); // Handle potential null id
Building.fromJson(dynamic json) { Building.fromJson(dynamic json) {
id = json['id']; id = json['id'];
identifier = id.toString(); identifier = id?.toString() ?? ''; // Handle potential null id
name = json['name']; name = json['name'];
value = json['value']; value = json['value'];
if (json['floors'] != null) { if (json['floors'] != null) {
floors = []; floors = [];
json['floors'].forEach((v) { json['floors'].forEach((v) {
floors.add(Floor.fromJson(v)); floors!.add(Floor.fromJson(v));
}); });
} }
} }
num id; num? id;
num value; num? value;
List<Floor> floors; List<Floor>? floors;
Building copyWith({ Building copyWith({
num id, num? id,
String name, String? name,
num value, num? value,
List<Floor> floors, List<Floor>? floors,
}) => }) =>
Building( Building(
id: id ?? this.id, id: id ?? this.id,
@ -46,7 +46,7 @@ class Building extends Base {
map['value'] = value; map['value'] = value;
if (addFloor) { if (addFloor) {
if (floors != null) { if (floors != null) {
map['floors'] = floors.map((v) => v.toJson()).toList(); map['floors'] = floors!.map((v) => v.toJson()).toList();
} }
} }

@ -10,33 +10,40 @@ class Department extends Base {
this.departmentId, this.departmentId,
this.ntCode, this.ntCode,
this.rooms, this.rooms,
}) : super(identifier: id.toString(), name: departmentName); }) : super(identifier: id?.toString() ?? '', name: departmentName); // Handle potential null id
Department.fromJson(dynamic json) { Department.fromJson(dynamic json) {
id = json['id']; id = json['id'];
identifier = id.toString(); identifier = id?.toString() ?? ''; // Handle potential null id
departmentName = json['departmentName'] ?? json['name']; departmentName = json['departmentName'] ?? json['name'];
name = departmentName; name = departmentName;
departmentCode = json['departmentCode']; departmentCode = json['departmentCode'];
departmentId = json['departmentId']; departmentId = json['departmentId'];
ntCode = json['ntCode']; ntCode = json['ntCode'];
rooms = <Rooms>[];
if (json['rooms'] != null) { if (json['rooms'] != null) {
rooms = [];
json['rooms'].forEach((v) { json['rooms'].forEach((v) {
rooms.add(Rooms.fromJson(v)); rooms!.add(Rooms.fromJson(v)); // Use '!' since rooms is non-nullable after initialization
}); });
} }
} }
num id; num? id; // Now nullable
String departmentName; String? departmentName; // Now nullable
String departmentCode; String? departmentCode; // Now nullable
String departmentId; String? departmentId; // Now nullable
String ntCode; String? ntCode; // Now nullable
List<Rooms>? rooms; // Now nullable
List<Rooms> rooms; Department copyWith({
num? id, // Parameters are now nullable
Department copyWith({num id, String departmentName, String departmentCode, String ntCode, List<Rooms> rooms}) => Department( String? departmentName,
String? departmentCode,
String? departmentId,
String? ntCode,
List<Rooms>? rooms,
}) =>
Department(
id: id ?? this.id, id: id ?? this.id,
departmentName: departmentName ?? this.departmentName, departmentName: departmentName ?? this.departmentName,
departmentCode: departmentCode ?? this.departmentCode, departmentCode: departmentCode ?? this.departmentCode,
@ -53,7 +60,7 @@ class Department extends Base {
map['departmentId'] = departmentId; map['departmentId'] = departmentId;
map['ntCode'] = ntCode; map['ntCode'] = ntCode;
if (rooms != null) { 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; return map;
} }

@ -4,33 +4,33 @@ import 'package:test_sa/models/new_models/department.dart';
class Floor extends Base { class Floor extends Base {
Floor({ Floor({
this.id, this.id,
String name, String? name, // Name is now nullable
this.value, this.value,
this.departments, this.departments,
}) : super(identifier: id.toString(), name: name); }) : super(identifier: id?.toString() ?? '', name: name); // Handle potentialnull id
Floor.fromJson(dynamic json) { Floor.fromJson(dynamic json) {
id = json['id']; id = json['id'];
identifier = id.toString(); identifier = id?.toString() ?? ''; // Handle potential null id
name = json['name']; name = json['name'];
value = json['value']; value = json['value'];
if (json['departments'] != null) { if (json['departments'] != null) {
departments = []; departments = [];
json['departments'].forEach((v) { 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? id; // Now nullable
num value; num? value; //Now nullable
List<Department> departments; List<Department>? departments; // Now nullable
Floor copyWith({ Floor copyWith({
num id, num? id, // Parameters are now nullable
String name, String? name,
num value, num? value,
List<Department> departments, List<Department>? departments,
}) => }) =>
Floor( Floor(
id: id ?? this.id, id: id ?? this.id,
@ -44,8 +44,10 @@ class Floor extends Base {
map['id'] = id; map['id'] = id;
map['name'] = name; map['name'] = name;
map['value'] = value; map['value'] = value;
if (addDepartments) if (departments != null) { if (addDepartments) {
map['departments'] = departments.map((v) => v.toJson()).toList(); if (departments != null) {
map['departments'] = departments!.map((v) => v.toJson()).toList(); // Use '!' since departments could be null
}
} }
return map; return map;
} }

@ -49,17 +49,18 @@ class GasRefillModel {
comment = json['comment']; comment = json['comment'];
workingHours = json['workingHours']; workingHours = json['workingHours'];
try { try {
final sd = DateTime.tryParse(startDate ?? ""); final DateTime? sd = DateTime.tryParse(startDate ?? "");
final st = DateTime.tryParse(startTime ?? ""); final DateTime? st = DateTime.tryParse(startTime ?? "");
final ed = DateTime.tryParse(endDate ?? ""); final DateTime? ed = DateTime.tryParse(endDate ?? "");
final et = DateTime.tryParse(endTime ?? ""); final DateTime? et = DateTime.tryParse(endTime ?? "");
timer = TimerModel( timer = TimerModel(
startAt: st == null ? sd : sd.add(Duration(hours: st.hour, minutes: st.minute, seconds: st.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)), 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) { if (timer!.endAt != null && timer!.startAt != null) {
timer.durationInSecond = (timer.endAt.difference(timer.startAt))?.inSeconds; // Use '!' since timer could be null after initialization
workingHours = (((timer.durationInSecond ?? 0) / 60) / 60); timer!.durationInSecond = (timer!.endAt!.difference(timer!.startAt!)).inSeconds;
workingHours = (((timer!.durationInSecond ?? 0) / 60) / 60);
} }
} catch (e) { } catch (e) {
print(e); print(e);
@ -75,55 +76,55 @@ class GasRefillModel {
if (json['gazRefillDetails'] != null) { if (json['gazRefillDetails'] != null) {
gazRefillDetails = []; gazRefillDetails = [];
json['gazRefillDetails'].forEach((v) { json['gazRefillDetails'].forEach((v) {
gazRefillDetails.add(GasRefillDetails.fromJson(v)); gazRefillDetails!.add(GasRefillDetails.fromJson(v)); // Use '!' since gazRefillDetails is initialized here
}); });
} }
} }
num id; num? id; // Now nullable
String gazRefillNo; String? gazRefillNo; // Now nullable
String expectedDate; String? expectedDate; // Now nullable
String expectedTime; String? expectedTime; // Now nullable
String startDate; String? startDate; // Now nullable
String startTime; String? startTime; // Now nullable
String endDate; String? endDate; // Now nullable
String endTime; String? endTime; // Now nullable
String engSignature; String? engSignature; // Now nullable
String nurseSignature; String? nurseSignature; // Now nullable
num workingHours; num? workingHours; // Now nullable
Site site; Site? site; // Now nullable
Building building; Building? building; // Now nullable
Floor floor; Floor? floor; // Now nullable
Department department; Department? department; // Now nullable
AssignedEmployee assignedEmployee; AssignedEmployee? assignedEmployee; // Now nullable
Lookup status; Lookup? status; // Now nullable
String comment; String? comment; // Now nullable
List<GasRefillDetails> gazRefillDetails; List<GasRefillDetails>? gazRefillDetails; // Now nullable
Uint8List localNurseSignature; Uint8List? localNurseSignature; // Now nullable
Uint8List localEngineerSignature; Uint8List? localEngineerSignature; // Now nullable
TimerModel timer = TimerModel(); TimerModel? timer; // Now nullable
GasRefillModel copyWith({ GasRefillModel copyWith({
num id, num? id, // Parameters are now nullable
String gazRefillNo, String? gazRefillNo,
String expectedDate, String? expectedDate,
String expectedTime, String? expectedTime,
String startDate, String? startDate,
String startTime, String? startTime,
String endDate, String? endDate,
String endTime, String? endTime,
String engSignature, String? engSignature,
String nurseSignature, String? nurseSignature,
num workingHours, num? workingHours,
Site site, Site? site,
Building building, Building? building,
Floor floor, Floor? floor,
Department department, Department? department,
AssignedEmployee assignedEmployee, AssignedEmployee? assignedEmployee,
Lookup status, Lookup? status,
String comment, String? comment,
List<GasRefillDetails> gazRefillDetails, List<GasRefillDetails>? gazRefillDetails,
TimerModel timer, TimerModel? timer,
}) => }) =>
GasRefillModel( GasRefillModel(
id: id ?? this.id, id: id ?? this.id,
@ -163,25 +164,25 @@ class GasRefillModel {
map['workingHours'] = workingHours; map['workingHours'] = workingHours;
map['comment'] = comment; map['comment'] = comment;
if (site != null) { if (site != null) {
map['site'] = site.toJson(addBuildings: false); map['site'] = site?.toJson(addBuildings: false); // Use '?.' for null safety
} }
if (building != null) { if (building != null) {
map['building'] = building.toJson(addFloor: false); map['building'] = building?.toJson(addFloor: false); // Use '?.' for null safety
} }
if (floor != null) { if (floor != null) {
map['floor'] = floor.toJson(addDepartments: false); map['floor'] = floor?.toJson(addDepartments: false); // Use '?.' for null safety
} }
if (department != null) { if (department != null) {
map['department'] = department.toJson(); map['department'] = department?.toJson(); // Use '?.' for null safety
} }
if (assignedEmployee != null) { if (assignedEmployee != null) {
map['assignedEmployee'] = assignedEmployee.toJson(); map['assignedEmployee'] = assignedEmployee?.toJson(); // Use '?.' for null safety
} }
if (status != null) { if (status != null) {
map['status'] = status.toJson(); map['status'] = status?.toJson(); // Use '?.' for null safety
} }
if (gazRefillDetails != null) { 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; return map;
} }
@ -227,7 +228,15 @@ class GasRefillModel {
} }
class GasRefillDetails { 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) { GasRefillDetails.fromJson(dynamic json) {
id = json['id']; id = json['id'];
@ -238,21 +247,22 @@ class GasRefillDetails {
deliverdQty = json['deliverdQty']; deliverdQty = json['deliverdQty'];
} }
num id; num? id; // Now nullable
Lookup gasType; Lookup? gasType; // Now nullable
Lookup cylinderType; Lookup? cylinderType; // Now nullable
Lookup cylinderSize; Lookup? cylinderSize; // Now nullable
num requestedQty; num? requestedQty; // Now nullable
num deliverdQty; num? deliverdQty; // Now nullable
bool selectedForEditing; bool? selectedForEditing; // Now nullable
GasRefillDetails copyWith({ GasRefillDetails copyWith({
num id, num? id, // Parameters are now nullable
Lookup gasType, Lookup? gasType,
Lookup cylinderType, Lookup? cylinderType,
Lookup cylinderSize, Lookup? cylinderSize,
num requestedQty, num? requestedQty,
num deliverdQty, num? deliverdQty,
bool? selectedForEditing,
}) => }) =>
GasRefillDetails( GasRefillDetails(
id: id ?? this.id, id: id ?? this.id,
@ -261,19 +271,20 @@ class GasRefillDetails {
cylinderSize: cylinderSize ?? this.cylinderSize, cylinderSize: cylinderSize ?? this.cylinderSize,
requestedQty: requestedQty ?? this.requestedQty, requestedQty: requestedQty ?? this.requestedQty,
deliverdQty: deliverdQty ?? this.deliverdQty, deliverdQty: deliverdQty ?? this.deliverdQty,
selectedForEditing: selectedForEditing ?? this.selectedForEditing,
); );
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final map = <String, dynamic>{}; final map = <String, dynamic>{};
map['id'] = id ?? 0; map['id'] = id ?? 0;
if (gasType != null) { if (gasType != null) {
map['gasType'] = gasType.toJson(); map['gasType'] = gasType?.toJson(); // Use '?.' for null safety
} }
if (cylinderType != null) { if (cylinderType != null) {
map['cylinderType'] = cylinderType.toJson(); map['cylinderType'] = cylinderType?.toJson(); // Use '?.' for null safety
} }
if (cylinderSize != null) { if (cylinderSize != null) {
map['cylinderSize'] = cylinderSize.toJson(); map['cylinderSize'] = cylinderSize?.toJson(); // Use '?.' for null safety
} }
map['requestedQty'] = requestedQty; map['requestedQty'] = requestedQty;
map['deliverdQty'] = deliverdQty; map['deliverdQty'] = deliverdQty;

@ -1,16 +1,17 @@
import 'package:test_sa/models/base.dart'; import 'package:test_sa/models/base.dart';
class Rooms extends Base { class Rooms extends Base {
int id; int? id; // Now nullable
String name; String? name; // Now nullable
int value; 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<String, dynamic> json) { Rooms.fromJson(Map<String, dynamic>? json) {
id = json['id']; // Handle potential null json input
name = json['name']; id = json?['id']; // Use null-aware operator
value = json['value']; name = json?['name'];
value = json?['value'];
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
@ -21,25 +22,24 @@ class Rooms extends Base {
return data; return data;
} }
} }
//
// class Rooms extends Base { // class Rooms extends Base {
// int id; // int? id; // Now nullable
// int departmentId; // int? departmentId; // Now nullable
// int clientRoomId; // int? clientRoomId; // Now nullable
// String roomName; // 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<String, dynamic> json) { // Rooms.fromJson(Map<String, dynamic>? json) { // Handle potential null json input
// id = json['id']; // id = json?['id']; // Use null-aware operator
// departmentId = json['departmentId']; // departmentId = json?['departmentId'];
// clientRoomId = json['clientRoomId']; // clientRoomId = json?['clientRoomId'];
// roomName = json['roomName']; // roomName = json?['roomName'];
// } // }
// //
// Map<String, dynamic> toJson() { // Map<String, dynamic> toJson() {
// final Map<String, dynamic> data = new Map<String, dynamic>(); // final Map<String, dynamic> data = new Map<String, dynamic>();// data['id'] = this.id;
// data['id'] = this.id;
// data['departmentId'] = this.departmentId; // data['departmentId'] = this.departmentId;
// data['clientRoomId'] = this.clientRoomId; // data['clientRoomId'] = this.clientRoomId;
// data['roomName'] = this.roomName; // data['roomName'] = this.roomName;

@ -6,29 +6,29 @@ class Site extends Base {
this.id, this.id,
this.custName, this.custName,
this.buildings, this.buildings,
}) : super(identifier: id.toString(), name: custName); }) : super(identifier: id?.toString() ?? '', name: custName); // Handle potential null id
Site.fromJson(dynamic json) { Site.fromJson(dynamic json) {
id = json['id']; id = json['id'];
identifier = id.toString(); identifier = id?.toString() ?? ''; // Handle potential null id
custName = json['custName']; custName = json['custName'];
name = custName; name = custName;
if (json['buildings'] != null) { if (json['buildings'] != null) {
buildings = []; buildings = [];
json['buildings'].forEach((v) { json['buildings'].forEach((v) {
buildings.add(Building.fromJson(v)); buildings!.add(Building.fromJson(v)); // Use '!' since buildings is initialized here
}); });
} }
} }
num id; num? id; // Now nullable
String custName; String? custName; // Now nullable
List<Building> buildings; List<Building>? buildings; // Now nullable
Site copyWith({ Site copyWith({
num id, num? id, // Parameters are now nullable
String custName, String? custName,
List<Building> buildings, List<Building>? buildings,
}) => }) =>
Site( Site(
id: id ?? this.id, id: id ?? this.id,
@ -42,7 +42,7 @@ class Site extends Base {
map['custName'] = custName; map['custName'] = custName;
if (addBuildings) { if (addBuildings) {
if (buildings != null) { 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 { } else {
map['buildings'] = []; map['buildings'] = [];

@ -13,10 +13,10 @@ import 'package:test_sa/models/ppm/ppm_kit.dart';
import 'package:test_sa/models/timer_model.dart'; import 'package:test_sa/models/timer_model.dart';
class VisitTimers { class VisitTimers {
int id; int? id;
String startDateTime; String? startDateTime;
String endDateTime; String? endDateTime;
double workingHours; double? workingHours;
VisitTimers({this.id, this.startDateTime, this.endDateTime, this.workingHours}); VisitTimers({this.id, this.startDateTime, this.endDateTime, this.workingHours});
@ -102,7 +102,7 @@ class Ppm {
this.modelId, this.modelId,
this.modelName, this.modelName,
this.modifiedOn, this.modifiedOn,
bool notified, this.notified,
this.planCode, this.planCode,
this.planNo, this.planNo,
this.ppmId, this.ppmId,
@ -149,38 +149,38 @@ class Ppm {
if (json['vCalibrationTools'] != null) { if (json['vCalibrationTools'] != null) {
vCalibrationTools = []; vCalibrationTools = [];
json['vCalibrationTools'].forEach((v) { json['vCalibrationTools'].forEach((v) {
vCalibrationTools.add(PpmCalibrationTools.fromJson(v)); vCalibrationTools!.add(PpmCalibrationTools.fromJson(v));
}); });
} }
if (json['vKits'] != null) { if (json['vKits'] != null) {
vKits = []; vKits = [];
json['vKits'].forEach((v) { json['vKits'].forEach((v) {
vKits.add(PpmKits.fromJson(v)); vKits!.add(PpmKits.fromJson(v));
}); });
} }
if (json['vContacts'] != null) { if (json['vContacts'] != null) {
vContacts = []; vContacts = [];
json['vContacts'].forEach((v) { json['vContacts'].forEach((v) {
vContacts.add(PpmContacts.fromJson(v)); vContacts!.add(PpmContacts.fromJson(v));
}); });
} }
if (json['vChecklists'] != null) { if (json['vChecklists'] != null) {
vChecklists = []; vChecklists = [];
json['vChecklists'].forEach((v) { json['vChecklists'].forEach((v) {
vChecklists.add(PpmChecklists.fromJson(v)); vChecklists!.add(PpmChecklists.fromJson(v));
}); });
} }
if (json['vAttachments'] != null) { if (json['vAttachments'] != null) {
files = []; files = [];
json['vAttachments'].forEach((v) { json['vAttachments'].forEach((v) {
files.add(PpmAttachments.fromJson(v)); files!.add(PpmAttachments.fromJson(v));
}); });
} }
visitStatusId = json['visitStatusId']; visitStatusId = json['visitStatusId'];
visitTimers = <VisitTimers>[]; visitTimers = <VisitTimers>[];
if (json['visitTimers'] != null) { if (json['visitTimers'] != null) {
json['visitTimers'].forEach((v) { json['visitTimers'].forEach((v) {
visitTimers.add(VisitTimers.fromJson(v)); visitTimers!.add(VisitTimers.fromJson(v));
}); });
} }
startDate = json['startDate']; startDate = json['startDate'];
@ -208,9 +208,9 @@ class Ppm {
try { try {
externalEngineerTimer = TimerModel(startAt: DateTime.tryParse(suppStartDate ?? ""), endAt: DateTime.tryParse(suppEndDate ?? "")); externalEngineerTimer = TimerModel(startAt: DateTime.tryParse(suppStartDate ?? ""), endAt: DateTime.tryParse(suppEndDate ?? ""));
if (externalEngineerTimer.endAt != null && externalEngineerTimer.startAt != null) { if (externalEngineerTimer?.endAt != null && externalEngineerTimer?.startAt != null) {
externalEngineerTimer.durationInSecond = (externalEngineerTimer.endAt.difference(externalEngineerTimer.startAt))?.inSeconds; externalEngineerTimer?.durationInSecond = (externalEngineerTimer!.endAt!.difference(externalEngineerTimer!.startAt!)).inSeconds;
suppWorkingHours = (((externalEngineerTimer.durationInSecond ?? 0) / 60) / 60).toStringAsFixed(2); suppWorkingHours = (((externalEngineerTimer!.durationInSecond ?? 0) / 60) / 60).toStringAsFixed(2);
} }
} catch (e) { } catch (e) {
print(e.toString()); print(e.toString());
@ -265,189 +265,189 @@ class Ppm {
warrantyEndDate = json['warrantyEndDate']; warrantyEndDate = json['warrantyEndDate'];
} }
num id; num? id;
num ppmScheduleId; num? ppmScheduleId;
num assetId; num? assetId;
String jobSheetNo; String? jobSheetNo;
String assignedEmployeeId; String? assignedEmployeeId;
String expectedDate; String? expectedDate;
String actualDate; String? actualDate;
String nextDate; String? nextDate;
String forwardToId; String? forwardToId;
num maintenanceContractId; num? maintenanceContractId;
num typeOfServiceId; num? typeOfServiceId;
num executionTimeFrameId; num? executionTimeFrameId;
String externalEngineer; String? externalEngineer;
String telephone; String? telephone;
num groupLeaderReviewId; num? groupLeaderReviewId;
num timePeriodId; num? timePeriodId;
num assignedToId; num? assignedToId;
List<PpmCalibrationTools> vCalibrationTools; List<PpmCalibrationTools>? vCalibrationTools;
List<PpmKits> vKits; List<PpmKits>? vKits;
List<PpmContacts> vContacts; List<PpmContacts>? vContacts;
List<PpmChecklists> vChecklists; List<PpmChecklists>? vChecklists;
List<PpmAttachments> files; List<PpmAttachments>? files;
num visitStatusId; num? visitStatusId;
List<VisitTimers> visitTimers; List<VisitTimers>? visitTimers;
String startDate; String? startDate;
String endDate; String? endDate;
String workingHours; String? workingHours;
String travelingHours; String? travelingHours;
num deviceStatusId; num? deviceStatusId;
String comments; String? comments;
String workPerformed; String? workPerformed;
num supplierId; num? supplierId;
num suppPersonId; num? suppPersonId;
String suppStartDate; String? suppStartDate;
String suppEndDate; String? suppEndDate;
String suppWorkingHours; String? suppWorkingHours;
num taskStatusId; num? taskStatusId;
String engSignature; String? engSignature;
String nurseSignature; String? nurseSignature;
num safetyId; num? safetyId;
num assetAvailabilityId; num? assetAvailabilityId;
String assetAvailabilityName; String? assetAvailabilityName;
String assetName; String? assetName;
String assetNumber; String? assetNumber;
String assetSerialNo; String? assetSerialNo;
num assetSupplierId; num? assetSupplierId;
String assetSupplierName; String? assetSupplierName;
String assignedEmployeeName; String? assignedEmployeeName;
String assignedToName; String? assignedToName;
String contractNumber; String? contractNumber;
String createdOn; String? createdOn;
num departmentId; num? departmentId;
String departmentName; String? departmentName;
String deviceStatusName; String? deviceStatusName;
String dueDate; String? dueDate;
String executionTimeFrameName; String? executionTimeFrameName;
String forwardToName; String? forwardToName;
String groupLeaderReviewName; String? groupLeaderReviewName;
num manufacturerId; num? manufacturerId;
String manufacturerName; String? manufacturerName;
num modelId; num? modelId;
String modelName; String? modelName;
String modifiedOn; String? modifiedOn;
bool notified; bool? notified;
String planCode; String? planCode;
num planNo; num? planNo;
num ppmId; num? ppmId;
String ppmScheduleCode; String? ppmScheduleCode;
num ppmScheduleNo; num? ppmScheduleNo;
num ppmSupplierId; num? ppmSupplierId;
String ppmSupplierName; String? ppmSupplierName;
String safetyName; String? safetyName;
num siteId; num? siteId;
String siteName; String? siteName;
String buildingName; String? buildingName;
String floorName; String? floorName;
String roomName; String? roomName;
String supplierName; String? supplierName;
String suppPerson; String? suppPerson;
String taskStatusName; String? taskStatusName;
String timePeriodName; String? timePeriodName;
num timePeriodValue; num? timePeriodValue;
String typeOfServiceName; String? typeOfServiceName;
String visitCode; String? visitCode;
num visitNo; num? visitNo;
String visitStatusName; String? visitStatusName;
String warrantyEndDate; String? warrantyEndDate;
TimerModel tbsTimer = TimerModel(); TimerModel? tbsTimer = TimerModel();
TimerModel externalEngineerTimer = TimerModel(); TimerModel? externalEngineerTimer = TimerModel();
Uint8List localNurseSignature; Uint8List? localNurseSignature;
Uint8List localEngineerSignature; Uint8List? localEngineerSignature;
Ppm copyWith({ Ppm copyWith({
num id, num? id,
num ppmScheduleId, num? ppmScheduleId,
num assetId, num? assetId,
String jobSheetNo, String? jobSheetNo,
String assignedEmployeeId, String? assignedEmployeeId,
String expectedDate, String? expectedDate,
String actualDate, String? actualDate,
String nextDate, String? nextDate,
String forwardToId, String? forwardToId,
num maintenanceContractId, num? maintenanceContractId,
num typeOfServiceId, num? typeOfServiceId,
num executionTimeFrameId, num? executionTimeFrameId,
String externalEngineer, String? externalEngineer,
String telephone, String? telephone,
num groupLeaderReviewId, num? groupLeaderReviewId,
num timePeriodId, num? timePeriodId,
num assignedToId, num? assignedToId,
List<PpmCalibrationTools> vCalibrationTools, List<PpmCalibrationTools>? vCalibrationTools,
List<PpmKits> vKits, List<PpmKits>? vKits,
List<PpmContacts> vContacts, List<PpmContacts>? vContacts,
List<PpmChecklists> vChecklists, List<PpmChecklists>? vChecklists,
List<PpmAttachments> files, List<PpmAttachments>? files,
num visitStatusId, num? visitStatusId,
List<VisitTimers> visitTimers, List<VisitTimers>? visitTimers,
String startDate, String? startDate,
String endDate, String? endDate,
String workingHours, String? workingHours,
String travelingHours, String? travelingHours,
num deviceStatusId, num? deviceStatusId,
String comments, String? comments,
String workPerformed, String? workPerformed,
num supplierId, num? supplierId,
num suppPersonId, num? suppPersonId,
String suppStartDate, String? suppStartDate,
String suppEndDate, String? suppEndDate,
String suppWorkingHours, String? suppWorkingHours,
num taskStatusId, num? taskStatusId,
String engSignature, String? engSignature,
String nurseSignature, String? nurseSignature,
num safetyId, num? safetyId,
num assetAvailabilityId, num? assetAvailabilityId,
String assetAvailabilityName, String? assetAvailabilityName,
String assetName, String? assetName,
String assetNumber, String? assetNumber,
String assetSerialNo, String? assetSerialNo,
num assetSupplierId, num? assetSupplierId,
String assetSupplierName, String? assetSupplierName,
String assignedEmployeeName, String? assignedEmployeeName,
String assignedToName, String? assignedToName,
String contractNumber, String? contractNumber,
String createdOn, String? createdOn,
num departmentId, num? departmentId,
String departmentName, String? departmentName,
String deviceStatusName, String? deviceStatusName,
String dueDate, String? dueDate,
String executionTimeFrameName, String? executionTimeFrameName,
String forwardToName, String? forwardToName,
String groupLeaderReviewName, String? groupLeaderReviewName,
num manufacturerId, num? manufacturerId,
String manufacturerName, String? manufacturerName,
num modelId, num? modelId,
String modelName, String? modelName,
String modifiedOn, String? modifiedOn,
bool notified, bool? notified,
String planCode, String? planCode,
num planNo, num? planNo,
num ppmId, num? ppmId,
String ppmScheduleCode, String? ppmScheduleCode,
num ppmScheduleNo, num? ppmScheduleNo,
num ppmSupplierId, num? ppmSupplierId,
String ppmSupplierName, String? ppmSupplierName,
String safetyName, String? safetyName,
num siteId, num? siteId,
String siteName, String? siteName,
String buildingName, String? buildingName,
String floorName, String? floorName,
String roomName, String? roomName,
String supplierName, String? supplierName,
String suppPerson, String? suppPerson,
String taskStatusName, String? taskStatusName,
String timePeriodName, String? timePeriodName,
num timePeriodValue, num? timePeriodValue,
String typeOfServiceName, String? typeOfServiceName,
String visitCode, String? visitCode,
num visitNo, num? visitNo,
String visitStatusName, String? visitStatusName,
String warrantyEndDate, String? warrantyEndDate,
TimerModel tbsTimer, TimerModel? tbsTimer,
TimerModel externalEngineerTimer, TimerModel? externalEngineerTimer,
}) { }) {
Ppm ppm = Ppm( Ppm ppm = Ppm(
id: id ?? this.id, id: id ?? this.id,
@ -560,26 +560,26 @@ class Ppm {
map['timePeriodId'] = timePeriodId; map['timePeriodId'] = timePeriodId;
map['assignedToId'] = assignedToId; map['assignedToId'] = assignedToId;
if (vCalibrationTools != null) { 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) { 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) { if (vContacts != null) {
map['vContacts'] = vContacts.map((v) => v.toJson()).toList(); map['vContacts'] = vContacts!.map((v) => v.toJson()).toList();
} }
if (vChecklists != null) { if (vChecklists != null) {
map['vChecklists'] = vChecklists.map((v) => v.toJson()).toList(); map['vChecklists'] = vChecklists!.map((v) => v.toJson()).toList();
} }
if (files?.isNotEmpty ?? false) { if (files?.isNotEmpty ?? false) {
map["vAttachments"] = files map["vAttachments"] = files!
.map((file) => .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(); .toList();
} }
map['visitStatusId'] = visitStatusId; map['visitStatusId'] = visitStatusId;
if (this.visitTimers != null) { 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['startDate'] = tbsTimer?.startAt?.toIso8601String();
// map['endDate'] = tbsTimer?.endAt?.toIso8601String(); // map['endDate'] = tbsTimer?.endAt?.toIso8601String();
@ -678,7 +678,7 @@ class Ppm {
} }
void removeEmptyObjects() { void removeEmptyObjects() {
if (vCalibrationTools?.isNotEmpty ?? false) vCalibrationTools.removeWhere((element) => element.assetId == null && element.calibrationDateOfTesters == 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); if (vKits?.isNotEmpty ?? false) vKits!.removeWhere((element) => element.partName == null && element.partNumber == null);
} }
} }

@ -9,26 +9,24 @@ class PpmAttachments {
PpmAttachments.fromJson(dynamic json) { PpmAttachments.fromJson(dynamic json) {
id = json['id']; id = json['id'];
visitId = json['visitId']; visitId = json['visitId'];
attachmentName = json['attachmentName']; attachmentName = json['attachmentName'] ?? json['attachmentURL']; // Handle potential null and prioritize'attachmentName'
attachmentName = json['attachmentURL'];
} }
num id; num? id; // Now nullable
num visitId; num? visitId; // Now nullable
String attachmentName; String? attachmentName; // Now nullable
String attachmentURL; String? attachmentURL; // Now nullable
PpmAttachments copyWith({ PpmAttachments copyWith({
num id, num? id,
num visitId, num? visitId,
String attachmentName, String? attachmentName,
String attachmentURL, String? attachmentURL,
}) => }) =>
PpmAttachments( PpmAttachments(
id: id ?? this.id, id: id ?? this.id,
visitId: visitId ?? this.visitId, visitId: visitId ?? this.visitId,
attachmentName: attachmentName ?? this.attachmentName, attachmentName: attachmentName ?? this.attachmentName,attachmentURL: attachmentURL ?? this.attachmentURL,
attachmentURL: attachmentURL ?? this.attachmentURL,
); );
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {

@ -19,22 +19,22 @@ class PpmCalibrationTools {
assetNumber = json['assetNumber']; assetNumber = json['assetNumber'];
} }
num id; num? id; // Now nullable
num visitId; num? visitId; // Now nullable
num assetId; num? assetId; // Now nullable
String calibrationDateOfTesters; String? calibrationDateOfTesters; // Now nullable
String assetSerialNo; String? assetSerialNo; // Now nullable
String assetName; String? assetName; //Now nullable
String assetNumber; String? assetNumber; // Now nullable
PpmCalibrationTools copyWith({ PpmCalibrationTools copyWith({
num id, num? id,
num visitId, num? visitId,
num assetId, num? assetId,
String calibrationDateOfTesters, String? calibrationDateOfTesters,
String assetSerialNo, String? assetSerialNo,
String assetName, String? assetName,
String assetNumber, String? assetNumber,
}) => }) =>
PpmCalibrationTools( PpmCalibrationTools(
id: id ?? this.id, id: id ?? this.id,

@ -19,22 +19,22 @@ class PpmChecklists {
measuredValue = json['measuredValue']; measuredValue = json['measuredValue'];
} }
num id; num? id;
num visitId; num? visitId;
String task; String? task;
num taskStatusId; num? taskStatusId;
String taskComment; String? taskComment;
String measuredValue; String? measuredValue;
String taskStatusName; String? taskStatusName;
PpmChecklists copyWith({ PpmChecklists copyWith({
num id, num? id,
num visitId, num? visitId,
String task, String? task,
num taskStatusId, num? taskStatusId,
String taskComment, String? taskComment,
String measuredValue, String? measuredValue,
String taskStatusName, String? taskStatusName,
}) => }) =>
PpmChecklists( PpmChecklists(
id: id ?? this.id, id: id ?? this.id,

@ -21,24 +21,24 @@ class PpmContacts {
landLine = json['landLine']; landLine = json['landLine'];
} }
num id; num? id;
num visitId; num? visitId;
String title; String? title;
String person; String? person;
String job; String? job;
String email; String? email;
String telephone; String? telephone;
String landLine; String? landLine;
PpmContacts copyWith({ PpmContacts copyWith({
num id, num? id, // All parameters are now nullable
num visitId, num? visitId,
String title, String? title,
String person, String? person,
String job, String? job,
String email, String? email,
String telephone, String? telephone,
String landLine, String? landLine,
}) => }) =>
PpmContacts( PpmContacts(
id: id ?? this.id, id: id ?? this.id,

@ -19,22 +19,22 @@ class PpmKits {
partName2 = json['partName2']; partName2 = json['partName2'];
} }
num id; num? id; // Now nullable
num visitId; num? visitId; // Now nullable
num partCatalogItemId; num? partCatalogItemId; // Now nullable
String partNumber; String? partNumber; // Now nullable
String oracleCode; String? oracleCode; // Now nullable
String partName; String? partName; // Now nullable
String partName2; String? partName2; // Nownullable
PpmKits copyWith({ PpmKits copyWith({
num id, num? id, // All parameters are now nullable
num visitId, num? visitId,
num partCatalogItemId, num? partCatalogItemId,
String partNumber, String? partNumber,
String oracleCode, String? oracleCode,
String partName, String? partName,
String partName2, String? partName2,
}) => }) =>
PpmKits( PpmKits(
id: id ?? this.id, id: id ?? this.id,

@ -54,8 +54,7 @@ class PpmSearch {
actualDateFrom = json['actualDateFrom']; actualDateFrom = json['actualDateFrom'];
actualDateTo = json['actualDateTo']; actualDateTo = json['actualDateTo'];
siteId = json['siteId']; siteId = json['siteId'];
jobSheetNo = json['jobSheetNo']; jobSheetNo = json['jobSheetNo'];typeOfServiceId = json['typeOfServiceId'];
typeOfServiceId = json['typeOfServiceId'];
planNumber = json['planNumber']; planNumber = json['planNumber'];
notified = json['notified']; notified = json['notified'];
mostRecent = json['mostRecent']; mostRecent = json['mostRecent'];
@ -67,68 +66,68 @@ class PpmSearch {
assetName = json['assetName']; assetName = json['assetName'];
} }
num pageSize; num? pageSize; // Now nullable
num pageNumber; num? pageNumber; // Now nullable
num id; num? id; // Now nullable
num assetId; num? assetId; // Now nullable
num modelId; num? modelId; // Now nullable
num ppmId; num? ppmId; // Now nullable
num ppmScheduleId; num? ppmScheduleId; // Now nullable
num classification; num? classification; // Now nullable
num visitStatusId; num? visitStatusId; // Now nullable
num deviceStatusId; num? deviceStatusId; // Now nullable
num groupLeaderReviewId; num? groupLeaderReviewId; // Now nullable
String assignedEmployeeId; String? assignedEmployeeId; // Now nullable
bool hasAssignedEmployee; bool? hasAssignedEmployee; // Now nullable
num assignedToId; num? assignedToId; // Now nullable
String expectedDateFrom; String? expectedDateFrom; // Now nullable
String expectedDateTo; String? expectedDateTo; // Now nullable
String actualDateFrom; String? actualDateFrom; // Now nullable
String actualDateTo; String? actualDateTo; // Now nullable
num siteId; num? siteId; // Now nullable
String jobSheetNo; String? jobSheetNo; // Now nullable
num typeOfServiceId; num? typeOfServiceId; // Now nullable
num planNumber; num? planNumber; // Now nullable
bool notified; bool? notified; // Now nullable
bool mostRecent; bool? mostRecent; // Now nullable
AssetGroup assetGroup; AssetGroup? assetGroup; // Now nullable
num buildingId; num? buildingId; // Now nullable
num floorId; num? floorId; // Now nullable
num roomId; num? roomId; // Now nullable
num departmentId; num? departmentId; // Now nullable
String assetName; String? assetName; // Now nullable
PpmSearch copyWith({ PpmSearch copyWith({
num pageSize, num? pageSize, // All parameters are now nullable
num pageNumber, num? pageNumber,
num id, num? id,
num assetId, num? assetId,
num modelId, num? modelId,
num ppmId, num? ppmId,
num ppmScheduleId, num? ppmScheduleId,
num classification, num? classification,
num visitStatusId, num? visitStatusId,
num deviceStatusId, num? deviceStatusId,
num groupLeaderReviewId, num? groupLeaderReviewId,
String assignedEmployeeId, String? assignedEmployeeId,
bool hasAssignedEmployee, bool? hasAssignedEmployee,
num assignedToId, num? assignedToId,
String expectedDateFrom, String? expectedDateFrom,
String expectedDateTo, String? expectedDateTo,
String actualDateFrom, String? actualDateFrom,
String actualDateTo, String? actualDateTo,
num siteId, num? siteId,
String jobSheetNo, String? jobSheetNo,
num typeOfServiceId, num? typeOfServiceId,
num planNumber, num? planNumber,
bool notified, bool? notified,
bool mostRecent, bool? mostRecent,
AssetGroup assetGroup, AssetGroup? assetGroup,
num buildingId, num? buildingId,
num floorId, num? floorId,
num roomId, num? roomId,
num departmentId, num? departmentId,
String assetName, String? assetName,
}) => }) =>
PpmSearch( PpmSearch(
pageSize: pageSize ?? this.pageSize, pageSize: pageSize ?? this.pageSize,
@ -190,7 +189,7 @@ class PpmSearch {
map['notified'] = notified; map['notified'] = notified;
map['mostRecent'] = mostRecent; map['mostRecent'] = mostRecent;
if (assetGroup != null) { if (assetGroup != null) {
map['assetGroup'] = assetGroup.toJson(); map['assetGroup'] = assetGroup?.toJson(); // Use '?.' to handle potential null
} }
map['buildingId'] = buildingId; map['buildingId'] = buildingId;
map['floorId'] = floorId; map['floorId'] = floorId;

@ -2,17 +2,17 @@ import 'package:flutter/cupertino.dart';
import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/context_extension.dart';
class SearchAllRequestsModel { class SearchAllRequestsModel {
SearchByRequestNumberModel requestNumber; SearchByRequestNumberModel? requestNumber; // Now nullable
SearchByAssetNameModel assetName; SearchByAssetNameModel? assetName; // Now nullable
SearchByAssetNoModel assetNo; SearchByAssetNoModel? assetNo; // Now nullable
SearchByManufactureModel manufacture; SearchByManufactureModel? manufacture; // Now nullable
SearchBySNModel sn; SearchBySNModel? sn; // Now nullable
SearchByRequestModel model; SearchByRequestModel? model; // Now nullable
SearchAllRequestsBaseModel searchBySelectedValue; SearchAllRequestsBaseModel? searchBySelectedValue; // Now nullable
List<int> statuses; List<int>? statuses; // Now nullable
List<int> typeTransaction; List<int>? typeTransaction; // Now nullable
DateTime startDate, endDate; DateTime? startDate, endDate; // Now nullable
bool isArchived; bool isArchived = false;
SearchAllRequestsModel({ SearchAllRequestsModel({
this.requestNumber, this.requestNumber,
@ -30,7 +30,6 @@ class SearchAllRequestsModel {
void resetSearchValues() { void resetSearchValues() {
requestNumber?.controller?.text = ""; requestNumber?.controller?.text = "";
requestNumber?.value = "";
assetName?.controller?.text = ""; assetName?.controller?.text = "";
assetNo?.controller?.text = ""; assetNo?.controller?.text = "";
manufacture?.controller?.text = ""; manufacture?.controller?.text = "";
@ -41,35 +40,41 @@ class SearchAllRequestsModel {
} }
abstract class SearchAllRequestsBaseModel { abstract class SearchAllRequestsBaseModel {
String label; String? label; // Now nullable
String value; String? value; // Now nullable
BuildContext context; BuildContext? context; // Now nullable
TextInputType inputType; TextInputType inputType;
TextEditingController controller; TextEditingController? controller; // Now nullable
SearchAllRequestsBaseModel(this.context, {this.controller, this.label, this.value, this.inputType = TextInputType.text}); SearchAllRequestsBaseModel(this.context, {this.controller, this.label, this.value, this.inputType = TextInputType.text});
} }
class SearchByRequestNumberModel extends SearchAllRequestsBaseModel { 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 { 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 { 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 { 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 { 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 { 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);
} }

@ -1,10 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
abstract class SizeConfig { abstract class SizeConfig {
static MediaQueryData _mediaQueryData; static late MediaQueryData _mediaQueryData;
static double screenWidth; static double? screenWidth;
static double screenHeight; static double? screenHeight;
static double defaultSize; static double? defaultSize;
/// Call this method to save the height and width of the available layout /// Call this method to save the height and width of the available layout
static void init(BuildContext context) { static void init(BuildContext context) {

@ -1,23 +1,39 @@
class SystemNotificationModel { class SystemNotificationModel {
String userId; String? userId;
String userName; String? userName;
String title; String? title;
String text; String? text;
int referenceId; int? referenceId;
int sourceId; int? sourceId;
String sourceName; String? sourceName;
bool readed; bool? readed;
String readingDate; String? readingDate;
int id; int? id;
String createdOn; String? createdOn;
String modifiedOn; String? modifiedOn;
String priorityName; String? priorityName;
String statusName; String? statusName;
SystemNotificationModel( 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<String, dynamic> json) { SystemNotificationModel.fromJson(Map<String, dynamic>? json) {
// Allow json to be null
if (json != null) {
// Add null check
userId = json['userId']; userId = json['userId'];
userName = json['userName']; userName = json['userName'];
title = json['title']; title = json['title'];
@ -33,43 +49,44 @@ class SystemNotificationModel {
priorityName = json['priorityName']; priorityName = json['priorityName'];
statusName = json['statusName']; statusName = json['statusName'];
} }
}
Map<String, dynamic> toNotificationJson() { Map<String, dynamic> toNotificationJson() {
final Map<String, dynamic> data = new Map<String, dynamic>(); final Map<String, dynamic> data = <String, dynamic>{}; // Use <String, dynamic> for type safety
data['userId'] = this.userId; data['userId'] = userId;
data['userName'] = this.userName; data['userName'] = userName;
data['title'] = this.title; data['title'] = title;
data['text'] = this.text; data['text'] = text;
data['requestNumber'] = this.referenceId; data['requestNumber'] = referenceId;
data['sourceId'] = this.sourceId; data['sourceId'] = sourceId;
data['requestType'] = this.sourceName; data['requestType'] = sourceName;
data['readed'] = this.readed; data['readed'] = readed;
data['readingDate'] = this.readingDate; data['readingDate'] = readingDate;
data['id'] = this.id; data['id'] = id;
data['createdOn'] = this.createdOn; data['createdOn'] = createdOn;
data['modifiedOn'] = this.modifiedOn; data['modifiedOn'] = modifiedOn;
data['priorityName'] = this.priorityName; data['priorityName'] = priorityName;
data['priority'] = this.priorityName; data['priority'] = priorityName;
data['statusName'] = this.statusName; data['statusName'] = statusName;
return data; return data;
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>(); final Map<String, dynamic> data = <String, dynamic>{}; // Use <String, dynamic> for type safety
data['userId'] = this.userId; data['userId'] = userId;
data['userName'] = this.userName; data['userName'] = userName;
data['title'] = this.title; data['title'] = title;
data['text'] = this.text; data['text'] = text;
data['referenceId'] = this.referenceId; data['referenceId'] = referenceId;
data['sourceId'] = this.sourceId; data['sourceId'] = sourceId;
data['sourceName'] = this.sourceName; data['sourceName'] = sourceName;
data['readed'] = this.readed; data['readed'] = readed;
data['readingDate'] = this.readingDate; data['readingDate'] = readingDate;
data['id'] = this.id; data['id'] = id;
data['createdOn'] = this.createdOn; data['createdOn'] = createdOn;
data['modifiedOn'] = this.modifiedOn; data['modifiedOn'] = modifiedOn;
data['priorityName'] = this.priorityName; data['priorityName'] = priorityName;
data['statusName'] = this.statusName; data['statusName'] = statusName;
return data; return data;
} }
} }

@ -1,7 +1,7 @@
class TimerModel { class TimerModel {
DateTime startAt; DateTime? startAt;
DateTime endAt; DateTime? endAt;
int durationInSecond; int? durationInSecond;
// bool stopped; // bool stopped;

@ -2,38 +2,38 @@ import 'package:test_sa/controllers/notification/firebase_notification_manger.da
import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/enums/user_types.dart';
class User { class User {
int clientId; int? clientId;
String clientName; String? clientName;
List<int> departmentId; List<int>? departmentId;
List<String> departmentName; List<String>? departmentName;
String message; String? message;
String username; String? username;
String userID; String? userID;
String email; String? email;
String password; String? password;
String token; String? token;
dynamic roles; dynamic roles;
List<UserRoles> userRoles; List<UserRoles>? userRoles;
String tokenlife; String? tokenlife;
bool isAuthenticated; bool? isAuthenticated;
bool hasError; bool? hasError;
String profilePhotoName; String? profilePhotoName;
String id; String? id;
String userName; String? userName;
String normalizedUserName; String? normalizedUserName;
String normalizedEmail; String? normalizedEmail;
bool emailConfirmed; bool? emailConfirmed;
dynamic passwordHash; dynamic passwordHash;
String securityStamp; String? securityStamp;
String concurrencyStamp; String? concurrencyStamp;
String phoneNumber; String? phoneNumber;
String extensionNo; String? extensionNo;
bool phoneNumberConfirmed; bool? phoneNumberConfirmed;
bool twoFactorEnabled; bool? twoFactorEnabled;
dynamic lockoutEnd; dynamic lockoutEnd;
bool lockoutEnabled; bool? lockoutEnabled;
int accessFailedCount; int? accessFailedCount;
List<AssetGroup> assetGroups; List<AssetGroup>? assetGroups;
User({ User({
this.clientId, this.clientId,
@ -68,7 +68,7 @@ class User {
this.accessFailedCount, 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<Map<String, dynamic>> toLoginJson() async { Future<Map<String, dynamic>> toLoginJson() async {
if (FirebaseNotificationManger.token == null) await FirebaseNotificationManger.getToken(); if (FirebaseNotificationManger.token == null) await FirebaseNotificationManger.getToken();
@ -79,7 +79,7 @@ class User {
}; };
} }
UsersTypes get type { UsersTypes? get type {
switch (userRoles?.first?.value) { switch (userRoles?.first?.value) {
case "R-6": case "R-6":
return UsersTypes.engineer; return UsersTypes.engineer;
@ -128,10 +128,10 @@ class User {
map['token'] = token; map['token'] = token;
map['roles'] = roles; map['roles'] = roles;
if (userRoles != null) { if (userRoles != null) {
map['userRoles'] = userRoles.map((v) => v.toJson()).toList(); map['userRoles'] = userRoles!.map((v) => v.toJson()).toList();
} }
if (assetGroups != null) { if (assetGroups != null) {
map['assetGroups'] = assetGroups.map((v) => v.toJson()).toList(); map['assetGroups'] = assetGroups!.map((v) => v.toJson()).toList();
} }
map['tokenlife'] = tokenlife; map['tokenlife'] = tokenlife;
map['isAuthenticated'] = isAuthenticated; map['isAuthenticated'] = isAuthenticated;
@ -161,13 +161,13 @@ class User {
if (json['department_id'] != null) { if (json['department_id'] != null) {
departmentId = []; departmentId = [];
json['department_id'].forEach((v) { json['department_id'].forEach((v) {
departmentId.add(v); departmentId!.add(v);
}); });
} }
if (json['department_name'] != null) { if (json['department_name'] != null) {
departmentName = []; departmentName = [];
json['department_name'].forEach((v) { json['department_name'].forEach((v) {
departmentName.add(v); departmentName!.add(v);
}); });
} }
message = json['message']; message = json['message'];
@ -180,14 +180,14 @@ class User {
if (json['userRoles'] != null) { if (json['userRoles'] != null) {
userRoles = []; userRoles = [];
json['userRoles'].forEach((v) { json['userRoles'].forEach((v) {
userRoles.add(UserRoles.fromJson(v)); userRoles!.add(UserRoles.fromJson(v));
}); });
} }
if (json['assetGroups'] != null) { if (json['assetGroups'] != null) {
assetGroups = <AssetGroup>[]; assetGroups = <AssetGroup>[];
json['assetGroups'].forEach((v) { json['assetGroups'].forEach((v) {
assetGroups.add(AssetGroup.fromJson(v)); assetGroups!.add(AssetGroup.fromJson(v));
}); });
} }
tokenlife = json['tokenlife']; tokenlife = json['tokenlife'];
@ -213,6 +213,10 @@ class User {
} }
class UserRoles { class UserRoles {
String? id;
String? name;
String? value;
UserRoles({ UserRoles({
this.id, this.id,
this.name, this.name,
@ -225,14 +229,10 @@ class UserRoles {
value = json['value']; value = json['value'];
} }
String id;
String name;
String value;
UserRoles copyWith({ UserRoles copyWith({
String id, String? id,
String name, String? name,
String value, String? value,
}) => }) =>
UserRoles( UserRoles(
id: id ?? this.id, id: id ?? this.id,
@ -250,23 +250,27 @@ class UserRoles {
} }
class AssetGroup { class AssetGroup {
int id; int? id;
String name; String? name;
String code; String? code;
AssetGroup({this.id, this.name, this.code}); AssetGroup({this.id, this.name, this.code});
AssetGroup.fromJson(Map<String, dynamic> json) { AssetGroup.fromJson(Map<String, dynamic>? json) {
// Allow json to be null
if (json != null) {
// Add null check
id = json['id']; id = json['id'];
name = json['name']; name = json['name'];
code = json['code']; code = json['code'];
} }
}
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>(); final Map<String, dynamic> data = <String, dynamic>{}; // Use <String, dynamic> for type safety
data['id'] = this.id; data['id'] = id;
data['name'] = this.name; data['name'] = name;
data['code'] = this.code; data['code'] = code;
return data; return data;
} }
} }

@ -13,13 +13,13 @@ import '../app_style/app_color.dart';
class SingleItemDropDownMenu<T extends Base, X extends LoadingListNotifier> class SingleItemDropDownMenu<T extends Base, X extends LoadingListNotifier>
extends StatefulWidget { extends StatefulWidget {
final BuildContext context; final BuildContext context;
final Function(T) onSelect; final Function(T)? onSelect;
final T initialValue; final T? initialValue;
final bool enabled; final bool enabled;
final bool showAsBottomSheet; final bool showAsBottomSheet;
final List<T> staticData; final List<T> staticData;
final String title; final String title;
final double height; final double? height;
final bool showShadow ; final bool showShadow ;
final Color backgroundColor; final Color backgroundColor;
final bool loading; final bool loading;
@ -27,7 +27,7 @@ class SingleItemDropDownMenu<T extends Base, X extends LoadingListNotifier>
/// To use a static data (without calling API) /// To use a static data (without calling API)
/// just send [NullableLoadingProvider] as generic data type and fill the [staticData] /// just send [NullableLoadingProvider] as generic data type and fill the [staticData]
const SingleItemDropDownMenu({ const SingleItemDropDownMenu({
Key key, Key? key,
@required this.context, @required this.context,
@required this.title, @required this.title,
this.onSelect, this.onSelect,
@ -48,8 +48,8 @@ class SingleItemDropDownMenu<T extends Base, X extends LoadingListNotifier>
class _SingleItemDropDownMenuState<T extends Base, class _SingleItemDropDownMenuState<T extends Base,
X extends LoadingListNotifier> extends State<SingleItemDropDownMenu<T, X>> { X extends LoadingListNotifier> extends State<SingleItemDropDownMenu<T, X>> {
T _selectedItem; T? _selectedItem;
X provider; X? provider;
@override @override
void initState() { void initState() {
@ -164,10 +164,11 @@ class _SingleItemDropDownMenuState<T extends Base,
), ),
style: TextStyle(color: Theme.of(context).primaryColor), style: TextStyle(color: Theme.of(context).primaryColor),
underline: const SizedBox.shrink(), underline: const SizedBox.shrink(),
onChanged: (widget.enabled == false || widget.showAsBottomSheet) onChanged: (widget.enabled == false || widget.showAsBottomSheet)
? null ? null
: (T newValue) { : (T? newValue) {
final isNull = newValue.identifier == "-1"; final isNull = newValue?.identifier == "-1";
setState(() { setState(() {
_selectedItem = isNull ? null : newValue; _selectedItem = isNull ? null : newValue;
}); });
@ -187,7 +188,7 @@ class _SingleItemDropDownMenuState<T extends Base,
})?.toList(), })?.toList(),
).onPress(widget.showAsBottomSheet ? () async{ ).onPress(widget.showAsBottomSheet ? () async{
T _selectedT = (await showModalBottomSheet( T? _selectedT = (await showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
@ -204,7 +205,7 @@ class _SingleItemDropDownMenuState<T extends Base,
title: widget.title, title: widget.title,
builderString: (emp) => emp?.name ?? "", builderString: (emp) => emp?.name ?? "",
), ),
)) as T; )) as T?;
if(_selectedT !=null) { if(_selectedT !=null) {
widget.onSelect(_selectedT); widget.onSelect(_selectedT);
} }

@ -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/status_drop_down/employee/nurse_provider.dart';
import 'package:test_sa/controllers/providers/api/user_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/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/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/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/models/new_models/room_model.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.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/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/building.dart';
import '../../../models/new_models/site.dart'; import '../../../models/new_models/site.dart';
@ -38,17 +36,18 @@ class RequestDeviceTransfer extends StatefulWidget {
} }
class _RequestDeviceTransferState extends State<RequestDeviceTransfer> { class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
UserProvider _userProvider; UserProvider? _userProvider;
SettingProvider _settingProvider; SettingProvider? _settingProvider;
AssetTransferProvider _deviceTransferProvider; AssetTransferProvider? _deviceTransferProvider;
final TextEditingController _requestedQuantityController = TextEditingController(); final TextEditingController _requestedQuantityController = TextEditingController();
final AssetTransfer _transferModel = AssetTransfer(); final AssetTransfer _transferModel = AssetTransfer();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final TextEditingController _receiverNameController = TextEditingController(), _commentsController = TextEditingController(); final TextEditingController _receiverNameController = TextEditingController(), _commentsController = TextEditingController();
final Asset _assetDestination = Asset(); final Asset _assetDestination = Asset();
Asset _pickedAsset; Asset? _pickedAsset;
Employee receiverEndUser; Employee? receiverEndUser;
Employee? _selectedNurse;
@override @override
void setState(VoidCallback fn) { void setState(VoidCallback fn) {
@ -56,7 +55,7 @@ class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
} }
void _onSubmit() async { void _onSubmit() async {
_transferModel.assetId = _pickedAsset.id; _transferModel.assetId = _pickedAsset?.id;
_transferModel.destSiteId = _assetDestination.site?.id; _transferModel.destSiteId = _assetDestination.site?.id;
_transferModel.destBuildingId = _assetDestination.building?.id; _transferModel.destBuildingId = _assetDestination.building?.id;
_transferModel.destFloorId = _assetDestination.floor?.id; _transferModel.destFloorId = _assetDestination.floor?.id;
@ -73,14 +72,12 @@ class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
@override @override
void dispose() { void dispose() {
_requestedQuantityController.dispose(); _requestedQuantityController.dispose();
_deviceTransferProvider.reset(); _deviceTransferProvider!.reset();
_receiverNameController.dispose(); _receiverNameController.dispose();
_commentsController.dispose(); _commentsController.dispose();
super.dispose(); super.dispose();
} }
Employee _selectedNurse;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
_userProvider = Provider.of<UserProvider>(context, listen: false); _userProvider = Provider.of<UserProvider>(context, listen: false);
@ -121,7 +118,7 @@ class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
_assetDestination.floor = null; _assetDestination.floor = null;
_assetDestination.department = null; _assetDestination.department = null;
_selectedNurse = null; _selectedNurse = null;
Provider.of<NurseProvider>(context, listen: false).siteId = value.id; Provider.of<NurseProvider>(context, listen: false).siteId = value.id!.toInt();
Provider.of<NurseProvider>(context, listen: false).getData(); Provider.of<NurseProvider>(context, listen: false).getData();
setState(() {}); setState(() {});
}, },
@ -182,7 +179,7 @@ class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
NurseMenu( NurseMenu(
title: context.translation.receiverName, title: context.translation.receiverName,
initialValue: _selectedNurse, initialValue: _selectedNurse,
enable: _assetDestination?.site != null, enable: _assetDestination.site != null,
onSelect: (employee) { onSelect: (employee) {
if (employee != null) { if (employee != null) {
_selectedNurse = employee; _selectedNurse = employee;

@ -1,32 +1,28 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:test_sa/views/app_style/sizing.dart'; import 'package:test_sa/views/app_style/sizing.dart';class ATextFormField extends StatefulWidget {
final Function(String)? onSaved;
class ATextFormField extends StatefulWidget { final String? Function(String?)? validator;
final Function(String) onSaved; final Function(String)? onChange;
final Function(String) validator; final bool? obscureText;
final Function(String) onChange; final VoidCallback? showPassword;
final bool obscureText; final String? hintText;final String? labelText;
final VoidCallback showPassword;
final String hintText;
final String labelText;
final TextInputType textInputType; final TextInputType textInputType;
final String initialValue; final String? initialValue;
final TextStyle style; final TextStyle? style;
final bool enable; final bool enable;
final TextAlign textAlign; final TextAlign? textAlign;
final FocusNode node; final FocusNode? node;
final Widget suffixIcon; final Widget? suffixIcon;
final IconData prefixIconData; final IconData? prefixIconData;
final double prefixIconSize; final double? prefixIconSize;
final TextEditingController controller; final TextEditingController? controller;
final TextInputAction textInputAction; final TextInputAction? textInputAction;
final VoidCallback onAction; final VoidCallback? onAction;
const ATextFormField( const ATextFormField({
{Key key, Key? key,
this.onSaved, this.onSaved,
this.validator, this.validator,this.node,
this.node,
this.onChange, this.onChange,
this.obscureText, this.obscureText,
this.showPassword, this.showPassword,
@ -42,8 +38,8 @@ class ATextFormField extends StatefulWidget {
this.prefixIconSize, this.prefixIconSize,
this.controller, this.controller,
this.textInputAction, this.textInputAction,
this.onAction}) this.onAction,
: super(key: key); }) : super(key: key);
@override @override
State<ATextFormField> createState() => _ATextFormFieldState(); State<ATextFormField> createState() => _ATextFormFieldState();
@ -52,30 +48,31 @@ class ATextFormField extends StatefulWidget {
class _ATextFormFieldState extends State<ATextFormField> { class _ATextFormFieldState extends State<ATextFormField> {
@override @override
void initState() { 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(); super.initState();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
height: widget.textInputType == TextInputType.multiline ? null : 50, height: widget.textInputType == TextInputType.multiline ? null : 50,padding: const EdgeInsets.only(left: 12, right: 12),
padding: EdgeInsets.only(left: 12, right: 12),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Color(0xfff5f5f5), color: const Color(0xfff5f5f5),
border: Border.all( border: Border.all(
color: Color(0xffefefef), color: const Color(0xffefefef),
), ),
borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)), borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
), ),
child: TextFormField( child: TextFormField(
focusNode: widget.node, focusNode: widget.node,
enabled: widget.enable, enabled: widget.enable,
onSaved: widget.onSaved, //onSaved: widget.onSaved,
initialValue: widget.controller != null ? null : widget.initialValue, initialValue: widget.controller != null ? null : widget.initialValue,
validator: widget.validator, validator: widget.validator,
onChanged: widget.onChange, onChanged: widget.onChange,
textAlign: TextAlign.left, textAlign: widget.textAlign ?? TextAlign.left,
obscureText: widget.obscureText ?? false, obscureText: widget.obscureText ?? false,
keyboardType: widget.textInputType, keyboardType: widget.textInputType,
maxLines: widget.textInputType == TextInputType.multiline ? null : 1, maxLines: widget.textInputType == TextInputType.multiline ? null : 1,
@ -83,24 +80,26 @@ class _ATextFormFieldState extends State<ATextFormField> {
controller: widget.controller, controller: widget.controller,
textInputAction: widget.textInputType == TextInputType.multiline ? null : widget.textInputAction ?? TextInputAction.next, textInputAction: widget.textInputType == TextInputType.multiline ? null : widget.textInputAction ?? TextInputAction.next,
onEditingComplete: widget.onAction ?? () => FocusScope.of(context).nextFocus(), onEditingComplete: widget.onAction ?? () => FocusScope.of(context).nextFocus(),
// style: widget.style, style: widget.style ?? Theme.of(context).textTheme.bodyLarge,
style: Theme.of(context).textTheme.bodyText1,
decoration: InputDecoration( decoration: InputDecoration(
border: InputBorder.none, border: InputBorder.none,
suffixIconConstraints: BoxConstraints(minWidth: 0), suffixIconConstraints: const BoxConstraints(minWidth: 0),
disabledBorder: InputBorder.none, disabledBorder: InputBorder.none,
focusedBorder: InputBorder.none, focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none, enabledBorder: InputBorder.none,
constraints: BoxConstraints(), constraints: const BoxConstraints(),
errorStyle: TextStyle(height: 0.3), errorStyle: const TextStyle(height: 0.3),
//contentPadding: EdgeInsets.only(left: 0),
hintText: widget.hintText, hintText: widget.hintText,
labelText: widget.labelText, labelText: widget.labelText,
//suffixIcon: widget.suffixIcon, suffixIcon: widget.suffixIcon,
suffixIcon: widget.prefixIconData == null prefixIcon: widget.prefixIconData == null
? null ? null
: Icon(widget.prefixIconData, : Icon(
size: widget.prefixIconSize == null ? 20 * AppStyle.getScaleFactor(context) : (widget.prefixIconSize - 10) * AppStyle.getScaleFactor(context), color: Color(0xff2e303a))), widget.prefixIconData,
size: widget.prefixIconSize == null ? 20 * AppStyle.getScaleFactor(context) : (widget.prefixIconSize! - 10) * AppStyle.getScaleFactor(context),
color: const Color(0xff2e303a),
),
),
), ),
); );
} }

@ -8,9 +8,9 @@ import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/app_style/app_color.dart';
class AssetDetailBottomSheet extends StatelessWidget { 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -32,7 +32,7 @@ class AssetDetailBottomSheet extends StatelessWidget {
), ),
image: DecorationImage( image: DecorationImage(
fit: BoxFit.cover, 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( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
"${context.translation.assetNo}: ${asset.assetNumber}".bodyText(context), "${context.translation.assetNo}: ${asset!.assetNumber}".bodyText(context),
"${context.translation.modelName}: ${asset.modelDefinition.modelName}".bodyText(context), "${context.translation.modelName}: ${asset!.modelDefinition!.modelName}".bodyText(context),
"${context.translation.supplier}: ${asset.supplier?.suppliername?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), "${context.translation.supplier}: ${asset!.supplier?.suppliername?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context),
"${context.translation.manufacture}: ${asset.modelDefinition.manufacturerName?.cleanupWhitespace?.capitalizeFirstOfEach}".bodyText(context), "${context.translation.manufacture}: ${asset!.modelDefinition!.manufacturerName?.cleanupWhitespace.capitalizeFirstOfEach}".bodyText(context),
//"${context.translation.location}: ${assetModel.site.custName?.cleanupWhitespace?.capitalizeFirstOfEach}".bodyText(context), //"${context.translation.location}: ${assetModel.site.custName?.cleanupWhitespace?.capitalizeFirstOfEach}".bodyText(context),
], ],
).expanded, ).expanded,
@ -58,22 +58,22 @@ class AssetDetailBottomSheet extends StatelessWidget {
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
"${context.translation.snNo}: ${asset.assetSerialNo}".bodyText(context), "${context.translation.snNo}: ${asset!.assetSerialNo}".bodyText(context),
"${context.translation.site}: ${asset?.site?.custName?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), "${context.translation.site}: ${asset?.site?.custName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context),
"${context.translation.building}: ${asset?.building?.name?.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.floor}: ${asset?.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context),
"${context.translation.md}: ${asset?.department?.departmentName?.cleanupWhitespace?.capitalizeFirstOfEach ?? "-"}".bodyText(context), "${context.translation.md}: ${asset?.department?.departmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"}".bodyText(context),
"${context.translation.room}: ${asset?.room?.value ?? "-"}".bodyText(context), "${context.translation.room}: ${asset?.room?.value ?? "-"}".bodyText(context),
], ],
).expanded, ).expanded,
], ],
), ),
8.height, 8.height,
if ((asset.modelDefinition.assetDescription ?? "").isNotEmpty) ...[ if ((asset?.modelDefinition?.assetDescription ?? "").isNotEmpty) ...[
8.height, 8.height,
const Divider(color: AppColor.neutral30, height: 1, thickness: 1), const Divider(color: AppColor.neutral30, height: 1, thickness: 1),
8.height, 8.height,
asset.modelDefinition.assetDescription.bodyText(context), asset!.modelDefinition!.assetDescription!.bodyText(context),
] ]
], ],
) )

@ -12,7 +12,7 @@ class PendingRequestBottomSheet extends StatelessWidget {
final PendingAssetServiceRequest pendingAssetServiceRequest; final PendingAssetServiceRequest pendingAssetServiceRequest;
final Asset device; final Asset device;
PendingRequestBottomSheet(this.pendingAssetServiceRequest, this.device, {Key key}) : super(key: key); PendingRequestBottomSheet(this.pendingAssetServiceRequest, this.device, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {

@ -2,33 +2,29 @@ import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.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/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/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
typedef SelectionBuilderString = String Function(dynamic); typedef SelectionBuilderString = String Function(dynamic);
class SelectionBottomSheet<T> extends StatefulWidget { class SelectionBottomSheet<T> extends StatefulWidget {
List<T> items; final List<T> items;
T selectedItem; final T? selectedItem; // Now nullable
String title; final String title;
final SelectionBuilderString builderString; 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 @override
_SelectionBottomSheetState createState() { _SelectionBottomSheetState createState() => _SelectionBottomSheetState<T>();
return _SelectionBottomSheetState();
}
} }
class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet> { class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet<T>> {
T _selectedValue; T? _selectedValue; // Now nullable
String query = ""; String query = "";
List<T> get filteredList => widget.items.where((element) => element.name.toString().toLowerCase().contains(query.toLowerCase())).toList(); List<T> get filteredList => widget.items.where((element) => widget.builderString(element).toLowerCase().contains(query.toLowerCase())).toList();
@override @override
void initState() { void initState() {
@ -40,6 +36,7 @@ class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet> {
@override @override
void dispose() { void dispose() {
searchFocusNode.dispose();
super.dispose(); super.dispose();
} }
@ -58,28 +55,31 @@ class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet> {
query = queryString; query = queryString;
setState(() {}); setState(() {});
}, },
style: TextStyle(fontSize: 14), style: const TextStyle(fontSize: 14),
focusNode: searchFocusNode, focusNode: searchFocusNode,
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Search by name', hintText: 'Search by name',
labelText: 'Search', labelText: 'Search',
hintStyle: TextStyle(fontSize: 14), hintStyle: const TextStyle(fontSize: 14),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: AppColor.blueStatus(context), width: 2.0), 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( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: AppColor.blueStatus(context), width: 1.0), 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, 8.height,
ListView.builder( Expanded(
// Wrap ListView with Expanded
child: ListView.builder(
itemCount: filteredList.length, itemCount: filteredList.length,
padding: EdgeInsets.only(top: 8), padding: const EdgeInsets.only(top: 8),
itemBuilder: (cxt, index) => RadioListTile( itemBuilder: (cxt, index) => RadioListTile<T>(
// Specify type for RadioListTile
value: filteredList[index], value: filteredList[index],
dense: true, dense: true,
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
@ -93,7 +93,10 @@ class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet> {
title: Text( title: Text(
widget.builderString(filteredList[index]).cleanupWhitespace?.capitalizeFirstOfEach ?? "", widget.builderString(filteredList[index]).cleanupWhitespace?.capitalizeFirstOfEach ?? "",
style: Theme.of(context).textTheme.bodyLarge, style: Theme.of(context).textTheme.bodyLarge,
))).expanded, ),
),
),
),
8.height, 8.height,
if (_selectedValue != null) if (_selectedValue != null)
AppFilledButton( AppFilledButton(
@ -101,7 +104,8 @@ class _SelectionBottomSheetState<T> extends State<SelectionBottomSheet> {
maxWidth: true, maxWidth: true,
onPressed: () { onPressed: () {
Navigator.pop(context, _selectedValue); Navigator.pop(context, _selectedValue);
}), },
),
], ],
), ),
); );

@ -11,12 +11,12 @@ import '../../../new_views/common_widgets/asset_info_card.dart';
class PickAsset extends StatelessWidget { class PickAsset extends StatelessWidget {
final Function(Asset) onPickAsset; final Function(Asset) onPickAsset;
final Asset device; final Asset? device; // Now nullable
final bool editable; final bool editable;
final bool showAssetInfo; final bool showAssetInfo;
final bool forPPM; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -32,21 +32,24 @@ class PickAsset extends StatelessWidget {
padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight), padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight),
child: Row( child: Row(
children: [ children: [
Column( Expanded(
// Wrap the Column with Expanded
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
context.translation.device.tinyFont(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), context.translation.device.tinyFont(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50),
if (device != null) if (device != null)
device.assetNumber.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50) device!.assetNumber.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50)
else else
context.translation.pickAsset.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50), context.translation.pickAsset.bodyText(context).custom(color: context.isDark ? AppColor.neutral40 : AppColor.neutral50),
], ],
).onPress(() async { ).onPress(() async {
Asset device = await Navigator.of(context).pushNamed(MyAssetsPage.id) as Asset; final selectedDevice = await Navigator.of(context).pushNamed(MyAssetsPage.id) as Asset?;
if (device != null) { if (selectedDevice != null) {
onPickAsset(device); onPickAsset(selectedDevice);
} }
}).expanded, }),
),
if (device != null) if (device != null)
Icon(Icons.change_circle_rounded, size: 22, color: context.isDark ? AppColor.primary40 : AppColor.primary70) Icon(Icons.change_circle_rounded, size: 22, color: context.isDark ? AppColor.primary40 : AppColor.primary70)
else 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),
], ],
); );
} }

@ -7,7 +7,7 @@ import 'package:test_sa/extensions/widget_extensions.dart';
import '../../new_views/app_style/app_color.dart'; import '../../new_views/app_style/app_color.dart';
class HorizontalListWidget extends StatefulWidget { 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<String> list; final List<String> list;
final Function(int index) callBackFunction; final Function(int index) callBackFunction;

@ -9,20 +9,18 @@ class LoadingManager extends StatefulWidget {
final bool isLoading; final bool isLoading;
final bool isFailedLoading; final bool isFailedLoading;
final bool isNotPage; final bool isNotPage;
final int progress;
final bool askOnBack; final bool askOnBack;
final int stateCode; final int? stateCode;
final Future<void> Function() onRefresh; final Future<void> Function() onRefresh;
final Widget child; final Widget child;
LoadingManager({ LoadingManager({
Key key, Key? key,
@required this.isLoading, required this.isLoading,
@required this.isFailedLoading, required this.isFailedLoading,
@required this.stateCode, required this.stateCode,
@required this.onRefresh, required this.onRefresh,
@required this.child, required this.child,
this.progress,
this.isNotPage = false, this.isNotPage = false,
this.askOnBack = false, this.askOnBack = false,
}) : super(key: key); }) : super(key: key);
@ -44,7 +42,7 @@ class _LoadingManagerState extends State<LoadingManager> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget placeHolder; Widget? placeHolder;
// to load data if load not start // to load data if load not start
if (widget.isLoading != true && widget.stateCode == null) { if (widget.isLoading != true && widget.stateCode == null) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) {

@ -6,7 +6,7 @@ import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.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:rive/rive.dart';
import 'package:test_sa/extensions/context_extension.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';
@ -18,11 +18,11 @@ import '../../../new_views/app_style/app_color.dart';
import '../../../new_views/common_widgets/app_text_form_field.dart'; import '../../../new_views/common_widgets/app_text_form_field.dart';
class RecordSound extends StatefulWidget { class RecordSound extends StatefulWidget {
final Function(String) onRecord; final Function(String?) onRecord;
final Function(String) onStop; final Function(String)? onStop;
final bool enabled; 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 @override
State<RecordSound> createState() => _RecordSoundState(); State<RecordSound> createState() => _RecordSoundState();
@ -34,10 +34,10 @@ class _RecordSoundState extends State<RecordSound> {
bool _recorderIsOpened = false; bool _recorderIsOpened = false;
bool _recording = false; bool _recording = false;
bool _played = false; bool _played = false;
String _record; String? _record;
Artboard _rive; late Artboard _rive;
Timer _timer; Timer? _timer;
TextEditingController _timeController; late TextEditingController _timeController;
FocusNode node = FocusNode(); FocusNode node = FocusNode();
@ -89,7 +89,7 @@ class _RecordSoundState extends State<RecordSound> {
super.dispose(); super.dispose();
} }
String recordingFileDirectory; late String recordingFileDirectory;
_startRecording() async { _startRecording() async {
PermissionStatus status = await Permission.microphone.request(); PermissionStatus status = await Permission.microphone.request();
@ -102,10 +102,10 @@ class _RecordSoundState extends State<RecordSound> {
} }
_timer = Timer.periodic(const Duration(seconds: 1), (timer) { _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() { setState(() {
String duration = Duration(seconds: timer?.tick).toString(); String duration = Duration(seconds: timer.tick).toString();
duration = duration.substring(duration.indexOf(":") + 1, duration.indexOf(".")); 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"); // print("recordTime:$recordTime");
if (recordTime.length == 4 || recordTime.length == 7) { if (recordTime.length == 4 || recordTime.length == 7) {
recordTime = "0$recordTime"; recordTime = "0$recordTime";
@ -136,7 +136,7 @@ class _RecordSoundState extends State<RecordSound> {
return; return;
} }
if (_timer?.isActive ?? false) { if (_timer?.isActive ?? false) {
_timer.cancel(); _timer?.cancel();
} }
RecordMp3.instance.stop(); RecordMp3.instance.stop();
@ -174,7 +174,7 @@ class _RecordSoundState extends State<RecordSound> {
node: node, node: node,
controller: _timeController, controller: _timeController,
labelText: context.translation.recordVoice, labelText: context.translation.recordVoice,
initialValue: (_timeController?.text?.isEmpty ?? true) ? "00:00" : _timeController?.text, initialValue: (_timeController.text.isEmpty) ? "00:00" : _timeController.text,
suffixIcon: suffixIcon:
(_recording ? "record".toLottieAsset(height: 24) : (_record != null ? "trash" : "mic").toSvgAsset(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, height: 24)) (_recording ? "record".toLottieAsset(height: 24) : (_record != null ? "trash" : "mic").toSvgAsset(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, height: 24))
.paddingOnly(end: 16), .paddingOnly(end: 16),
@ -194,7 +194,7 @@ class _RecordSoundState extends State<RecordSound> {
], ],
), ),
if (_record != null) 8.height, if (_record != null) 8.height,
if (_record != null) ASoundPlayer(audio: _record), if (_record != null) ASoundPlayer(audio: _record!),
], ],
); );
} }

@ -7,19 +7,18 @@ import '../../../new_views/app_style/app_color.dart';
class AssistantEmployeeMenu extends StatefulWidget { class AssistantEmployeeMenu extends StatefulWidget {
final List<AssistantEmployees> statuses; final List<AssistantEmployees> statuses;
final AssistantEmployees initialStatus; final AssistantEmployees? initialStatus; // Now nullable
final Function(AssistantEmployees) onSelect; final Function(AssistantEmployees?) onSelect; // Now accepts nullable values
final String title; final String? title; // Now nullable
final bool enable; 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 @override
_SingleAssistantEmployeeMenuState createState() => _SingleAssistantEmployeeMenuState(); _SingleAssistantEmployeeMenuState createState() => _SingleAssistantEmployeeMenuState();
} }
class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> { class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> {AssistantEmployees? _selectedStatus; // Now nullable
AssistantEmployees _selectedStatus;
@override @override
void setState(VoidCallback fn) { void setState(VoidCallback fn) {
@ -29,15 +28,13 @@ class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> {
@override @override
void didUpdateWidget(covariant AssistantEmployeeMenu oldWidget) { void didUpdateWidget(covariant AssistantEmployeeMenu oldWidget) {
if (widget.initialStatus != null) { if (widget.initialStatus != null) {
final result = widget.statuses?.where((element) { final result = widget.statuses.where((element) => element.user?.id == widget.initialStatus?.user?.id);
return element?.user?.id == widget.initialStatus?.user?.id;
});
if (result.isNotEmpty) { if (result.isNotEmpty) {
_selectedStatus = result.first; _selectedStatus = result.first;
} else { } else {
_selectedStatus = null; _selectedStatus = null;
} }
if ((widget.initialStatus?.user?.id ?? "") != (_selectedStatus?.user?.id ?? "")) { if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) {
widget.onSelect(_selectedStatus); widget.onSelect(_selectedStatus);
} }
} else { } else {
@ -49,15 +46,14 @@ class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> {
@override @override
void initState() { void initState() {
if (widget.initialStatus != null) { if (widget.initialStatus != null) {
final result = widget.statuses?.where((element) { final result = widget.statuses.where((element) => element.user?.id == widget.initialStatus?.user?.id);
return element?.user?.id == widget.initialStatus?.user?.id; if (result.isNotEmpty) {
}); _selectedStatus = result.first;
if (result.isNotEmpty) _selectedStatus = result.first; }
if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) { if (widget.initialStatus?.user?.id != _selectedStatus?.user?.id) {
widget.onSelect(_selectedStatus); widget.onSelect(_selectedStatus);
} }
} }
super.initState(); super.initState();
} }
@ -79,14 +75,15 @@ class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> {
child: Icon( child: Icon(
Icons.keyboard_arrow_down_rounded, Icons.keyboard_arrow_down_rounded,
color: widget.enable ? null : Colors.grey, color: widget.enable ? null : Colors.grey,
)), ),
),
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
if (widget.title != null) if (widget.title != null)
Text( Text(
widget.title, widget.title!, // Non-null assertion after null check
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500),
), ),
DropdownButton<AssistantEmployees>( DropdownButton<AssistantEmployees>(
@ -102,33 +99,27 @@ class _SingleAssistantEmployeeMenuState extends State<AssistantEmployeeMenu> {
), ),
style: TextStyle(color: Theme.of(context).primaryColor), style: TextStyle(color: Theme.of(context).primaryColor),
underline: const SizedBox.shrink(), underline: const SizedBox.shrink(),
onChanged: widget.enable onChanged: widget.enable
? (AssistantEmployees newValue) { ? (AssistantEmployees? newValue) { // Now accepts nullable values
setState(() { setState(() {
_selectedStatus = newValue; _selectedStatus = newValue;
}); });
widget.onSelect(newValue); widget.onSelect(newValue);
} }
:null, :null,
items: widget.statuses.map<DropdownMenuItem<AssistantEmployees>>(
// onChanged: (AssistantEmployees newValue) { (AssistantEmployees value) {
// setState(() {
// _selectedStatus = newValue;
// });
// widget.onSelect(newValue);
// },
items: widget.statuses.map<DropdownMenuItem<AssistantEmployees>>((AssistantEmployees value) {
return DropdownMenuItem<AssistantEmployees>( return DropdownMenuItem<AssistantEmployees>(
value: value, value: value,
child: Text( child: Text(
value.user?.name ?? "NULL", value.user?.name ?? "NULL", // Use null-aware operator for user.name
style: Theme.of(context).textTheme.bodyLarge.copyWith( style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: widget.enable ? Theme.of(context).primaryColor : Colors.grey, color: widget.enable ? Theme.of(context).primaryColor : Colors.grey,
), ),
), ),
); );
}).toList(), },
).toList(),
), ),
], ],
), ),

@ -2,43 +2,38 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_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/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/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 '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 { class NurseMenu extends StatelessWidget {
final Function(Employee) onSelect; final Function(Employee?) onSelect; // Now accepts nullable Employee
final Employee initialValue; final Employee? initialValue; // Now nullable
final String title; final String title; // Now nullable
final bool enable; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
NurseProvider menuProvider = Provider.of<NurseProvider>(context); final menuProvider = Provider.of<NurseProvider>(context, listen: false);
menuProvider.siteId = siteId; if (siteId != null) {
menuProvider.siteId = siteId!;
}
return LoadingManager( return LoadingManager(
isLoading: menuProvider.isLoading, isLoading: menuProvider.isLoading,
isFailedLoading: menuProvider.nursesList == null, isFailedLoading: menuProvider.nursesList == null,
stateCode: menuProvider.stateCode, stateCode: menuProvider.stateCode,
onRefresh: () async { onRefresh: menuProvider.getData,
await menuProvider.getData(); // Directly pass the getData method
// menuProvider.setStateCode = null;
},
child: NurseEmployeeMenu( child: NurseEmployeeMenu(
initialValue: initialValue, initialValue: initialValue,
title: title, title: title,
list: menuProvider.nursesList, list: menuProvider.nursesList ?? [],
onSelect: (employee) { // Provide an empty list if null
onSelect(employee); onSelect: onSelect,
}, // Pass the onSelect function directly
enable: enable, enable: enable,
), ),
); );

@ -6,24 +6,23 @@ import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/employee.dart'; import 'package:test_sa/models/employee.dart';
import 'package:test_sa/views/widgets/bottom_sheets/selection_bottom_sheet.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'; import '../../../new_views/app_style/app_color.dart';
class NurseEmployeeMenu extends StatefulWidget { class NurseEmployeeMenu extends StatefulWidget {
final List<Employee> list; final List<Employee>? list;
final Employee initialValue; final Employee? initialValue;
final Function(Employee) onSelect; final Function(Employee?) onSelect;
final String title; 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 @override
_SingleNurseEmployeeMenuState createState() => _SingleNurseEmployeeMenuState(); _SingleNurseEmployeeMenuState createState() => _SingleNurseEmployeeMenuState();
} }
class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> { class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
Employee _selectedStatus; Employee? _selectedStatus;
@override @override
void setState(VoidCallback fn) { void setState(VoidCallback fn) {
@ -34,15 +33,16 @@ class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
void didUpdateWidget(covariant NurseEmployeeMenu oldWidget) { void didUpdateWidget(covariant NurseEmployeeMenu oldWidget) {
if (widget.initialValue != null) { if (widget.initialValue != null) {
final result = widget.list?.where((element) { final result = widget.list?.where((element) {
return element?.id == widget.initialValue?.id; return element.id == widget.initialValue?.id;
}); }) ??
[];
if (result.isNotEmpty) { if (result.isNotEmpty) {
_selectedStatus = result.first; _selectedStatus = result.first;
} else { } else {
_selectedStatus = null; _selectedStatus = null;
} }
if ((widget.initialValue?.id ?? "") != (_selectedStatus?.id ?? "")) { if ((widget.initialValue?.id ?? "") != (_selectedStatus?.id ?? "")) {
widget.onSelect(_selectedStatus); widget.onSelect!(_selectedStatus!);
} }
} else { } else {
_selectedStatus = null; _selectedStatus = null;
@ -54,8 +54,9 @@ class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
void initState() { void initState() {
if (widget.initialValue != null) { if (widget.initialValue != null) {
final result = widget.list?.where((element) { 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 (result.isNotEmpty) _selectedStatus = result.first;
if (widget.initialValue?.id != _selectedStatus?.id) { if (widget.initialValue?.id != _selectedStatus?.id) {
widget.onSelect(_selectedStatus); widget.onSelect(_selectedStatus);
@ -87,13 +88,12 @@ class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
end: 0, end: 0,
child: Icon( child: Icon(
Icons.keyboard_arrow_down_rounded, Icons.keyboard_arrow_down_rounded,
color: widget.enable ? null : Colors.grey, color: widget.enable == null ? null : Colors.grey,
)), )),
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
if (widget.title != null)
Text( Text(
widget.title, widget.title,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500), style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500),
@ -106,7 +106,7 @@ class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
), ),
], ],
), ),
).onPress(widget.enable ).onPress(((widget.enable ?? false)
? () async { ? () async {
_selectedStatus = (await showModalBottomSheet( _selectedStatus = (await showModalBottomSheet(
context: context, context: context,
@ -118,15 +118,15 @@ class _SingleNurseEmployeeMenuState extends State<NurseEmployeeMenu> {
), ),
clipBehavior: Clip.antiAliasWithSaveLayer, clipBehavior: Clip.antiAliasWithSaveLayer,
builder: (BuildContext context) => SelectionBottomSheet( builder: (BuildContext context) => SelectionBottomSheet(
items: widget.list, items: widget.list ?? [],
selectedItem: _selectedStatus, selectedItem: _selectedStatus,
title: widget.title, title: widget.title,
builderString: (emp) => emp?.name ?? "", builderString: (emp) => emp?.name ?? "",
), ),
)) as Employee; )) as Employee?;
if (_selectedStatus != null) setState(() {}); if (_selectedStatus != null) setState(() {});
widget.onSelect(_selectedStatus); widget.onSelect(_selectedStatus!);
} }
: null); : null));
} }
} }

@ -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'; import '../../../../controllers/providers/api/status_drop_down/report/service_report_assistants_employee_provider.dart';
class ServiceReportAssistantEmployeeMenu extends StatelessWidget { class ServiceReportAssistantEmployeeMenu extends StatelessWidget {
final Function(AssistantEmployees) onSelect; final Function(AssistantEmployees?) onSelect;
final AssistantEmployees initialValue; final AssistantEmployees? initialValue; // Now nullable
final String title; final String title;
final num assetId; final num assetId;
final bool enable; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ServiceReportAssistantsEmployeeProvider menuProvider = Provider.of<ServiceReportAssistantsEmployeeProvider>(context); final menuProvider = Provider.of<ServiceReportAssistantsEmployeeProvider>(context);
return LoadingManager( return LoadingManager(
isLoading: menuProvider.isLoading, isLoading: menuProvider.isLoading,
isFailedLoading: menuProvider.assistantEmployees == null, isFailedLoading: menuProvider.assistantEmployees == null,
stateCode: menuProvider.stateCode, stateCode: menuProvider.stateCode,
onRefresh: () async { onRefresh: () async {
await menuProvider.getAssistantEmployees(assetId); await menuProvider.getAssistantEmployees(assetId);
// menuProvider.setStateCode = null;
}, },
child: AssistantEmployeeMenu( child: AssistantEmployeeMenu(
initialStatus: initialValue, initialStatus: initialValue,
title: title, title: title,
statuses: menuProvider.assistantEmployees, statuses: menuProvider.assistantEmployees ?? [], // Provide an empty list if null
onSelect: (employee) { onSelect: onSelect, // Pass onSelect directly
if (employee.id == -1) {
onSelect(null);
} else {
onSelect(employee);
}
},
enable: enable, enable: enable,
), ),
); );

@ -10,28 +10,28 @@ import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart'; import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
class ServiceReportFaultDescription extends StatefulWidget { class ServiceReportFaultDescription extends StatefulWidget {
final String requestId; final String? requestId; // Now nullable
final Function(FaultDescription) onSelect; final Function(FaultDescription)? onSelect; // Now nullable
final FaultDescription initialValue; 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 @override
State<ServiceReportFaultDescription> createState() => _ServiceReportFaultDescriptionState(); State<ServiceReportFaultDescription> createState() => _ServiceReportFaultDescriptionState();
} }
class _ServiceReportFaultDescriptionState extends State<ServiceReportFaultDescription> { class _ServiceReportFaultDescriptionState extends State<ServiceReportFaultDescription> {
FaultDescription initialValue; FaultDescription? initialValue;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
initialValue = widget.initialValue; initialValue = widget.initialValue;
if (widget.initialValue == null) { if (widget.initialValue == null && widget.requestId != null) {
WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((timeStamp) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
ServiceRequestFaultDescriptionProvider menuProvider = Provider.of<ServiceRequestFaultDescriptionProvider>(context, listen: false); ServiceRequestFaultDescriptionProvider menuProvider = Provider.of<ServiceRequestFaultDescriptionProvider>(context, listen: false);
menuProvider.reset(); 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<ServiceReportFaultDescri
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
SettingProvider settingProvider = Provider.of<SettingProvider>(context); final settingProvider = Provider.of<SettingProvider>(context);
UserProvider userProvider = Provider.of<UserProvider>(context); final userProvider = Provider.of<UserProvider>(context);
ServiceRequestFaultDescriptionProvider menuProvider = Provider.of<ServiceRequestFaultDescriptionProvider>(context); final menuProvider = Provider.of<ServiceRequestFaultDescriptionProvider>(context);
return LoadingManager( return LoadingManager(
isLoading: menuProvider.isLoading, isLoading: menuProvider.isLoading,
isFailedLoading: menuProvider.items == null, isFailedLoading: menuProvider.items == null,
stateCode: menuProvider.stateCode, stateCode: menuProvider.stateCode,
onRefresh: () async { onRefresh: () async {
if (widget.requestId != null) {
// Add null check for requestId
menuProvider.reset(); menuProvider.reset();
await menuProvider.getCallRequestForWorkOrder(user: userProvider.user, host: settingProvider.host, requestId: widget.requestId); await menuProvider.getCallRequestForWorkOrder(widget.requestId!); // Non-null assertion since requestId is checked for null
}
}, },
child: SingleItemDropDownMenu<FaultDescription, NullableLoadingProvider>( child: SingleItemDropDownMenu<FaultDescription, NullableLoadingProvider>(
context: context, context: context,
title: context.translation.faultDescription, title: context.translation.faultDescription,
onSelect: widget.onSelect, onSelect: widget.onSelect,
// Pass onSelect directly
initialValue: initialValue, initialValue: initialValue,
staticData: menuProvider.items ?? [], staticData: menuProvider.items ?? [],
), ),
// child: FaultDescriptionMenu(
// initialStatus: initialValue,
// statuses: menuProvider.items ?? [],
// onSelect: onSelect,
// ),
); );
} }
} }

@ -11,17 +11,17 @@ import 'package:test_sa/views/app_style/sizing.dart';
import '../../../new_views/app_style/app_color.dart'; import '../../../new_views/app_style/app_color.dart';
class AppTimer extends StatefulWidget { class AppTimer extends StatefulWidget {
final TimerModel timer; final TimerModel? timer;
final Future<bool> Function(TimerModel) onChange; final Future<bool> Function(TimerModel)? onChange;
final TextStyle style; final TextStyle? style;
final BoxDecoration decoration; final BoxDecoration? decoration;
final bool enabled; final bool enabled;
final String label; final String? label;
final Function(bool) timerProgress; final Function(bool)? timerProgress;
const AppTimer({ const AppTimer({
Key key, Key? key,
this.label, this.label,
this.timer, this.timer,
this.onChange, this.onChange,
@ -36,46 +36,48 @@ class AppTimer extends StatefulWidget {
} }
class _AppTimerState extends State<AppTimer> { class _AppTimerState extends State<AppTimer> {
Timer _timer; Timer? _timer;
DateTime _startAt; DateTime? _startAt;
DateTime _endAt; DateTime? _endAt;
int _delay = 0; int _delay = 0;
bool _running = false; bool _running = false;
bool _loading = false; bool _loading = false;
final ValueNotifier<String> _period = ValueNotifier("0:00:00"); final ValueNotifier<String> _period = ValueNotifier("0:00:00");
_startTimer() async { Future<void> _startTimer() async {
if (!_running) { if (!_running && widget.onChange != null) {
final time = DateTime.now(); 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; if (!result) return;
_running = true; _running = true;
if (_endAt != null) { if (_endAt != null) {
_delay += _endAt.difference(_startAt).inSeconds; _delay += _endAt!.difference(_startAt!).inSeconds;
} }
_startAt = time.subtract(Duration(seconds: _delay)); _startAt = time.subtract(Duration(seconds: _delay));
_endAt = null; _endAt = null;
} }
_timer = Timer.periodic(const Duration(seconds: 1), (timer) { _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (_loading == true) return; if (_loading) return;
_period.value = (_endAt ?? DateTime.now()).difference(_startAt).toString().split(".").first; _period.value = (_endAt ?? DateTime.now()).difference(_startAt!).toString().split(".").first;
}); });
} }
_stopTimer() async { Future<void> _stopTimer() async {
if (widget.onChange != null) {
final time = DateTime.now(); final time = DateTime.now();
final tempStartAt = _startAt.add(Duration(seconds: _delay)); final tempStartAt = _startAt!.add(Duration(seconds: _delay));
bool result = await widget.onChange(TimerModel(startAt: tempStartAt, endAt: time, durationInSecond: _delay)); bool result = await widget.onChange!(TimerModel(startAt: tempStartAt, endAt: time, durationInSecond: _delay));
if (!result) return; if (!result) return;
_running = false; _running = false;
_endAt = time; _endAt = time;
_startAt = tempStartAt; _startAt = tempStartAt;
_timer?.cancel(); _timer?.cancel();
} }
}
_onPressed() async { Future<void> _onPressed() async {
_loading = true; _loading = true;
setState(() {}); setState(() {});
if (!_running) { if (!_running) {
@ -85,7 +87,7 @@ class _AppTimerState extends State<AppTimer> {
} }
_loading = false; _loading = false;
setState(() {}); setState(() {});
//widget.timerProgress(_running); //widget.timerProgress?(_running); // Use null-aware operator to call timerProgress
} }
@override @override
@ -93,8 +95,8 @@ class _AppTimerState extends State<AppTimer> {
_startAt = widget.timer?.startAt; _startAt = widget.timer?.startAt;
_endAt = widget.timer?.endAt; _endAt = widget.timer?.endAt;
_running = _startAt != null && _endAt == null; _running = _startAt != null && _endAt == null;
_delay = (widget.timer?.durationInSecond ?? 0); _delay = widget.timer?.durationInSecond ?? 0;
final difference = _startAt == null ? 0 : (_endAt ?? DateTime.now())?.difference(_startAt)?.inSeconds ?? 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; _period.value = Duration(seconds: _running ? difference : (difference != 0 ? difference : _delay)).toString().split(".").first;
super.initState(); super.initState();
if (_running) { if (_running) {
@ -104,6 +106,7 @@ class _AppTimerState extends State<AppTimer> {
@override @override
void dispose() { void dispose() {
_timer?.cancel(); // Cancel the timer when the widget is disposed
super.dispose(); super.dispose();
} }
@ -113,10 +116,11 @@ class _AppTimerState extends State<AppTimer> {
width: 100 * AppStyle.getScaleFactor(context), width: 100 * AppStyle.getScaleFactor(context),
height: 56.toScreenHeight, height: 56.toScreenHeight,
padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
decoration:widget.decoration?? BoxDecoration( decoration: widget.decoration ??
color: context.isDark && (widget.enabled == false) BoxDecoration(
color: context.isDark && !widget.enabled
? AppColor.neutral60 ? AppColor.neutral60
: (widget.enabled == false) : !widget.enabled
? AppColor.neutral40 ? AppColor.neutral40
: AppColor.background(context), : AppColor.background(context),
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
@ -150,6 +154,6 @@ class _AppTimerState extends State<AppTimer> {
if (widget.enabled) Icon(_running ? Icons.pause : Icons.play_arrow), if (widget.enabled) Icon(_running ? Icons.pause : Icons.play_arrow),
], ],
), ),
).onPress(_loading || widget.enabled == false ? () {} : _onPressed); ).onPress(_loading || !widget.enabled ? null : _onPressed);
} }
} }

@ -1,26 +1,26 @@
import 'package:flutter/material.dart'; // import 'package:flutter/material.dart';
import 'package:test_sa/views/app_style/sizing.dart'; // import 'package:test_sa/views/app_style/sizing.dart';
//
class ASubTitle extends StatelessWidget { // class ASubTitle extends StatelessWidget {
final String text; // final String text;
final EdgeInsets padding; // final EdgeInsets padding;
final Color color; // final Color color;
final double font; // final double font;
//
const ASubTitle(this.text, {Key key, this.padding, this.color, this.font}) : super(key: key); // const ASubTitle(this.text, {Key key, this.padding, this.color, this.font}) : super(key: key);
//
@override // @override
Widget build(BuildContext context) { // Widget build(BuildContext context) {
return Padding( // return Padding(
padding: padding ?? EdgeInsets.zero, // padding: padding ?? EdgeInsets.zero,
child: Text( // child: Text(
text, // text,
style: Theme.of(context).textTheme.bodyText1.copyWith( // style: Theme.of(context).textTheme.bodyLarge?.copyWith(
// fontWeight: FontWeight.bold, // // fontWeight: FontWeight.bold,
fontSize: font, // fontSize: font,
color: color), // color: color),
textScaleFactor: AppStyle.getScaleFactor(context), // textScaleFactor: AppStyle.getScaleFactor(context),
), // ),
); // );
} // }
} // }

@ -37,10 +37,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: async name: async
sha256: bfe67ef28df125b7dddcea62755991f807aa39a2492a23e1550161692950bbe0 sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.10.0" version: "2.11.0"
audioplayers: audioplayers:
dependency: "direct main" dependency: "direct main"
description: description:
@ -149,10 +149,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: characters name: characters
sha256: e6a326c8af69605aec75ed6c187d06b349707a27fbff8222ca9cc2cff167975c sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.2.1" version: "1.3.0"
checked_yaml: checked_yaml:
dependency: transitive dependency: transitive
description: description:
@ -181,10 +181,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: collection name: collection
sha256: cfc915e6923fe5ce6e153b0723c753045de46de1b4d63771530504004a45fae0 sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.17.0" version: "1.18.0"
convert: convert:
dependency: transitive dependency: transitive
description: description:
@ -382,6 +382,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.3.1" 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: flutter_keyboard_visibility:
dependency: transitive dependency: transitive
description: description:
@ -475,14 +483,6 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" 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: flutter_plugin_android_lifecycle:
dependency: transitive dependency: transitive
description: description:
@ -557,6 +557,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "10.4.0" version: "10.4.0"
get:
dependency: transitive
description:
name: get
sha256: e4e7335ede17452b391ed3b2ede016545706c01a02292a6c97619705e7d2a85e
url: "https://pub.dev"
source: hosted
version: "4.6.6"
graphs: graphs:
dependency: transitive dependency: transitive
description: description:
@ -681,10 +689,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: intl name: intl
sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.17.0" version: "0.18.1"
js: js:
dependency: transitive dependency: transitive
description: description:
@ -777,26 +785,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: "16db949ceee371e9b99d22f88fa3a73c4e59fd0afed0bd25fc336eb76c198b72" sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.13" version: "0.12.16"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
name: material_color_utilities name: material_color_utilities
sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.2.0" version: "0.5.0"
meta: meta:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "6c268b42ed578a53088d834796959e4a1814b5e9e164f147f580a386e5decf42" sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.8.0" version: "1.10.0"
mime: mime:
dependency: transitive dependency: transitive
description: description:
@ -841,10 +849,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: path name: path
sha256: db9d4f58c908a4ba5953fcee2ae317c94889433e5024c27ce74a37f94267945b sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.8.2" version: "1.8.3"
path_drawing: path_drawing:
dependency: transitive dependency: transitive
description: description:
@ -1037,14 +1045,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.0" version: "4.1.0"
record_mp3: record_mp3_plus:
dependency: "direct main" dependency: "direct main"
description: description:
name: record_mp3 name: record_mp3_plus
sha256: "2da2cd2f8c053f9ff03388019bc3eff035ef72f8ea8efac24674c5e528a1cc68" sha256: bf0b3f3ed96227a289ddf71605eb5370e5d43b8a2c17429ec55e60ace03d76e9
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.0" version: "1.2.0"
rive: rive:
dependency: "direct main" dependency: "direct main"
description: description:
@ -1158,10 +1166,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: source_span name: source_span
sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.9.1" version: "1.10.0"
speech_to_text: speech_to_text:
dependency: "direct main" dependency: "direct main"
description: description:
@ -1206,18 +1214,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: stack_trace name: stack_trace
sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.11.0" version: "1.11.1"
stream_channel: stream_channel:
dependency: transitive dependency: transitive
description: description:
name: stream_channel name: stream_channel
sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.1" version: "2.1.2"
string_scanner: string_scanner:
dependency: transitive dependency: transitive
description: description:
@ -1254,10 +1262,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: table_calendar name: table_calendar
sha256: "7f1270313c0cdb245b583ed8518982c01d4a7e95869b3c30abcbae3b642c45d0" sha256: "1e3521a3e6d3fc7f645a58b135ab663d458ab12504f1ea7f9b4b81d47086c478"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.8" version: "3.0.9"
term_glyph: term_glyph:
dependency: transitive dependency: transitive
description: description:
@ -1270,10 +1278,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: ad540f65f92caa91bf21dfc8ffb8c589d6e4dc0c2267818b4cc2792857706206 sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.4.16" version: "0.6.1"
timezone: timezone:
dependency: transitive dependency: transitive
description: description:
@ -1282,14 +1290,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.9.2" 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: typed_data:
dependency: transitive dependency: transitive
description: description:
@ -1386,6 +1386,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.4" version: "2.1.4"
web:
dependency: transitive
description:
name: web
sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152
url: "https://pub.dev"
source: hosted
version: "0.3.0"
win32: win32:
dependency: transitive dependency: transitive
description: description:
@ -1419,5 +1427,5 @@ packages:
source: hosted source: hosted
version: "3.1.2" version: "3.1.2"
sdks: sdks:
dart: ">=2.19.0 <3.0.0" dart: ">=3.2.0-194.0.dev <4.0.0"
flutter: ">=3.7.0" flutter: ">=3.16.0"

@ -18,7 +18,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.2.2+9 version: 1.2.2+9
environment: environment:
sdk: ">=2.7.0 <3.0.0" sdk: ">=2.12.0 <4.0.0"
localization_dir: assets\translations localization_dir: assets\translations
@ -50,7 +50,7 @@ dependencies:
flutter_local_notifications: ^12.0.1+1 flutter_local_notifications: ^12.0.1+1
cached_network_image: ^3.2.2 cached_network_image: ^3.2.2
carousel_slider: ^4.1.1 carousel_slider: ^4.1.1
intl: ^0.17.0 intl: ^0.18.0
flutter_typeahead: ^4.1.1 flutter_typeahead: ^4.1.1
speech_to_text: ^6.1.1 speech_to_text: ^6.1.1
firebase_core: ^2.4.0 firebase_core: ^2.4.0
@ -66,7 +66,7 @@ dependencies:
signature: ^5.3.0 signature: ^5.3.0
flutter_svg: ^1.1.6 flutter_svg: ^1.1.6
file_picker: ^5.2.5 file_picker: ^5.2.5
record_mp3: ^2.1.0 record_mp3_plus: any
path_provider: ^2.1.0 path_provider: ^2.1.0
open_file: ^3.3.2 open_file: ^3.3.2
localization: ^2.1.0 localization: ^2.1.0
@ -76,10 +76,10 @@ dependencies:
flutter_advanced_switch: ^3.0.1 flutter_advanced_switch: ^3.0.1
table_calendar: ^3.0.8 table_calendar: ^3.0.8
image_cropper: ^3.0.3 image_cropper: ^3.0.3
touchable: ^0.2.1
badges: ^3.1.1 badges: ^3.1.1
# buttons_tabbar: ^1.1.2 # buttons_tabbar: ^1.1.2
flutter_month_picker: ^0.0.2 flutter_custom_month_picker: ^0.1.3
syncfusion_flutter_charts: ^21.2.3 syncfusion_flutter_charts: ^21.2.3
local_auth: ^2.1.6 local_auth: ^2.1.6

Loading…
Cancel
Save