From ca11fe313458be4ad71beff0a83233d849354389 Mon Sep 17 00:00:00 2001 From: Fatimah Alshammari Date: Sun, 7 Nov 2021 09:27:19 +0300 Subject: [PATCH 1/8] fix issues --- lib/config/localized_values.dart | 1 + .../pharmacyModule/order_model_view_model.dart | 11 +++++++---- lib/pages/pharmacy/order/ProductReview.dart | 2 +- lib/uitl/translations_delegate_base.dart | 2 ++ 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/config/localized_values.dart b/lib/config/localized_values.dart index a61f86c4..69e412bb 100644 --- a/lib/config/localized_values.dart +++ b/lib/config/localized_values.dart @@ -1037,6 +1037,7 @@ const Map localizedValues = { "no-data": {"en": "No data found", "ar": "لاتوجد بيانات"}, "insurance-details": {"en": "Insurance Details", "ar": "تفاصيل التأمين"}, "nearest-hospital": {"en": "Nearest Hospital", "ar": "أقرب مستشفى"}, + "submitReview": {"en": "Your review has been Submitted successfully", "ar": "تم إرسال التقييم بنجاح"}, "request-sent": {"en": "Request sent successfully", "ar": "تم إرسال الطلب بنجاح"}, "message-sent": {"en": "Message sent successfully", "ar": "تم إرسال الرسالة بنجاح"}, "sent-on": {"en": "Sent on", "ar": "أرسلت في"}, diff --git a/lib/core/viewModels/pharmacyModule/order_model_view_model.dart b/lib/core/viewModels/pharmacyModule/order_model_view_model.dart index 232e10c4..fe5be016 100644 --- a/lib/core/viewModels/pharmacyModule/order_model_view_model.dart +++ b/lib/core/viewModels/pharmacyModule/order_model_view_model.dart @@ -11,6 +11,7 @@ import 'package:diplomaticquarterapp/services/pharmacy_services/cancelOrder_serv import 'package:diplomaticquarterapp/services/pharmacy_services/orderDetails_service.dart'; import 'package:diplomaticquarterapp/services/pharmacy_services/order_service.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import '../../../locator.dart'; import '../base_view_model.dart'; @@ -77,7 +78,8 @@ class OrderModelViewModel extends BaseViewModel { dynamic res; await _cancelOrderService.getCanceledOrder(order).then((value) { res = value['success']['SuccessEndUserMsg']; - AppToast.showSuccessToast(message: "Request Sent Successfully"); + // AppToast.showSuccessToast(message: "Request Sent Successfully"); + AppToast.showSuccessToast(message: TranslationBase.of(context).requestSent); // Navigator.pop(context); }); if (_cancelOrderService.hasError) { @@ -95,7 +97,7 @@ class OrderModelViewModel extends BaseViewModel { return res; } - Future makeReview(PharmacyProduct product, double rating, String reviewText) async { + Future makeReview(PharmacyProduct product, double rating, String reviewText, context) async { setState(ViewState.Busy); await _orderDetailsService.makeReview(product, rating, reviewText); if (_orderDetailsService.hasError) { @@ -104,8 +106,9 @@ class OrderModelViewModel extends BaseViewModel { AppToast.showErrorToast(message: error); } else { setState(ViewState.Idle); - AppToast.showSuccessToast( - message: "Your review has been Submitted successfully"); + AppToast.showSuccessToast(message: TranslationBase.of(context).submitReview); + // AppToast.showSuccessToast( + // message: "Your review has been Submitted successfully"); } } diff --git a/lib/pages/pharmacy/order/ProductReview.dart b/lib/pages/pharmacy/order/ProductReview.dart index 12ab939a..bb680864 100644 --- a/lib/pages/pharmacy/order/ProductReview.dart +++ b/lib/pages/pharmacy/order/ProductReview.dart @@ -201,7 +201,7 @@ class _ProductReviewPageState extends State { ? () { model .makeReview( - widget.product, ratingValue, reviewText) + widget.product, ratingValue, reviewText, context) .then((value) { setState(() { finishReview = true; diff --git a/lib/uitl/translations_delegate_base.dart b/lib/uitl/translations_delegate_base.dart index b15f7adb..12e01337 100644 --- a/lib/uitl/translations_delegate_base.dart +++ b/lib/uitl/translations_delegate_base.dart @@ -1770,6 +1770,8 @@ class TranslationBase { String get requestSent => localizedValues['request-sent'][locale.languageCode]; + String get submitReview => localizedValues['submitReview'][locale.languageCode]; + String get attachInsuraceImage => localizedValues['attach-insurace-image'][locale.languageCode]; String get infoInsurCards => localizedValues['info-insur-cards'][locale.languageCode]; From d5c68c503230f82a3fee9787c94728f73dab83bc Mon Sep 17 00:00:00 2001 From: Haroon Amjad Date: Mon, 8 Nov 2021 01:59:01 +0300 Subject: [PATCH 2/8] Packages & offers design --- .../responses/PackagesResponseModel.dart | 8 +- lib/core/service/client/base_app_client.dart | 1 - .../PackagesOffersServices.dart | 257 +++++--- .../OfferAndPackageDetailPage.dart | 5 +- .../packages_offers/OfferAndPackagesPage.dart | 594 +++++++++--------- .../offers_packages/PackagesOfferCard.dart | 245 ++++---- 6 files changed, 569 insertions(+), 541 deletions(-) diff --git a/lib/core/model/packages_offers/responses/PackagesResponseModel.dart b/lib/core/model/packages_offers/responses/PackagesResponseModel.dart index 7297a20a..8d4f619b 100644 --- a/lib/core/model/packages_offers/responses/PackagesResponseModel.dart +++ b/lib/core/model/packages_offers/responses/PackagesResponseModel.dart @@ -207,12 +207,10 @@ class PackagesResponseModel with JsonConvert { String seName; String getName() { - if(localizedNames.length == 2){ - if(localizedNames.first.languageId == 2) + if (localizedNames.length == 2) { + if (localizedNames.first.languageId == 2) return localizedNames.first.localizedName ?? name; - - else if(localizedNames.first.languageId == 1) - return localizedNames.last.localizedName ?? name; + else if (localizedNames.first.languageId == 1) return localizedNames.last.localizedName ?? name; } return name; } diff --git a/lib/core/service/client/base_app_client.dart b/lib/core/service/client/base_app_client.dart index 322ec08b..206c45c6 100644 --- a/lib/core/service/client/base_app_client.dart +++ b/lib/core/service/client/base_app_client.dart @@ -514,7 +514,6 @@ class BaseAppClient { simpleGet(String fullUrl, {Function(dynamic response, int statusCode) onSuccess, Function(String error, int statusCode) onFailure, Map queryParams, Map headers}) async { String url = fullUrl; - print("URL Query String: $url"); var haveParams = (queryParams != null); if (haveParams) { diff --git a/lib/core/service/packages_offers/PackagesOffersServices.dart b/lib/core/service/packages_offers/PackagesOffersServices.dart index d05bc274..3b34b957 100644 --- a/lib/core/service/packages_offers/PackagesOffersServices.dart +++ b/lib/core/service/packages_offers/PackagesOffersServices.dart @@ -21,7 +21,8 @@ import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:flutter/cupertino.dart'; -var packagesAuthHeader = {'Authorization' : ''}; +var packagesAuthHeader = {'Authorization': ''}; + class OffersAndPackagesServices extends BaseService { AuthenticatedUser patientUser; List categoryList = List(); @@ -33,52 +34,62 @@ class OffersAndPackagesServices extends BaseService { List cartItemList = List(); String cartItemCount = ""; - PackagesCustomerResponseModel customer; - Future> getAllCategories(OffersCategoriesRequestModel request) async { + Future> getAllCategories( + OffersCategoriesRequestModel request) async { Future errorThrow; var url = EXA_CART_API_BASE_URL + PACKAGES_CATEGORIES; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['categories'].forEach((json) { categoryList.add(PackagesCategoriesResponseModel().fromJson(json)); }); } - }, onFailure: (String error, int statusCode) { - }, queryParams: request.toFlatMap()); + }, + onFailure: (String error, int statusCode) {}, + queryParams: request.toFlatMap()); return categoryList; } - Future> getAllProducts({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { + Future> getAllProducts( + {@required OffersProductsRequestModel request, + @required BuildContext context, + @required bool showLoading = true}) async { Future errorThrow; request.sinceId = (productList.isNotEmpty) ? productList.last.id : 0; - + productList = List(); var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { productList.add(PackagesResponseModel().fromJson(json)); }); } - }, onFailure: (String error, int statusCode) { - }, queryParams: request.toFlatMap()); + }, + onFailure: (String error, int statusCode) {}, + queryParams: request.toFlatMap()); return productList; } - Future> getTamaraOptions({@required BuildContext context, @required bool showLoading = true}) async { - if(tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty) + Future> getTamaraOptions( + {@required BuildContext context, + @required bool showLoading = true}) async { + if (tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty) return tamaraPaymentOptions; var url = EXA_CART_API_BASE_URL + PACKAGES_TAMARA_OPT; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['payment_option'].forEach((json) { @@ -92,10 +103,13 @@ class OffersAndPackagesServices extends BaseService { return tamaraPaymentOptions; } - Future> getLatestOffers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { - + Future> getLatestOffers( + {@required OffersProductsRequestModel request, + @required BuildContext context, + @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -109,10 +123,14 @@ class OffersAndPackagesServices extends BaseService { return latestOffersList; } - Future> getBestSellers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { - + Future> getBestSellers( + {@required OffersProductsRequestModel request, + @required BuildContext context, + @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { + bestSellerList.clear(); if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -126,10 +144,13 @@ class OffersAndPackagesServices extends BaseService { return bestSellerList; } - - Future> getBanners({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { + Future> getBanners( + {@required OffersProductsRequestModel request, + @required BuildContext context, + @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -143,15 +164,16 @@ class OffersAndPackagesServices extends BaseService { return bannersList; } - Future loadOffersPackagesDataForMainPage({@required BuildContext context, bool showLoading = true, Function completion }) async { + Future loadOffersPackagesDataForMainPage( + {@required BuildContext context, + bool showLoading = true, + Function completion}) async { var finished = 0; - var totalCalls = 3; - - - completedAll(){ + var totalCalls = 2; + completedAll() { finished++; - if(completion != null && finished == totalCalls) { + if (completion != null && finished == totalCalls) { _hideLoading(context, showLoading); completion(); } @@ -160,57 +182,71 @@ class OffersAndPackagesServices extends BaseService { _showLoading(context, showLoading); final auth_token = await baseAppClient.generatePackagesToken(); - if(auth_token == null){ + if (auth_token == null) { throw 'Something went wrong while authentication, Please try again letter'; } packagesAuthHeader["Authorization"] = 'Bearer $auth_token'; - // Check and Create Customer - if(patientUser != null){ - customer = await getCurrentCustomer(context: context, showLoading: showLoading); - if(customer == null){ - createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), context: context); + if (patientUser != null) { + customer = + await getCurrentCustomer(context: context, showLoading: showLoading); + if (customer == null) { + createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), + context: context); } } // Performing Parallel Request on same time // # 1 - getBestSellers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value){ - completedAll(); + getBestSellers( + request: OffersProductsRequestModel(), + context: context, + showLoading: false) + .then((value) { + completedAll(); }); // # 2 - getLatestOffers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value){ + getLatestOffers( + request: OffersProductsRequestModel(), + context: context, + showLoading: false) + .then((value) { completedAll(); }); // # 3 - getBanners(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value){ - completedAll(); - }); - + // getBanners( + // request: OffersProductsRequestModel(), + // context: context, + // showLoading: false) + // .then((value) { + // completedAll(); + // }); } // -------------------- // Create Customer // -------------------- - Future createCustomer(PackagesCustomerRequestModel request, {@required BuildContext context, bool showLoading = true, Function(bool) completion }) async{ - if(customer != null) - return Future.value(customer); + Future createCustomer(PackagesCustomerRequestModel request, + {@required BuildContext context, + bool showLoading = true, + Function(bool) completion}) async { + if (customer != null) return Future.value(customer); customer = null; Future errorThrow; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER; - await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode){ - + await baseAppClient + .simplePost(url, headers: packagesAuthHeader, body: request.json(), + onSuccess: (dynamic stringResponse, int statusCode) { var jsonResponse = json.decode(stringResponse); var customerJson = jsonResponse['customers'].first; customer = PackagesCustomerResponseModel.fromJson(customerJson); - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { errorThrow = Future.error(error); log(error); }); @@ -221,55 +257,60 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? customer; } - Future getCurrentCustomer({@required BuildContext context, bool showLoading = true}) async{ - if(customer != null) - return Future.value(customer); + Future getCurrentCustomer( + {@required BuildContext context, bool showLoading = true}) async { + if (customer != null) return Future.value(customer); _showLoading(context, showLoading); - var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER + "/username/${patientUser.patientID}"; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode){ + var url = EXA_CART_API_BASE_URL + + PACKAGES_CUSTOMER + + "/username/${patientUser.patientID}"; + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { var jsonResponse = json.decode(stringResponse); var customerJson = jsonResponse['customers'].first; customer = PackagesCustomerResponseModel.fromJson(customerJson); - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { log(error); }); _hideLoading(context, showLoading); - return customer; + return customer; } - - // -------------------- // Shopping Cart // -------------------- - Future> cartItems({@required BuildContext context, bool showLoading = true}) async{ + Future> cartItems( + {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; cartItemList.clear(); _showLoading(context, showLoading); - var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}'; - Map jsonResponse; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + var url = + EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}'; + Map jsonResponse; + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); jsonResponse = json.decode(stringResponse); jsonResponse['shopping_carts'].forEach((json) { cartItemList.add(PackagesCartItemsResponseModel.fromJson(json)); }); - }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); log(error); - errorThrow = Future.error({"error":error, "statusCode":statusCode}); + errorThrow = Future.error({"error": error, "statusCode": statusCode}); }, queryParams: null); return errorThrow ?? jsonResponse; } - Future> addProductToCart(AddProductToCartRequestModel request, {@required BuildContext context, bool showLoading = true}) async{ + Future> addProductToCart( + AddProductToCartRequestModel request, + {@required BuildContext context, + bool showLoading = true}) async { Future errorThrow; ResponseModel response; @@ -277,55 +318,64 @@ class OffersAndPackagesServices extends BaseService { _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART; - await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode){ + await baseAppClient + .simplePost(url, headers: packagesAuthHeader, body: request.json(), + onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); var jsonCartItem = jsonResponse["shopping_carts"][0]; - response = ResponseModel(status: true, data: PackagesCartItemsResponseModel.fromJson(jsonCartItem), error: null); + response = ResponseModel( + status: true, + data: PackagesCartItemsResponseModel.fromJson(jsonCartItem), + error: null); cartItemCount = (jsonResponse['count'] ?? 0).toString(); - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); - errorThrow = Future.error(ResponseModel(status: true, data: null, error: error)); + errorThrow = + Future.error(ResponseModel(status: true, data: null, error: error)); }); return errorThrow ?? response; } - Future updateProductToCart(int cartItemID, {UpdateProductToCartRequestModel request, @required BuildContext context, bool showLoading = true}) async{ + Future updateProductToCart(int cartItemID, + {UpdateProductToCartRequestModel request, + @required BuildContext context, + bool showLoading = true}) async { Future errorThrow; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; - await baseAppClient.simplePut(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode){ + await baseAppClient + .simplePut(url, headers: packagesAuthHeader, body: request.json(), + onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); log(error); - errorThrow = Future.error({"error":error, "statusCode":statusCode}); + errorThrow = Future.error({"error": error, "statusCode": statusCode}); }); return errorThrow ?? bannersList; } - - Future deleteProductFromCart(int cartItemID, {@required BuildContext context, bool showLoading = true}) async{ + Future deleteProductFromCart(int cartItemID, + {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; - await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode){ + await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); // var jsonResponse = json.decode(stringResponse); - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); log(error); - errorThrow = Future.error({"error":error, "statusCode":statusCode}); + errorThrow = Future.error({"error": error, "statusCode": statusCode}); }); return errorThrow ?? true; @@ -334,29 +384,33 @@ class OffersAndPackagesServices extends BaseService { // -------------------- // Place Order // -------------------- - Future placeOrder({@required Map paymentParams, @required BuildContext context, bool showLoading = true}) async{ + Future placeOrder( + {@required Map paymentParams, + @required BuildContext context, + bool showLoading = true}) async { Future errorThrow; - Map jsonBody = { - "customer_id" : customer.id, + Map jsonBody = { + "customer_id": customer.id, "billing_address": { "email": patientUser.emailAddress, "phone_number": patientUser.mobileNumber }, }; jsonBody.addAll(paymentParams); - jsonBody = {'order' : jsonBody}; + jsonBody = {'order': jsonBody}; int order_id; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS; - await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode){ + await baseAppClient.simplePost(url, + headers: packagesAuthHeader, + body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); order_id = jsonResponse['orders'][0]['id']; - - }, onFailure: (String error, int statusCode){ + }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); log(error); errorThrow = Future.error(error); @@ -365,35 +419,34 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? order_id; } - Future> getOrderById(int id, {@required BuildContext context, bool showLoading = true}) async{ + Future> getOrderById(int id, + {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; ResponseModel response; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS + '/$id'; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, + onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); var jsonOrder = jsonResponse['orders'][0]; - response = ResponseModel(status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder)); - + response = ResponseModel( + status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder)); }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); - errorThrow = Future.error(ResponseModel(status: false,error: error)); + errorThrow = Future.error(ResponseModel(status: false, error: error)); }, queryParams: null); return errorThrow ?? response; } - } -_showLoading(BuildContext context, bool flag){ - if(flag) - GifLoaderDialogUtils.showMyDialog(context); +_showLoading(BuildContext context, bool flag) { + if (flag) GifLoaderDialogUtils.showMyDialog(context); } -_hideLoading(BuildContext context, bool flag){ - if(flag) - GifLoaderDialogUtils.hideDialog(context); -} \ No newline at end of file +_hideLoading(BuildContext context, bool flag) { + if (flag) GifLoaderDialogUtils.hideDialog(context); +} diff --git a/lib/pages/packages_offers/OfferAndPackageDetailPage.dart b/lib/pages/packages_offers/OfferAndPackageDetailPage.dart index f2ff8f6c..24e75797 100644 --- a/lib/pages/packages_offers/OfferAndPackageDetailPage.dart +++ b/lib/pages/packages_offers/OfferAndPackageDetailPage.dart @@ -1,3 +1,4 @@ +import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/ProductCheckTypeWidget.dart'; @@ -10,9 +11,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OfferAndPackagesDetail extends StatefulWidget{ - final dynamic model; + final PackagesResponseModel itemModel; - const OfferAndPackagesDetail({@required this.model, Key key}) : super(key: key); + const OfferAndPackagesDetail({@required this.itemModel, Key key}) : super(key: key); @override State createState() => OfferAndPackagesDetailState(); diff --git a/lib/pages/packages_offers/OfferAndPackagesPage.dart b/lib/pages/packages_offers/OfferAndPackagesPage.dart index 056e23e1..063cc541 100644 --- a/lib/pages/packages_offers/OfferAndPackagesPage.dart +++ b/lib/pages/packages_offers/OfferAndPackagesPage.dart @@ -1,13 +1,13 @@ -import 'package:after_layout/after_layout.dart'; -import 'package:carousel_slider/carousel_slider.dart'; import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersProductsRequestModel.dart'; +import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCategoriesResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; @@ -17,229 +17,261 @@ import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackageDetail import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackagesCartPage.dart'; import 'package:diplomaticquarterapp/routes.dart'; import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart' as auth; +import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart' as utils; -import 'package:diplomaticquarterapp/widgets/carousel_indicator/carousel_indicator.dart'; +import 'package:diplomaticquarterapp/uitl/utils_new.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart'; import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesOfferCard.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; -import 'package:flutter_material_pickers/flutter_material_pickers.dart'; - -dynamic languageID; +import 'package:provider/provider.dart'; class PackagesHomePage extends StatefulWidget { final AuthenticatedUser user; + PackagesHomePage(this.user); @override _PackagesHomePageState createState() => _PackagesHomePageState(); - } -class _PackagesHomePageState extends State with AfterLayoutMixin{ - getLanguageID() async { - languageID = await sharedPref.getString(APP_LANGUAGE); - } +class _PackagesHomePageState extends State { + ProjectViewModel projectViewModel; @override void initState() { super.initState(); - getLanguageID(); - } - - @override - void afterFirstLayout(BuildContext context) async{ - viewModel.service.patientUser = widget.user; - viewModel.service.loadOffersPackagesDataForMainPage(context: context, completion: (){ - setState((){}); + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + viewModel.service.loadOffersPackagesDataForMainPage( + context: context, + completion: () { + setState(() {}); + }); }); } // Controllers var _searchTextController = TextEditingController(); - var _filterTextController = TextEditingController(); - var _carouselController = CarouselController(); - - - int carouselIndicatorIndex = 0; - CarouselSlider _bannerCarousel; - TextField _textFieldSearch; - TextField _textFieldFilterSelection; ListView _listViewLatestOffers; ListView _listViewBestSeller; PackagesViewModel viewModel; - onCartClick(){ - if (viewModel.service.customer == null){ + onCartClick() { + if (viewModel.service.customer == null) { utils.Utils.showErrorToast("Cart is empty for your current session"); return; } - Navigator.of(context).push( - MaterialPageRoute( - builder: (BuildContext context) => PackagesCartPage() - ) - ); + Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => PackagesCartPage())); } onProductCartClick(PackagesResponseModel product) async { - if(viewModel.service.customer == null) { + if (viewModel.service.customer == null) { // viewModel.service.customer = await CreateCustomerDialogPage(context: context).show(); loginCheck(context); } - - if(viewModel.service.customer != null) { + + if (viewModel.service.customer != null) { var request = AddProductToCartRequestModel(product_id: product.id, customer_id: viewModel.service.customer.id); - await viewModel.service.addProductToCart(request, context: context).then((response){ - // appScaffold.appBar.badgeUpdater(viewModel.service.cartItemCount); - }).catchError((error) { + await viewModel.service.addProductToCart(request, context: context).then((response) {}).catchError((error) { utils.Utils.showErrorToast(error.toString()); }); } } AppScaffold appScaffold; + PackagesCategoriesResponseModel selectedClinic; + @override Widget build(BuildContext context) { + projectViewModel = Provider.of(context); return BaseView( - allowAny: true, - onModelReady: (model) => viewModel = model, - builder: (_, model, wi){ - return - appScaffold = - AppScaffold( - description: TranslationBase.of(context).offerAndPackagesDetails, - imagesInfo: [ImagesInfo(imageAr: 'https://hmgwebservices.com/Images/MobileApp/CMC/ar/0.png', imageEn: 'https://hmgwebservices.com/Images/MobileApp/CMC/en/0.png')], - appBarTitle: TranslationBase.of(context).offerAndPackages, - isShowAppBar: true, - isPharmacy: false, - showPharmacyCart: false, - showHomeAppBarIcon: false, - isOfferPackages: true, - showOfferPackagesCart: true, - isShowDecPage: false, - body: ListView( + allowAny: true, + onModelReady: (model) => viewModel = model, + builder: (_, model, wi) { + return appScaffold = AppScaffold( + description: TranslationBase.of(context).offerAndPackagesDetails, + imagesInfo: [ImagesInfo(imageAr: 'https://hmgwebservices.com/Images/MobileApp/CMC/ar/0.png', imageEn: 'https://hmgwebservices.com/Images/MobileApp/CMC/en/0.png')], + appBarTitle: TranslationBase.of(context).offerAndPackages, + isShowAppBar: true, + isPharmacy: false, + showPharmacyCart: false, + isOfferPackages: true, + showOfferPackagesCart: false, + isShowDecPage: false, + showNewAppBar: true, + showNewAppBarTitle: true, + body: SingleChildScrollView( + child: Column( + children: [ + SizedBox( + height: 10, + ), + Padding( + padding: const EdgeInsets.all(21), + child: Column( children: [ - - // Top Banner Carousel - AspectRatio( - aspectRatio: 2.2/1, - child: bannerCarousel() + inputWidget(TranslationBase.of(context).search, "", _searchTextController, isInputTypeNum: false), + SizedBox( + height: 10, ), - - Center( - child: CarouselIndicator( - activeColor: Theme.of(context).appBarTheme.color, - color: Colors.grey[300], - cornerRadius: 15, - width: 15, height: 15, - count: _bannerCarousel.itemCount, - index: carouselIndicatorIndex, - onClick: (index){ - debugPrint('onClick at ${index}'); + InkWell( + onTap: () => showClinicSelectionList(), + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 65, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Color(0xffefefef), + width: 1, + ), + color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + selectedClinic != null ? selectedClinic.name : "Browse offers by clinic", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + letterSpacing: -0.46, + ), + ), + Icon(Icons.arrow_drop_down), + ], + ), + ), + ), + SizedBox( + height: 20, + ), + Container( + width: double.infinity, + height: MediaQuery.of(context).size.width * 0.8, + child: ListView.separated( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + itemCount: viewModel.bestSellerList.length, + separatorBuilder: (context, index) { + return mWidth(9.0); + }, + itemBuilder: (BuildContext context, int index) { + return PackagesItemCard( + itemModel: viewModel.bestSellerList[index], + onCartClick: onProductCartClick, + ); }, ), ), - - SizedBox(height: 10,), - - Padding( - padding: const EdgeInsets.all(15), - child: Column( - children: [ - // Search Textfield - searchTextField(), - - SizedBox(height: 10,), - - // Filter Selection - filterOptionSelection(), - - SizedBox(height: 20,), - - // Horizontal Scrollable Cards - Texts( - "Latest offers", - fontWeight: FontWeight.bold, - color: Colors.black87, - fontSize: 20 - ), - - // Latest Offers Horizontal Scrollable List - AspectRatio( - aspectRatio: 1.3/1, - child: LayoutBuilder(builder: (context, constraints){ - double itemContentPadding = 10; - double itemWidth = (constraints.maxWidth/2) - (itemContentPadding*2); - return latestOfferListView(itemWidth: itemWidth, itemContentPadding: itemContentPadding); - }), - ), - - SizedBox(height: 10,), - - Texts( - "Best sellers", - fontWeight: FontWeight.bold, - color: Colors.black87, - fontSize: 20 - ), - - - // Best Seller Horizontal Scrollable List - AspectRatio( - aspectRatio: 1.3/1, - child: LayoutBuilder(builder: (context, constraints){ - double itemContentPadding = 10; // 10 is content padding in each item - double itemWidth = (constraints.maxWidth/2) - (itemContentPadding*2 /* 2 = LeftRight */); - return bestSellerListView(itemWidth: itemWidth, itemContentPadding: itemContentPadding); - }), - ) - - ],), + SizedBox( + height: 21, + ), + // // Best Seller Horizontal Scrollable List + Container( + width: double.infinity, + height: MediaQuery.of(context).size.width * 0.8, + child: ListView.separated( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + itemCount: viewModel.latestOffersList.length, + separatorBuilder: (context, index) { + return mWidth(9.0); + }, + itemBuilder: (BuildContext context, int index) { + return PackagesItemCard( + itemModel: viewModel.latestOffersList[index], + onCartClick: onProductCartClick, + ); + }, + ), ), ], ), + ), + SizedBox( + height: 50.0, ) - .setOnAppBarCartClick(onCartClick); - } + ], + ), + ), + bottomSheet: Container( + color: Colors.white, + padding: const EdgeInsets.all(12.0), + child: SizedBox( + height: 43, + width: double.infinity, + child: FlatButton( + onPressed: () { + onCartClick(); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.only(left: 8.0, right: 8.0), + child: Icon( + Icons.add_shopping_cart_rounded, + size: 30.0, + color: Colors.white, + ), + ), + Container( + child: Text( + TranslationBase.of(context).shoppingCart, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white, letterSpacing: -0.48), + ), + ), + ], + ), + color: const Color(0xffD02127), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6), + ), + ), + ), + ), + ); + }, ); } - - - showClinicSelectionList() async { var clinics = viewModel.service.categoryList; - if(clinics.isEmpty) { + if (clinics.isEmpty) { GifLoaderDialogUtils.showMyDialog(context); clinics = await viewModel.service.getAllCategories(OffersCategoriesRequestModel()); GifLoaderDialogUtils.hideDialog(context); } - List options = clinics.map((e) => e.toString()).toList(); - - showMaterialSelectionPicker( + List list = [ + for (int i = 0; i < clinics.length; i++) RadioSelectionDialogModel(clinics[i].name, i), + ]; + showDialog( context: context, - title: "Select Clinic", - items: options, - selectedItem: options.first, - onChanged: (value) async { - var selectedClinic = clinics.firstWhere((element) => element.toString() == value); - var clinicProducts = await viewModel.service.getAllProducts(request: OffersProductsRequestModel(categoryId: selectedClinic.id), context: context, showLoading: true); - if(clinicProducts.isNotEmpty) - Navigator.of(context).push( - MaterialPageRoute( - builder: (BuildContext context) => ClinicPackagesPage(products: clinicProducts) - ) - ); - else - utils.Utils.showErrorToast("No offers available for this clinic"); - }, + child: RadioSelectionDialog( + listData: list, + selectedIndex: 0, + isScrollable: true, + onValueSelected: (index) async { + selectedClinic = clinics[index]; + var clinicProducts = await viewModel.service.getAllProducts(request: OffersProductsRequestModel(categoryId: selectedClinic.id), context: context, showLoading: true); + if (clinicProducts.isNotEmpty) + Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => ClinicPackagesPage(products: clinicProducts))); + else + utils.Utils.showErrorToast("No offers available for this clinic"); + setState(() {}); + }, + ), ); } @@ -247,182 +279,46 @@ class _PackagesHomePageState extends State with AfterLayoutMix // Main Widgets of Page //---------------------------------- - CarouselSlider bannerCarousel(){ - _bannerCarousel = CarouselSlider.builder( - carouselController: _carouselController, - itemCount: 10, - itemBuilder: (BuildContext context, int itemIndex) { - return Padding( - padding: const EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 15), - child: FractionallySizedBox( - widthFactor: 1, - heightFactor: 1, - child: utils.applyShadow( - spreadRadius: 1, - blurRadius: 5, - child: InkWell( - child: ClipRRect( - borderRadius: BorderRadius.circular(10), - child: utils.Utils.loadNetworkImage(url: "https://wallpaperaccess.com/full/30103.jpg",) - ), - onTap: (){ - Navigator.of(context).push( - MaterialPageRoute( - builder: (BuildContext context) => OfferAndPackagesDetail(model: "",) - ) - ); - }, - ) - ), - ), + Widget latestOfferListView({@required double itemWidth, @required double itemContentPadding}) { + return _listViewLatestOffers = ListView.separated( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + itemCount: viewModel.bestSellerList.length, + itemBuilder: (BuildContext context, int index) { + return PackagesItemCard( + itemWidth: itemWidth, + itemContentPadding: itemContentPadding, + itemModel: viewModel.bestSellerList[index], + onCartClick: onProductCartClick, ); }, - options: CarouselOptions( - autoPlayInterval: Duration(milliseconds: 3500), - enlargeStrategy: CenterPageEnlargeStrategy.scale, - enlargeCenterPage: true, - autoPlay: false, - autoPlayCurve: Curves.fastOutSlowIn, - enableInfiniteScroll: true, - autoPlayAnimationDuration: Duration(milliseconds: 1500), - viewportFraction: 1, - onPageChanged: (page, reason){ - setState(() { - carouselIndicatorIndex = page; - }); - }, - ), + separatorBuilder: separator, ); - return _bannerCarousel; - } - - TextField searchTextField(){ - return _textFieldSearch = - TextField( - controller: _searchTextController, - decoration: InputDecoration( - contentPadding: EdgeInsets.only(top: 0.0, bottom: 0.0, left: 10, right: 10), - enabledBorder: OutlineInputBorder( - borderSide: BorderSide( width: 0.5, color: Colors.grey), - borderRadius: const BorderRadius.all( - const Radius.circular(10.0), - ), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide( width: 1, color: Colors.grey), - borderRadius: const BorderRadius.all( - const Radius.circular(10.0), - ), - ), - filled: true, - fillColor: Colors.white, - hintText: "Search", - hintStyle: TextStyle(color: Colors.grey[350], fontWeight: FontWeight.bold), - suffixIcon: IconButton( - onPressed: (){ - // viewModel.search(text: _searchTextController.text); - }, - icon: Icon(Icons.search_rounded, size: 35,), - ), - ), - ); - } - Widget filterOptionSelection(){ - _textFieldFilterSelection = - TextField( - enabled: false, - controller: _searchTextController, - decoration: InputDecoration( - contentPadding: EdgeInsets.only(top: 0.0, bottom: 0.0, left: 10, right: 10), - border: OutlineInputBorder( - borderSide: BorderSide(color: Colors.grey, width: 1), - borderRadius: const BorderRadius.all( - const Radius.circular(10.0), - ), - ), - disabledBorder: OutlineInputBorder( - borderSide: BorderSide( width: 0.5, color: Colors.grey), - borderRadius: const BorderRadius.all( - const Radius.circular(10.0), - ), - ), - focusedBorder: OutlineInputBorder( - borderRadius: const BorderRadius.all( - const Radius.circular(10.0), - ), - ), - filled: true, - fillColor: Colors.white, - hintText: "Browse offers by Clinic", - hintStyle: TextStyle(color: Colors.grey[350], fontWeight: FontWeight.bold), - suffixIcon: IconButton( - onPressed: (){ - showClinicSelectionList(); - }, - icon: Icon(Icons.keyboard_arrow_down_rounded, size: 35, color: Colors.grey,), - ), - ), + Widget bestSellerListView({@required double itemWidth, @required double itemContentPadding}) { + return _listViewLatestOffers = ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: viewModel.bestSellerList.length, + itemBuilder: (BuildContext context, int index) { + return PackagesItemCard( + itemWidth: itemWidth, + itemContentPadding: itemContentPadding, + itemModel: viewModel.bestSellerList[index], + onCartClick: onProductCartClick, ); - - return InkWell( - child: _textFieldFilterSelection, - onTap: (){ - showClinicSelectionList(); }, + separatorBuilder: separator, ); - } - Widget latestOfferListView({@required double itemWidth, @required double itemContentPadding}){ - return _listViewLatestOffers = - ListView.separated( - scrollDirection: Axis.horizontal, - itemCount: viewModel.bestSellerList.length, - itemBuilder: (BuildContext context, int index) { - return PackagesItemCard(itemWidth: itemWidth, itemContentPadding: itemContentPadding, itemModel: viewModel.bestSellerList[index], onCartClick: onProductCartClick,); - }, - separatorBuilder: separator, - ); - - } - - Widget bestSellerListView({@required double itemWidth, @required double itemContentPadding}){ - return _listViewLatestOffers = - ListView.separated( - scrollDirection: Axis.horizontal, - itemCount: viewModel.bestSellerList.length, - itemBuilder: (BuildContext context, int index) { - return PackagesItemCard(itemWidth: itemWidth, itemContentPadding: itemContentPadding, itemModel: viewModel.bestSellerList[index], onCartClick: onProductCartClick,); - }, - separatorBuilder: separator, - ); - - } - - - Widget separator(BuildContext context, int index){ + Widget separator(BuildContext context, int index) { return Container( width: 1, - decoration: BoxDecoration( - gradient: LinearGradient( - begin: Alignment(-1.0, -2.0), - end: Alignment(1.0, 4.0), - colors: [ - Colors.grey, - Colors.grey[100], - Colors.grey[200], - Colors.grey[300], - Colors.grey[400], - Colors.grey[500] - ] - )), + decoration: BoxDecoration(gradient: LinearGradient(begin: Alignment(-1.0, -2.0), end: Alignment(1.0, 4.0), colors: [Colors.grey, Colors.grey[100], Colors.grey[200], Colors.grey[300], Colors.grey[400], Colors.grey[500]])), ); } - - loginCheck(context) async { var data = await sharedPref.getObject(IMEI_USER_DATA); sharedPref.remove(REGISTER_DATA_FOR_LOGIIN); @@ -449,4 +345,74 @@ class _PackagesHomePageState extends State with AfterLayoutMix }); } } + + Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {VoidCallback suffixTap, bool isEnable = true, bool hasSelection = false, int lines, bool isInputTypeNum = false}) { + return Container( + padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(15), + color: Colors.white, + border: Border.all( + color: Color(0xffefefef), + width: 1, + ), + ), + child: InkWell( + onTap: hasSelection ? () {} : null, + child: Row( + children: [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _labelText, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xff2B353E), + letterSpacing: -0.44, + ), + ), + TextField( + enabled: isEnable, + scrollPadding: EdgeInsets.zero, + keyboardType: isInputTypeNum ? TextInputType.number : TextInputType.text, + controller: _controller, + maxLines: lines, + onChanged: (value) => {setState(() {})}, + style: TextStyle( + fontSize: 14, + height: 21 / 14, + fontWeight: FontWeight.w400, + color: Color(0xff2B353E), + letterSpacing: -0.44, + ), + decoration: InputDecoration( + isDense: true, + hintText: _hintText, + hintStyle: TextStyle( + fontSize: 14, + height: 21 / 14, + fontWeight: FontWeight.w400, + color: Color(0xff575757), + letterSpacing: -0.56, + ), + contentPadding: EdgeInsets.zero, + border: InputBorder.none, + focusedBorder: InputBorder.none, + enabledBorder: InputBorder.none, + ), + ), + ], + ), + ), + Icon(Icons.search_outlined), + ], + ), + ), + ); + } } diff --git a/lib/widgets/offers_packages/PackagesOfferCard.dart b/lib/widgets/offers_packages/PackagesOfferCard.dart index 2242f01d..470550c6 100644 --- a/lib/widgets/offers_packages/PackagesOfferCard.dart +++ b/lib/widgets/offers_packages/PackagesOfferCard.dart @@ -1,10 +1,14 @@ import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; +import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackageDetailPage.dart'; +import 'package:diplomaticquarterapp/theme/colors.dart'; +import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; +import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/StarRating.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; - +import 'package:rating_bar/rating_bar.dart'; bool wide = true; @@ -15,15 +19,7 @@ class PackagesItemCard extends StatefulWidget { final PackagesResponseModel itemModel; final Function(PackagesResponseModel product) onCartClick; - const PackagesItemCard( - { - this.itemWidth, - this.itemHeight, - @required this.itemModel, - @required this.itemContentPadding, - @required this.onCartClick, - Key key}) - : super(key: key); + const PackagesItemCard({this.itemWidth, this.itemHeight, @required this.itemModel, @required this.itemContentPadding, @required this.onCartClick, Key key}) : super(key: key); @override State createState() => PackagesItemCardState(); @@ -35,123 +31,138 @@ class PackagesItemCardState extends State { @override Widget build(BuildContext context) { wide = !wide; - return Directionality( - textDirection: TextDirection.rtl, - child: Stack( - children: [ - Padding( - padding: EdgeInsets.only( - left: widget.itemContentPadding, - right: widget.itemContentPadding, - top: widget.itemContentPadding + 5), - child: Container( - width: widget.itemWidth, - color: Colors.transparent, - child: Stack( + return InkWell( + onTap: () { + Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => OfferAndPackagesDetail(itemModel: widget.itemModel))); + }, + child: Container( + // width: widget.itemWidth, + // color: Colors.transparent, + decoration: cardRadius(15.0), + width: MediaQuery.of(context).size.width * 0.46, + padding: const EdgeInsets.all(9.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(15.0), + child: Image.network("https://mdlaboratories.com/offersdiscounts/images/thumbs/0000162_dermatology-testing.jpeg", fit: BoxFit.fill, height: 180.0, width: 180.0), + ), + Container(margin: const EdgeInsets.only(top: 8.0), child: Text(widget.itemModel.name, maxLines: 1, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold, letterSpacing: -0.56))), + Container(width: MediaQuery.of(context).size.width * 0.4, child: Text("Special discount for all HMG Employees and their first…", maxLines: 2, style: TextStyle(fontSize: 10.0, fontWeight: FontWeight.w600, letterSpacing: -0.4, color: CustomColors.textColor), overflow: TextOverflow.clip)), + if (widget.itemModel.hasDiscountsApplied) Container(margin: const EdgeInsets.only(top: 19.0), child: Text(widget.itemModel.oldPrice.toString() + " " + TranslationBase.of(context).sar, style: TextStyle(fontSize: 9.0, fontWeight: FontWeight.w600, letterSpacing: -0.36, decoration: TextDecoration.lineThrough, color: CustomColors.grey2))), + Container( + margin: widget.itemModel.hasDiscountsApplied ? const EdgeInsets.only(top: 0.0) : const EdgeInsets.only(top: 19.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( - mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - AspectRatio( - aspectRatio:1 / 1, - child: applyShadow( - child: ClipRRect( - borderRadius: BorderRadius.circular(10), - child: Utils.loadNetworkImage( - url: imageUrl(), - )), - )), - Texts( - widget.itemModel.getName(), - fontWeight: FontWeight.normal, - color: Colors.black, - fontSize: 15 - ), - Padding( - padding: const EdgeInsets.only(left: 10, right: 10), - child: Row( - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisSize: MainAxisSize.max, - children: [ - Stack( - children: [ - Texts( - '${widget.itemModel.oldPrice} ${'SAR'}', - fontWeight: FontWeight.normal, - decoration: TextDecoration.lineThrough, - color: Colors.grey, - fontSize: 12 - ), - Padding( - padding: const EdgeInsets.only(top: 8), - child: Texts( - '${widget.itemModel.price} ${'SAR'}', - fontWeight: FontWeight.bold, - color: Colors.green, - fontSize: 18 - ), - ), - Padding( - padding: const EdgeInsets.only(top: 35), - child: StarRating( - size: 15, - totalCount: null, - totalAverage: widget.itemModel.approvedRatingSum.toDouble(), - forceStars: true), - ) - ], - ), - Spacer( - flex: 1, - ), - InkWell( - child: Icon( - Icons.add_shopping_cart_rounded, - size: 30.0, - color: Colors.grey, - ), - onTap: () { - widget.onCartClick(widget.itemModel); - }, - ), - ], - ), + Container(margin: const EdgeInsets.only(top: 0.0), child: Text(widget.itemModel.price.toString().trim() + " " + TranslationBase.of(context).sar, style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold, letterSpacing: -0.56))), + RatingBar.readOnly( + initialRating: 4.5, + size: 18.0, + filledColor: Color(0XFFD02127), + emptyColor: Color(0XFFD02127), + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star_border, ), ], ), + InkWell( + child: Icon( + Icons.add_shopping_cart_rounded, + size: 30.0, + color: Colors.black, + ), + onTap: () { + widget.onCartClick(widget.itemModel); + }, + ), ], ), ), - ), - Positioned( - top: 0, - right: 0, - child: Visibility( - visible: false, - child: InkWell( - child: Icon( - Icons.favorite, - size: 40.0, - color: Colors.red, - ), - onTap: () { - - }, - ), - ), - ), - - Positioned( - top: 7, - left: 2, - child: Image.asset( - 'assets/images/discount_${'en'}.png', - height: 60, - width: 60, - ), - ), - ], + ], + ), ), ); + // Stack( + // children: [ + // Column( + // mainAxisSize: MainAxisSize.max, + // children: [ + // AspectRatio( + // aspectRatio:1 / 1, + // child: applyShadow( + // child: ClipRRect( + // borderRadius: BorderRadius.circular(10), + // child: Utils.loadNetworkImage( + // url: imageUrl(), + // )), + // )), + // Texts( + // widget.itemModel.getName(), + // fontWeight: FontWeight.normal, + // color: Colors.black, + // fontSize: 15 + // ), + // Padding( + // padding: const EdgeInsets.only(left: 10, right: 10), + // child: Row( + // crossAxisAlignment: CrossAxisAlignment.end, + // mainAxisSize: MainAxisSize.max, + // children: [ + // Stack( + // children: [ + // Texts( + // '${widget.itemModel.oldPrice} ${'SAR'}', + // fontWeight: FontWeight.normal, + // decoration: TextDecoration.lineThrough, + // color: Colors.grey, + // fontSize: 12 + // ), + // Padding( + // padding: const EdgeInsets.only(top: 8), + // child: Texts( + // '${widget.itemModel.price} ${'SAR'}', + // fontWeight: FontWeight.bold, + // color: Colors.green, + // fontSize: 18 + // ), + // ), + // Padding( + // padding: const EdgeInsets.only(top: 35), + // child: StarRating( + // size: 15, + // totalCount: null, + // totalAverage: widget.itemModel.approvedRatingSum.toDouble(), + // forceStars: true), + // ) + // ], + // ), + // Spacer( + // flex: 1, + // ), + // InkWell( + // child: Icon( + // Icons.add_shopping_cart_rounded, + // size: 30.0, + // color: Colors.grey, + // ), + // onTap: () { + // widget.onCartClick(widget.itemModel); + // }, + // ), + // ], + // ), + // ), + // ], + // ), + // ], + // ), + // ); } } From eb4801c7ee2eea821afef18bf36c64214bb97710 Mon Sep 17 00:00:00 2001 From: Fatimah Alshammari Date: Mon, 8 Nov 2021 11:16:16 +0300 Subject: [PATCH 3/8] fixed rating issues --- lib/pages/final_products_page.dart | 41 ++++++++++++----- lib/pages/offers_categorise_page.dart | 63 ++++++++++++++++++--------- lib/pages/parent_categorise_page.dart | 41 ++++++++++++----- lib/pages/sub_categorise_page.dart | 41 ++++++++++++----- 4 files changed, 135 insertions(+), 51 deletions(-) diff --git a/lib/pages/final_products_page.dart b/lib/pages/final_products_page.dart index 5705f726..ea5ee011 100644 --- a/lib/pages/final_products_page.dart +++ b/lib/pages/final_products_page.dart @@ -15,6 +15,7 @@ import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/others/network_base_view.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; +import 'package:rating_bar/rating_bar.dart'; import 'base/base_view.dart'; @@ -274,11 +275,21 @@ class _FinalProductsPageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.finalProducts[index].approvedRatingSum > 0 - ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.finalProducts[index].approvedRatingSum > 0 +// ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.finalProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.finalProducts[index].approvedTotalReviews})", regular: true, @@ -424,11 +435,21 @@ class _FinalProductsPageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.finalProducts[index].approvedRatingSum > 0 - ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.finalProducts[index].approvedRatingSum > 0 +// ? (model.finalProducts[index].approvedRatingSum.toDouble() / model.finalProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.finalProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.finalProducts[index].approvedTotalReviews})", regular: true, diff --git a/lib/pages/offers_categorise_page.dart b/lib/pages/offers_categorise_page.dart index 15c3b070..263aef5c 100644 --- a/lib/pages/offers_categorise_page.dart +++ b/lib/pages/offers_categorise_page.dart @@ -7,6 +7,7 @@ import 'package:diplomaticquarterapp/widgets/others/app_scaffold_pharmacy_widget import 'package:diplomaticquarterapp/widgets/others/network_base_view.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:rating_bar/rating_bar.dart'; import 'base/base_view.dart'; @@ -428,14 +429,24 @@ class _OffersCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.products[index].approvedRatingSum > - 0 - ? (model.products[index].approvedRatingSum.toDouble() / model.products[index].approvedRatingSum.toDouble()) - .toDouble() - : 0, - forceStars: - true), +// StarRating( +// totalAverage: model.products[index].approvedRatingSum > +// 0 +// ? (model.products[index].approvedRatingSum.toDouble() / model.products[index].approvedRatingSum.toDouble()) +// .toDouble() +// : 0, +// forceStars: +// true), + RatingBar.readOnly( + initialRating: model.products[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.products[index].approvedTotalReviews})", regular: true, @@ -663,19 +674,29 @@ class _OffersCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model - .products[ - index] - .approvedRatingSum > - 0 - ? (model.products[index].approvedRatingSum.toDouble() / - model.products[index].approvedRatingSum - .toDouble()) - .toDouble() - : 0, - forceStars: - true), +// StarRating( +// totalAverage: model +// .products[ +// index] +// .approvedRatingSum > +// 0 +// ? (model.products[index].approvedRatingSum.toDouble() / +// model.products[index].approvedRatingSum +// .toDouble()) +// .toDouble() +// : 0, +// forceStars: +// true), + RatingBar.readOnly( + initialRating: model.products[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.products[index].approvedTotalReviews})", regular: true, diff --git a/lib/pages/parent_categorise_page.dart b/lib/pages/parent_categorise_page.dart index ec37cff5..d8c2279c 100644 --- a/lib/pages/parent_categorise_page.dart +++ b/lib/pages/parent_categorise_page.dart @@ -22,6 +22,7 @@ import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:rating_bar/rating_bar.dart'; import 'base/base_view.dart'; @@ -714,11 +715,21 @@ class _ParentCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.parentProducts[index].approvedRatingSum > 0 - ? (model.parentProducts[index].approvedRatingSum.toDouble() / model.parentProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.parentProducts[index].approvedRatingSum > 0 +// ? (model.parentProducts[index].approvedRatingSum.toDouble() / model.parentProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.parentProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.parentProducts[index].approvedTotalReviews})", regular: true, @@ -838,11 +849,21 @@ class _ParentCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.parentProducts[index].approvedRatingSum > 0 - ? (model.parentProducts[index].approvedRatingSum.toDouble() / model.parentProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.parentProducts[index].approvedRatingSum > 0 +// ? (model.parentProducts[index].approvedRatingSum.toDouble() / model.parentProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.parentProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.parentProducts[index].approvedTotalReviews})", regular: true, diff --git a/lib/pages/sub_categorise_page.dart b/lib/pages/sub_categorise_page.dart index e5a8b097..9d2a1f6b 100644 --- a/lib/pages/sub_categorise_page.dart +++ b/lib/pages/sub_categorise_page.dart @@ -17,6 +17,7 @@ import 'package:diplomaticquarterapp/widgets/others/entity_checkbox_list.dart'; import 'package:diplomaticquarterapp/widgets/others/network_base_view.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; +import 'package:rating_bar/rating_bar.dart'; import 'base/base_view.dart'; import 'final_products_page.dart'; @@ -641,11 +642,21 @@ class _SubCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.subProducts[index].approvedRatingSum > 0 - ? (model.subProducts[index].approvedRatingSum.toDouble() / model.subProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.subProducts[index].approvedRatingSum > 0 +// ? (model.subProducts[index].approvedRatingSum.toDouble() / model.subProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.subProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.subProducts[index].approvedTotalReviews})", regular: true, @@ -766,11 +777,21 @@ class _SubCategorisePageState extends State { ), Row( children: [ - StarRating( - totalAverage: model.subProducts[index].approvedRatingSum > 0 - ? (model.subProducts[index].approvedRatingSum.toDouble() / model.subProducts[index].approvedRatingSum.toDouble()).toDouble() - : 0, - forceStars: true), +// StarRating( +// totalAverage: model.subProducts[index].approvedRatingSum > 0 +// ? (model.subProducts[index].approvedRatingSum.toDouble() / model.subProducts[index].approvedRatingSum.toDouble()).toDouble() +// : 0, +// forceStars: true), + RatingBar.readOnly( + initialRating: model.subProducts[index].approvedRatingSum.toDouble(), + size: 15.0, + filledColor: Colors.yellow[700], + emptyColor: Colors.grey[500], + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star, + ), Texts( "(${model.subProducts[index].approvedTotalReviews})", regular: true, From 502c7fd3dea273c5c4bfc92b70c80a20af273c3f Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 8 Nov 2021 17:54:31 +0300 Subject: [PATCH 4/8] Offers & discounts UI updating --- lib/config/localized_values.dart | 2 + .../responses/PackagesResponseModel.dart | 2 + .../PackagesOffersServices.dart | 1 + .../OfferProductsResponseModel_helper.dart | 6 + .../fragments/home_page_fragment2.dart | 3 +- .../OfferAndPackageDetailPage.dart | 384 ++++++++++-------- .../OfferAndPackagesCartPage.dart | 189 ++++----- .../packages_offers/OfferAndPackagesPage.dart | 36 +- lib/uitl/translations_delegate_base.dart | 6 +- .../offers_packages/PackagesCartItemCard.dart | 269 +++++------- .../offers_packages/PackagesOfferCard.dart | 84 +--- 11 files changed, 416 insertions(+), 566 deletions(-) diff --git a/lib/config/localized_values.dart b/lib/config/localized_values.dart index a61f86c4..d35fce51 100644 --- a/lib/config/localized_values.dart +++ b/lib/config/localized_values.dart @@ -1630,4 +1630,6 @@ const Map localizedValues = { "RRTTitle": {"en": "RRT", "ar": "خدمة فريق"}, "RRTSubTitle": {"en": "Service", "ar": "الاستجابة السريع"}, "transportation": {"en": "Transportation", "ar": "النقل"}, + "myCart": {"en": "Cart", "ar": "عربة التسوق"}, + "browseOffers": {"en": "Browse offers by clinic", "ar": "تصفح العروض حسب العيادة"}, }; diff --git a/lib/core/model/packages_offers/responses/PackagesResponseModel.dart b/lib/core/model/packages_offers/responses/PackagesResponseModel.dart index 8d4f619b..23a864f7 100644 --- a/lib/core/model/packages_offers/responses/PackagesResponseModel.dart +++ b/lib/core/model/packages_offers/responses/PackagesResponseModel.dart @@ -192,6 +192,8 @@ class PackagesResponseModel with JsonConvert { List discountIds; @JSONField(name: "store_ids") List storeIds; + @JSONField(name: "store_names") + List storeNames; @JSONField(name: "manufacturer_ids") List manufacturerIds; List reviews; diff --git a/lib/core/service/packages_offers/PackagesOffersServices.dart b/lib/core/service/packages_offers/PackagesOffersServices.dart index 3b34b957..238cb611 100644 --- a/lib/core/service/packages_offers/PackagesOffersServices.dart +++ b/lib/core/service/packages_offers/PackagesOffersServices.dart @@ -110,6 +110,7 @@ class OffersAndPackagesServices extends BaseService { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + latestOffersList.clear(); if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { diff --git a/lib/generated/json/OfferProductsResponseModel_helper.dart b/lib/generated/json/OfferProductsResponseModel_helper.dart index d180af67..ca402fc0 100644 --- a/lib/generated/json/OfferProductsResponseModel_helper.dart +++ b/lib/generated/json/OfferProductsResponseModel_helper.dart @@ -313,6 +313,12 @@ offerProductsResponseModelFromJson(PackagesResponseModel data, Map(); data.storeIds.addAll(json['store_ids']); } + + if (json['store_names'] != null) { + data.storeNames = new List(); + data.storeNames.addAll(json['store_names']); + } + if (json['manufacturer_ids'] != null) { data.manufacturerIds = json['manufacturer_ids']?.map((v) => v?.toInt())?.toList()?.cast(); } diff --git a/lib/pages/landing/fragments/home_page_fragment2.dart b/lib/pages/landing/fragments/home_page_fragment2.dart index 4714c208..75b9a473 100644 --- a/lib/pages/landing/fragments/home_page_fragment2.dart +++ b/lib/pages/landing/fragments/home_page_fragment2.dart @@ -5,6 +5,7 @@ import 'package:diplomaticquarterapp/core/viewModels/dashboard_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart'; import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart'; +import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/models/gradient_color.dart'; import 'package:diplomaticquarterapp/models/hmg_services.dart'; import 'package:diplomaticquarterapp/models/slider_data.dart'; @@ -282,7 +283,7 @@ class _HomePageFragment2State extends State { flex: 1, child: InkWell( onTap: () { - final user = projectViewModel.user; + AuthenticatedUser user = projectViewModel.user; Navigator.of(context).push(MaterialPageRoute(builder: (context) => PackagesHomePage(user))); }, child: Container( diff --git a/lib/pages/packages_offers/OfferAndPackageDetailPage.dart b/lib/pages/packages_offers/OfferAndPackageDetailPage.dart index 24e75797..17c88cc8 100644 --- a/lib/pages/packages_offers/OfferAndPackageDetailPage.dart +++ b/lib/pages/packages_offers/OfferAndPackageDetailPage.dart @@ -1,214 +1,254 @@ import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; -import 'package:diplomaticquarterapp/pages/pharmacies/ProductCheckTypeWidget.dart'; +import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; -import 'package:diplomaticquarterapp/uitl/utils.dart' as utils; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; -import 'package:diplomaticquarterapp/widgets/others/StarRating.dart'; +import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; +import 'package:expandable/expandable.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:html/parser.dart'; +import 'package:rating_bar/rating_bar.dart'; -class OfferAndPackagesDetail extends StatefulWidget{ +class OfferAndPackagesDetail extends StatefulWidget { final PackagesResponseModel itemModel; + final Function(PackagesResponseModel product) onCartClick; - const OfferAndPackagesDetail({@required this.itemModel, Key key}) : super(key: key); + const OfferAndPackagesDetail({@required this.itemModel, @required this.onCartClick, Key key}) : super(key: key); @override State createState() => OfferAndPackagesDetailState(); } - -class OfferAndPackagesDetailState extends State{ - +class OfferAndPackagesDetailState extends State { PackagesViewModel viewModel; + bool expandFlag = false; + var controller = new ExpandableController(); + @override Widget build(BuildContext context) { return BaseView( - onModelReady: (model){ + onModelReady: (model) { viewModel = model; }, builder: (_, model, wi) => AppScaffold( - appBarTitle: TranslationBase.of(context).offerAndPackages, - isShowAppBar: true, - isPharmacy: false, - showPharmacyCart: false, - showHomeAppBarIcon: false, - isOfferPackages: true, - showOfferPackagesCart: true, - isShowDecPage: false, - body: Stack( + appBarTitle: TranslationBase.of(context).offerAndPackages, + isShowAppBar: true, + isPharmacy: false, + showPharmacyCart: false, + showHomeAppBarIcon: false, + isOfferPackages: true, + showOfferPackagesCart: true, + isShowDecPage: false, + showNewAppBar: true, + showNewAppBarTitle: true, + body: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding( - padding: const EdgeInsets.only(bottom: 60), - child: ListView( - children: [ - Padding( - padding: const EdgeInsets.all(5), - child: Stack( - children: [ - Padding( - padding: const EdgeInsets.all(10), - child: AspectRatio( - aspectRatio: 1/1, - child: utils.applyShadow( - child: ClipRRect( - borderRadius: BorderRadius.circular(10), - child: utils.Utils.loadNetworkImage(url: "https://wallpaperaccess.com/full/30103.jpg",) - ), - ) - ), - ), - Align( - alignment: Alignment.topLeft, - child: Image.asset( - 'assets/images/discount_${'en'}.png', - height: 70, - width: 70, - ), - ), - - ], - - ), + Container( + color: Colors.white, + padding: const EdgeInsets.all(21.0), + child: ClipRRect( + borderRadius: BorderRadius.circular(15.0), + child: Image.network("https://mdlaboratories.com/offersdiscounts/images/thumbs/0000162_dermatology-testing.jpeg", fit: BoxFit.fill), + ), + ), + Container( + padding: const EdgeInsets.only(left: 21.0, right: 21.0, top: 21.0), + child: Text(widget.itemModel.name, maxLines: 1, style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold, letterSpacing: -1.14))), + Container( + padding: const EdgeInsets.only(left: 21.0, right: 21.0), + child: Text(widget.itemModel.shortDescription, + maxLines: 2, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.textColor), overflow: TextOverflow.clip)), + Row( + children: [ + Container( + padding: const EdgeInsets.only(left: 21.0, right: 21.0, top: 12.0), + child: RatingBar.readOnly( + initialRating: 4.5, + size: 18.0, + filledColor: Color(0XFFD02127), + emptyColor: Color(0XFFD02127), + isHalfAllowed: true, + halfFilledIcon: Icons.star_half, + filledIcon: Icons.star, + emptyIcon: Icons.star_border, ), - - Padding( - padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts( - "Child Dental Offer", - fontSize: 25, - fontWeight: FontWeight.normal, - color: Colors.black, - ), - - Stack( - children: [ - Texts( - "200 SAR", - fontWeight: FontWeight.normal, - decoration: TextDecoration.lineThrough, - color: Colors.grey, - fontSize: 12 - ), - Padding( - padding: const EdgeInsets.only(top: 15), - child: Texts( - "894.99 SAR", - fontWeight: FontWeight.bold, - color: Colors.green, - fontSize: 18 + ), + ], + ), + Container( + padding: const EdgeInsets.only(left: 21.0, right: 21.0, top: 18.0), + width: double.infinity, + height: 50.0, + child: ListView.separated( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + itemCount: widget.itemModel.storeNames.length, + separatorBuilder: (context, index) { + return mWidth(5.0); + }, + itemBuilder: (BuildContext context, int index) { + return contactButton(widget.itemModel.storeNames[index].toString()); + }, + ), + ), + Container( + padding: const EdgeInsets.only(top: 18.0), + child: ExpandableNotifier( + initialExpanded: true, + child: Container( + color: Colors.white, + child: Column( + children: [ + ScrollOnExpand( + scrollOnExpand: true, + scrollOnCollapse: false, + child: ExpandablePanel( + hasIcon: false, + theme: const ExpandableThemeData( + headerAlignment: ExpandablePanelHeaderAlignment.center, + tapBodyToCollapse: true, + ), + header: Padding( + padding: const EdgeInsets.only(top: 20, bottom: 20, left: 21, right: 21), + child: InkWell( + onTap: () { + setState(() { + expandFlag = !expandFlag; + controller.expanded = expandFlag; + }); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + TranslationBase.of(context).description, + maxLines: 1, + style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold, letterSpacing: -1.14), + ), + ], + ), + ), + Icon( + expandFlag ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, + color: Color(0xff2E303A), + ), + ], ), ), - ], - ), - - StarRating( - size: 20, - totalCount: null, - totalAverage: 5, - forceStars: true), - - - SizedBox(height: 20,), - - - Texts( - "Details", - fontWeight: FontWeight.bold, - color: Colors.grey, - fontSize: 20 - ), - - - - AspectRatio( - aspectRatio: 2/1, - child: Container( - color: Colors.grey[300], - child: Padding( - padding: const EdgeInsets.all(10), - child: Texts("Detail of offers written here"), - ) ), + builder: (_, collapsed, expanded) { + return Expandable( + controller: controller, + collapsed: collapsed, + expanded: Container( + padding: const EdgeInsets.only(left: 21.0, right: 21.0, bottom: 21.0), + child: Text(parseHtmlString(widget.itemModel.fullDescription), + style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.textColor), overflow: TextOverflow.clip)), + theme: const ExpandableThemeData(crossFadePoint: 0), + ); + }, ), - - - SizedBox(height: 10,), - ], - ), + ), + ], ), + ), + ), + ), + ], + ), + ), + bottomSheet: Container( + padding: const EdgeInsets.only(top: 16, bottom: 16, left: 21, right: 21), + color: Colors.white, + child: Row( + children: [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if(widget.itemModel.hasDiscountsApplied) Container( + margin: const EdgeInsets.only(top: 0.0), + child: Text(widget.itemModel.oldPrice.toString() + " " + TranslationBase.of(context).sar, + style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.w600, letterSpacing: -0.6, decoration: TextDecoration.lineThrough, color: CustomColors.grey2))), + Container( + margin: const EdgeInsets.only(top: 0.0), + child: Text(widget.itemModel.price.toString().trim() + " " + TranslationBase.of(context).sar, + style: TextStyle(fontSize: 19.0, fontWeight: FontWeight.bold, letterSpacing: -0.56))), ], ), ), - - Padding( - padding: const EdgeInsets.all(10), - child: Align( - alignment: Alignment.bottomRight, - child: Row( - children: [ - - Expanded( - child: RaisedButton.icon( - padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8.0), - side: BorderSide(color: Colors.red, width: 0.5) - ), - color: Colors.red, - icon: Icon( - Icons.add_shopping_cart_outlined, - size: 25, - color: Colors.white, - ), - label: Texts( - "Add to Cart", - fontSize: 17, color: Colors.white, fontWeight: FontWeight.normal, - ), - onPressed: (){},), - ), - - SizedBox(width: 15,), - - Expanded( - child: OutlineButton.icon( - padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0), - borderSide: BorderSide(width: 1.0, color: Colors.red), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8.0), + SizedBox(width: 8), + Expanded( + child: SizedBox( + height: 43, + width: double.infinity, + child: FlatButton( + onPressed: () { + // onCartClick(); + widget.onCartClick(widget.itemModel); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.only(left: 8.0, right: 8.0), + child: SvgPicture.asset("assets/images/new/add-to-cart.svg", color: Colors.white), + ), + Container( + child: Text( + TranslationBase.of(context).addToCart, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white, letterSpacing: -0.48), ), - color: Colors.white, - icon: Icon( - Icons.favorite_rounded, - size: 25, - color: Colors.red, - ), - label: Texts( - "Add to Favorites", - fontSize: 17, color: Colors.red, fontWeight: FontWeight.normal - ), - onPressed: (){ - - },), - ), - - ], + ), + ], + ), + color: const Color(0xffD02127), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6), + ), ), ), - ) - + ), + ], + ), + ), + ), + ); + } + String parseHtmlString(String htmlString) { + var document = parse(htmlString); + String parsedString = parse(document.body.text).documentElement.text; + return parsedString; + } - ], - ) + Widget contactButton(String title) { + return SizedBox( + height: 32, + width: 80.0, + child: FlatButton( + onPressed: () {}, + color: Colors.white, + shape: StadiumBorder(side: BorderSide(color: CustomColors.devider, width: 1)), + child: Text( + title, + style: TextStyle(fontSize: 10, letterSpacing: -0.4, color: CustomColors.textColor), + maxLines: 1, + ), ), ); } } - diff --git a/lib/pages/packages_offers/OfferAndPackagesCartPage.dart b/lib/pages/packages_offers/OfferAndPackagesCartPage.dart index d1219541..e28110a8 100644 --- a/lib/pages/packages_offers/OfferAndPackagesCartPage.dart +++ b/lib/pages/packages_offers/OfferAndPackagesCartPage.dart @@ -32,20 +32,18 @@ class PackagesCartPage extends StatefulWidget { _PackagesCartPageState createState() => _PackagesCartPageState(); } -class _PackagesCartPageState extends State - with AfterLayoutMixin, SingleTickerProviderStateMixin { +class _PackagesCartPageState extends State with AfterLayoutMixin, SingleTickerProviderStateMixin { getLanguageID() async { languageID = await sharedPref.getString(APP_LANGUAGE); } - double subtotal,tax, total; + double subtotal, tax, total; @override void initState() { _agreeTerms = false; _selectedPaymentMethod = null; - _animationController = - AnimationController(vsync: this, duration: Duration(seconds: 500)); + _animationController = AnimationController(vsync: this, duration: Duration(seconds: 500)); super.initState(); } @@ -69,22 +67,13 @@ class _PackagesCartPageState extends State } onPayNowClick() async { - await viewModel.service - .placeOrder( - context: context, - paymentParams: _selectedPaymentParams) - .then((orderId) { + await viewModel.service.placeOrder(context: context, paymentParams: _selectedPaymentParams).then((orderId) { if (orderId.runtimeType == int) { // result == order_id - var browser = MyInAppBrowser( - context: context, - onExitCallback: (data, isDone) => paymentClosed( - orderId: orderId, withStatus: isDone, data: data)); - browser.openPackagesPaymentBrowser( - customer_id: viewModel.service.customer.id, order_id: orderId); + var browser = MyInAppBrowser(context: context, onExitCallback: (data, isDone) => paymentClosed(orderId: orderId, withStatus: isDone, data: data)); + browser.openPackagesPaymentBrowser(customer_id: viewModel.service.customer.id, order_id: orderId); } else { - utils.Utils.showErrorToast( - 'Failed to place order, please try again later'); + utils.Utils.showErrorToast('Failed to place order, please try again later'); } }).catchError((error) { utils.Utils.showErrorToast(error.toString()); @@ -111,56 +100,48 @@ class _PackagesCartPageState extends State isOfferPackages: true, showOfferPackagesCart: false, isShowDecPage: false, + showNewAppBar: true, + showNewAppBarTitle: true, body: Column( children: [ Expanded( - child: Padding( - padding: const EdgeInsets.all(5), - child: StaggeredGridView.countBuilder( - crossAxisCount: (_columnCount * _columnCount), - itemCount: viewModel.cartItemList.length, - itemBuilder: (BuildContext context, int index) { - var item = viewModel.cartItemList[index]; - return Dismissible( - key: Key(index.toString()), - direction: DismissDirection.startToEnd, - background: _cartItemDeleteContainer(), - secondaryBackground: _cartItemDeleteContainer(), - confirmDismiss: (direction) async { - bool status = await viewModel.service - .deleteProductFromCart(item.id, - context: context, showLoading: false); - return status; - }, - onDismissed: (direction) { - debugPrint('Index: $index'); - viewModel.cartItemList.removeAt(index); - }, - child: PackagesCartItemCard( - itemModel: item, - shouldStepperChangeApply: (apply, total) async { - var request = AddProductToCartRequestModel( - product_id: item.productId, - quantity: apply); - ResponseModel response = await viewModel - .service - .addProductToCart(request, - context: context, showLoading: false) - .catchError((error) { - utils.Utils.showErrorToast(error); - }); - if(response.status){ - fetchData(); - } - return response.status ?? false; - }, - )); - }, - staggeredTileBuilder: (int index) => - StaggeredTile.fit(_columnCount), - mainAxisSpacing: 0, - crossAxisSpacing: 10, - )), + child: StaggeredGridView.countBuilder( + crossAxisCount: (_columnCount * _columnCount), + itemCount: viewModel.cartItemList.length, + itemBuilder: (BuildContext context, int index) { + var item = viewModel.cartItemList[index]; + return Dismissible( + key: Key(index.toString()), + direction: DismissDirection.startToEnd, + background: _cartItemDeleteContainer(), + secondaryBackground: _cartItemDeleteContainer(), + confirmDismiss: (direction) async { + bool status = await viewModel.service.deleteProductFromCart(item.id, context: context, showLoading: false); + return status; + }, + onDismissed: (direction) { + viewModel.cartItemList.removeAt(index); + }, + child: PackagesCartItemCard( + itemModel: item, + viewModel: viewModel, + getCartItems: fetchData, + shouldStepperChangeApply: (apply, total) async { + var request = AddProductToCartRequestModel(product_id: item.productId, quantity: apply); + ResponseModel response = await viewModel.service.addProductToCart(request, context: context, showLoading: false).catchError((error) { + utils.Utils.showErrorToast(error); + }); + if (response.status) { + fetchData(); + } + return response.status ?? false; + }, + )); + }, + staggeredTileBuilder: (int index) => StaggeredTile.fit(_columnCount), + mainAxisSpacing: 0, + crossAxisSpacing: 10, + ), ), Container( height: 0.25, @@ -170,8 +151,7 @@ class _PackagesCartPageState extends State color: Colors.white, child: Column( children: [ - Texts(TranslationBase.of(context).selectPaymentOption, - fontSize: 10, fontWeight: FontWeight.bold), + Texts(TranslationBase.of(context).selectPaymentOption, fontSize: 10, fontWeight: FontWeight.bold), Container( height: 0.25, width: 100, @@ -184,11 +164,7 @@ class _PackagesCartPageState extends State height: 0.25, color: Colors.grey[300], ), - Container( - height: 40, - child: _termsAndCondition(context, - onSelected: onTermsClick, - onInfoClick: onTermsInfoClick)), + Container(height: 40, child: _termsAndCondition(context, onSelected: onTermsClick, onInfoClick: onTermsInfoClick)), Container( height: 0.25, color: Colors.grey[300], @@ -204,7 +180,7 @@ class _PackagesCartPageState extends State } fetchData() async { - await viewModel.service.cartItems(context: context).then((value){ + await viewModel.service.cartItems(context: context).then((value) { subtotal = value['subtotal'] ?? 0.0; tax = value['tax'] ?? 0.0; total = value['total'] ?? 0.0; @@ -213,15 +189,12 @@ class _PackagesCartPageState extends State setState(() {}); } - paymentClosed( - {@required int orderId, @required bool withStatus, dynamic data}) async { + paymentClosed({@required int orderId, @required bool withStatus, dynamic data}) async { viewModel.service.getOrderById(orderId, context: context).then((value) { var heading = withStatus ? "Success" : "Failed"; - var title = withStatus ? "Your order has been placed successfully" : "Failed to place your order"; + var title = withStatus ? "Your order has been placed successfully" : "Failed to place your order"; var subTitle = "Order# ${value.data.customOrderNumber}"; - Navigator.of(context).pushReplacement(MaterialPageRoute( - builder: (context) => PackageOrderCompletedPage( - heading: heading, title: title, subTitle: subTitle))); + Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => PackageOrderCompletedPage(heading: heading, title: title, subTitle: subTitle))); }).catchError((error) { debugPrint(error); }); @@ -231,7 +204,8 @@ class _PackagesCartPageState extends State // /* Payment Footer Widgets */ // --------------------------- String _selectedPaymentMethod; -Map _selectedPaymentParams; +Map _selectedPaymentParams; + Widget _paymentOptions(BuildContext context, Function(String) onSelected, {PackagesViewModel viewModel}) { double height = 30; @@ -247,18 +221,17 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa ), ], borderRadius: BorderRadius.all(Radius.circular(5)), - border: Border.all( - color: isSelected ? Colors.green : Colors.grey, - width: isSelected ? 1 : 0.5)), + border: Border.all(color: isSelected ? Colors.green : Colors.grey, width: isSelected ? 1 : 0.5)), child: Padding( padding: const EdgeInsets.all(4), child: Image.asset('assets/images/new-design/$imageName'), )); } - - Future selectTamaraPaymentOption() async{ + + Future selectTamaraPaymentOption() async { final tamara_options = await viewModel.service.getTamaraOptions(context: context, showLoading: true); - final selected = await SingleSelectionDialog(tamara_options, icon: Image.asset('assets/images/new-design/tamara.png'), title: TranslationBase.of(context).tamaraInstPlan).show(context); + final selected = + await SingleSelectionDialog(tamara_options, icon: Image.asset('assets/images/new-design/tamara.png'), title: TranslationBase.of(context).tamaraInstPlan).show(context); return selected.name; } @@ -272,9 +245,9 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa children: [ InkWell( child: buttonContent(_selectedPaymentMethod == "tamara", 'tamara.png'), - onTap: () async{ + onTap: () async { final tamara_option = await selectTamaraPaymentOption(); - _selectedPaymentParams = {"channel" : "Web", "payment_method_system_name" : "Payments.Tamara", "payment_option" : tamara_option}; + _selectedPaymentParams = {"channel": "Web", "payment_method_system_name": "Payments.Tamara", "payment_option": tamara_option}; onSelected("tamara"); }, ), @@ -284,7 +257,7 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa InkWell( child: buttonContent(_selectedPaymentMethod == "mada", 'mada.png'), onTap: () { - _selectedPaymentParams = {"payment_method_system_name" : "Payments.PayFort", "payment_option" : "MADA"}; + _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MADA"}; onSelected("mada"); }, ), @@ -294,7 +267,7 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa InkWell( child: buttonContent(_selectedPaymentMethod == "visa", 'visa.png'), onTap: () { - _selectedPaymentParams = {"payment_method_system_name" : "Payments.PayFort", "payment_option" : "VISA"}; + _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "VISA"}; onSelected("visa"); }, ), @@ -304,7 +277,7 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa InkWell( child: buttonContent(_selectedPaymentMethod == "mastercard", 'mastercard.png'), onTap: () { - _selectedPaymentParams = {"payment_method_system_name" : "Payments.PayFort", "payment_option" : "MASTERCARD"}; + _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MASTERCARD"}; onSelected("mastercard"); }, ), @@ -326,17 +299,15 @@ Widget _paymentOptions(BuildContext context, Function(String) onSelected, {Packa } bool _agreeTerms = false; -Widget _termsAndCondition(BuildContext context, - {@required Function(bool) onSelected, @required VoidCallback onInfoClick}) { + +Widget _termsAndCondition(BuildContext context, {@required Function(bool) onSelected, @required VoidCallback onInfoClick}) { return Padding( padding: const EdgeInsets.all(5), child: Row( children: [ InkWell( child: Icon( - _agreeTerms - ? Icons.check_circle - : Icons.radio_button_unchecked_sharp, + _agreeTerms ? Icons.check_circle : Icons.radio_button_unchecked_sharp, size: 20, color: _agreeTerms ? Colors.green[600] : Colors.grey[400], ), @@ -386,18 +357,8 @@ Widget _payNow(BuildContext context, {double subtotal, double tax, double total, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Texts( - '${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', - heightFactor: 1.5, - fontWeight: FontWeight.bold, - color: Colors.grey, - fontSize: 8), - Texts( - '${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', - heightFactor: 1.5, - fontWeight: FontWeight.bold, - color: Colors.grey, - fontSize: 8), + Texts('${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), + Texts('${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), Padding( padding: const EdgeInsets.all(3), child: Container( @@ -406,12 +367,7 @@ Widget _payNow(BuildContext context, {double subtotal, double tax, double total, color: Colors.grey[300], ), ), - Texts( - '${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', - heightFactor: 1.5, - fontWeight: FontWeight.bold, - color: Colors.black54, - fontSize: 15) + Texts('${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 15) ], ), ), @@ -425,10 +381,7 @@ Widget _payNow(BuildContext context, {double subtotal, double tax, double total, fontWeight: FontWeight.bold, ), padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(5), - side: BorderSide( - color: Theme.of(context).primaryColor, width: 0.5)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5), side: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)), color: Theme.of(context).primaryColor, onPressed: isPayNowAQctive ? onPayNowClick : null, ), diff --git a/lib/pages/packages_offers/OfferAndPackagesPage.dart b/lib/pages/packages_offers/OfferAndPackagesPage.dart index 063cc541..d323b36d 100644 --- a/lib/pages/packages_offers/OfferAndPackagesPage.dart +++ b/lib/pages/packages_offers/OfferAndPackagesPage.dart @@ -12,24 +12,20 @@ import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.da import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/packages_offers/ClinicOfferAndPackagesPage.dart'; -import 'package:diplomaticquarterapp/pages/packages_offers/CreateCustomerDailogPage.dart'; -import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackageDetailPage.dart'; import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackagesCartPage.dart'; import 'package:diplomaticquarterapp/routes.dart'; import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart' as auth; -import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart' as utils; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart'; import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesOfferCard.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter_svg/flutter_svg.dart'; import 'package:provider/provider.dart'; class PackagesHomePage extends StatefulWidget { @@ -48,6 +44,7 @@ class _PackagesHomePageState extends State { void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + viewModel.service.patientUser = widget.user; viewModel.service.loadOffersPackagesDataForMainPage( context: context, completion: () { @@ -111,11 +108,8 @@ class _PackagesHomePageState extends State { body: SingleChildScrollView( child: Column( children: [ - SizedBox( - height: 10, - ), Padding( - padding: const EdgeInsets.all(21), + padding: projectViewModel.isArabic ? const EdgeInsets.only(top: 21, right: 21, bottom: 21) : const EdgeInsets.only(top: 21, left: 21, bottom: 21), child: Column( children: [ inputWidget(TranslationBase.of(context).search, "", _searchTextController, isInputTypeNum: false), @@ -126,6 +120,7 @@ class _PackagesHomePageState extends State { onTap: () => showClinicSelectionList(), child: Container( padding: EdgeInsets.all(12), + margin: projectViewModel.isArabic ? const EdgeInsets.only(left: 21) : const EdgeInsets.only(right: 21), width: double.infinity, height: 65, decoration: BoxDecoration( @@ -139,7 +134,7 @@ class _PackagesHomePageState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - selectedClinic != null ? selectedClinic.name : "Browse offers by clinic", + selectedClinic != null ? selectedClinic.name : TranslationBase.of(context).browseOffers, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, @@ -218,15 +213,16 @@ class _PackagesHomePageState extends State { children: [ Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), - child: Icon( - Icons.add_shopping_cart_rounded, - size: 30.0, - color: Colors.white, - ), + child: SvgPicture.asset("assets/images/new/cart.svg"), + // child: Icon( + // Icons.add_shopping_cart_rounded, + // size: 30.0, + // color: Colors.white, + // ), ), Container( child: Text( - TranslationBase.of(context).shoppingCart, + TranslationBase.of(context).myCart, textAlign: TextAlign.center, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white, letterSpacing: -0.48), ), @@ -315,7 +311,9 @@ class _PackagesHomePageState extends State { Widget separator(BuildContext context, int index) { return Container( width: 1, - decoration: BoxDecoration(gradient: LinearGradient(begin: Alignment(-1.0, -2.0), end: Alignment(1.0, 4.0), colors: [Colors.grey, Colors.grey[100], Colors.grey[200], Colors.grey[300], Colors.grey[400], Colors.grey[500]])), + decoration: BoxDecoration( + gradient: + LinearGradient(begin: Alignment(-1.0, -2.0), end: Alignment(1.0, 4.0), colors: [Colors.grey, Colors.grey[100], Colors.grey[200], Colors.grey[300], Colors.grey[400], Colors.grey[500]])), ); } @@ -346,9 +344,11 @@ class _PackagesHomePageState extends State { } } - Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {VoidCallback suffixTap, bool isEnable = true, bool hasSelection = false, int lines, bool isInputTypeNum = false}) { + Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, + {VoidCallback suffixTap, bool isEnable = true, bool hasSelection = false, int lines, bool isInputTypeNum = false}) { return Container( padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), + margin: projectViewModel.isArabic ? const EdgeInsets.only(left: 21) : const EdgeInsets.only(right: 21), alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), diff --git a/lib/uitl/translations_delegate_base.dart b/lib/uitl/translations_delegate_base.dart index b15f7adb..492eab10 100644 --- a/lib/uitl/translations_delegate_base.dart +++ b/lib/uitl/translations_delegate_base.dart @@ -509,7 +509,7 @@ class TranslationBase { String get switchUser => localizedValues['switch-login'][locale.languageCode]; - String get removeMember => localizedValues['remove-membe'][locale.languageCode]; + String get removeMember => localizedValues['remove-member'][locale.languageCode]; String get allowView => localizedValues['allow-view'][locale.languageCode]; @@ -2618,6 +2618,10 @@ class TranslationBase { String get RRTSubTitle => localizedValues["RRTSubTitle"][locale.languageCode]; String get transportation => localizedValues["transportation"][locale.languageCode]; + + String get browseOffers => localizedValues["browseOffers"][locale.languageCode]; + + String get myCart => localizedValues["myCart"][locale.languageCode]; } class TranslationBaseDelegate extends LocalizationsDelegate { diff --git a/lib/widgets/offers_packages/PackagesCartItemCard.dart b/lib/widgets/offers_packages/PackagesCartItemCard.dart index ddca9d90..10c7e5b1 100644 --- a/lib/widgets/offers_packages/PackagesCartItemCard.dart +++ b/lib/widgets/offers_packages/PackagesCartItemCard.dart @@ -1,217 +1,136 @@ import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCartItemsResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; +import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; +import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; +import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/CounterView.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; - +import 'package:flutter_svg/flutter_svg.dart'; bool wide = true; class PackagesCartItemCard extends StatefulWidget { final PackagesCartItemsResponseModel itemModel; - final StepperCallbackFuture shouldStepperChangeApply ; + final StepperCallbackFuture shouldStepperChangeApply; + final PackagesViewModel viewModel; + final Function getCartItems; - const PackagesCartItemCard( - { - @required this.itemModel, - @required this.shouldStepperChangeApply, - Key key}) - : super(key: key); + const PackagesCartItemCard({@required this.itemModel, @required this.shouldStepperChangeApply, @required this.viewModel, this.getCartItems, Key key}) : super(key: key); @override State createState() => PackagesCartItemCardState(); } class PackagesCartItemCardState extends State { - @override Widget build(BuildContext context) { - wide = !wide; return Container( - color: Colors.transparent, - child: Card( - elevation: 3, - shadowColor: Colors.grey[100], - color: Colors.white, - child: Stack( - children: [ - Container( - height: 100, - child: Row( - children: [ - _image(widget.itemModel.product), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, + decoration: cardRadius(15.0), + margin: EdgeInsets.only(left: 21.0, right: 21.0, top: 12.0), + height: 90, + child: Row( + mainAxisSize: MainAxisSize.max, + children: [ + _image(widget.itemModel.product), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _itemName(widget.itemModel.product.getName()), + _itemDescription(widget.itemModel.product.shortDescription), + Container( + padding: const EdgeInsets.only(top: 12.0), + width: MediaQuery.of(context).size.width * 0.65, + child: Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _itemPrice(widget.itemModel.product.price, context: context), + InkWell( + onTap: () async { + await widget.viewModel.service.deleteProductFromCart(widget.itemModel.id, context: context, showLoading: false); + widget.getCartItems(); + }, + child: Row( children: [ - _itemName(widget.itemModel.product.getName()), - Row( - children: [ - _itemPrice(widget.itemModel.product.price, context: context), - _priceSeperator(), - _itemOldPrice(widget.itemModel.product.oldPrice, context: context), - ], - ), - Row( - children: [ - _itemCounter( - widget.itemModel.quantity, - minQuantity: widget.itemModel.product.orderMinimumQuantity, - maxQuantity: widget.itemModel.product.orderMaximumQuantity, - shouldStepperChangeApply: (apply,total) async{ - bool success = await widget.shouldStepperChangeApply(apply,total); - if(success == true) - setState(() => widget.itemModel.quantity = total); - return success; - } + Padding( + padding: const EdgeInsets.only(left: 5.0, right: 5.0), + child: Text( + TranslationBase.of(context).removeMember, + style: TextStyle( + fontSize: 10, + color: CustomColors.accentColor, + fontWeight: FontWeight.w600, + letterSpacing: -0.36, ), - ], + ), ), + SvgPicture.asset("assets/images/new-design/delete.svg", color: CustomColors.accentColor), ], - ) - ], - ), + ), + ), + ], ), - - // Positioned( - // bottom: 8, - // left: 10, - // child: Row( - // children: [ - // _totalLabel(context: context), - // _totalPrice((widget.itemModel.product.price * widget.itemModel.quantity), context: context), - // ], - // ), - // ) - ], - ) - ) + ), + ], + ) + ], + ), ); } } - -// -------------------- -// Product Image -// -------------------- Widget _image(PackagesResponseModel model) => AspectRatio( - aspectRatio: 1/1, - child: Padding( - padding: const EdgeInsets.all(10), - child: Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.grey[300], width: 0.25), - boxShadow: [ - BoxShadow(color: Colors.grey[200], blurRadius: 2.0, spreadRadius: 1, offset: Offset(1,1.5)) - ], - borderRadius: BorderRadius.circular(8), - color: Colors.white, - shape: BoxShape.rectangle, - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8), - child: (model.images.isNotEmpty) - ? Utils.loadNetworkImage(url: model.images.first.src, fitting:BoxFit.fill) - : Container(color: Colors.grey[200]) + aspectRatio: 1 / 1, + child: Padding( + padding: const EdgeInsets.all(9), + child: Container( + decoration: BoxDecoration( + border: Border.all(color: Colors.grey[300], width: 0.25), + boxShadow: [BoxShadow(color: Colors.grey[200], blurRadius: 2.0, spreadRadius: 1, offset: Offset(1, 1.5))], + borderRadius: BorderRadius.circular(15), + color: Colors.white, + shape: BoxShape.rectangle, + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(15), + child: (model.images.isNotEmpty) ? Utils.loadNetworkImage(url: model.images.first.src, fitting: BoxFit.fill) : Container(color: Colors.grey[200])), + ), ), - ), - ), -); + ); -// -------------------- -// Product Name -// -------------------- Widget _itemName(String name) => Padding( - padding: const EdgeInsets.all(0), - child: Texts( - name, - fontWeight: FontWeight.normal, - color: Colors.black, - fontSize: 15 - ) -); - + padding: const EdgeInsets.only(top: 9.0), + child: Text(name, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + letterSpacing: -0.56, + ))); + +Widget _itemDescription(String desc) => Padding( + padding: const EdgeInsets.only(top: 0.0), + child: Text(desc, + style: TextStyle( + fontSize: 10, + // fontWeight: FontWeight.bold, + letterSpacing: -0.4, + ))); Widget _itemPrice(double price, {@required BuildContext context}) { final prc = (price ?? 0.0).toStringAsFixed(2); return Padding( padding: const EdgeInsets.all(0), - child: Texts( - '${prc} ${TranslationBase.of(context).sar}', - fontWeight: FontWeight.bold, - color: Colors.green, - fontSize: 15 - ) -); -} - - -// -------------------- -// Price Seperator -// -------------------- -Widget _priceSeperator() => Padding( - padding: const EdgeInsets.only(left: 3, right: 3), - child: Container(height: 0.5, width: 5, color: Colors.grey[100],), -); - - -// -------------------- -// Product Price -// -------------------- -Widget _itemOldPrice(double oldPrice, {@required BuildContext context}) { - final prc = (oldPrice ?? 0.0).toStringAsFixed(2); - return Padding( - padding: const EdgeInsets.all(0), - child: Texts( - '${prc} ${TranslationBase.of(context).sar}', - fontWeight: FontWeight.normal, - decoration: TextDecoration.lineThrough, - color: Colors.grey, - fontSize: 10 - ) -); + child: Text( + '${prc} ${TranslationBase.of(context).sar}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + letterSpacing: -0.4, + ), + ), + ); } - -// -------------------- -// Product Price -// -------------------- -Widget _itemCounter(int quantity, {int minQuantity, int maxQuantity, StepperCallbackFuture shouldStepperChangeApply}) => Padding( - padding: const EdgeInsets.all(0), - child: StepperView( - height: 25, - backgroundColor: Colors.grey[300], - foregroundColor: Colors.grey[200], - initialNumber: quantity, - minNumber: minQuantity, - maxNumber: maxQuantity, - counterCallback: shouldStepperChangeApply, - decreaseCallback: (){}, - increaseCallback: (){}, - ) -); - - -Widget _totalLabel({@required BuildContext context}) => Padding( - padding: const EdgeInsets.all(0), - child: Texts( - '${TranslationBase.of(context).totalWithColonRight}', - fontWeight: FontWeight.bold, - color: Colors.grey[600], - fontSize: 13 - ) -); - - -Widget _totalPrice(double totalPrice, {@required BuildContext context}) => Padding( - padding: const EdgeInsets.all(0), - child: Texts( - '${totalPrice.toStringAsFixed(2)} ${TranslationBase.of(context).sar}', - fontWeight: FontWeight.normal, - color: Colors.green, - ) -); - diff --git a/lib/widgets/offers_packages/PackagesOfferCard.dart b/lib/widgets/offers_packages/PackagesOfferCard.dart index 470550c6..be756caf 100644 --- a/lib/widgets/offers_packages/PackagesOfferCard.dart +++ b/lib/widgets/offers_packages/PackagesOfferCard.dart @@ -8,6 +8,7 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/StarRating.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; import 'package:rating_bar/rating_bar.dart'; bool wide = true; @@ -33,7 +34,7 @@ class PackagesItemCardState extends State { wide = !wide; return InkWell( onTap: () { - Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => OfferAndPackagesDetail(itemModel: widget.itemModel))); + Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => OfferAndPackagesDetail(itemModel: widget.itemModel, onCartClick: widget.onCartClick))); }, child: Container( // width: widget.itemWidth, @@ -73,11 +74,7 @@ class PackagesItemCardState extends State { ], ), InkWell( - child: Icon( - Icons.add_shopping_cart_rounded, - size: 30.0, - color: Colors.black, - ), + child: SvgPicture.asset("assets/images/new/add-to-cart.svg"), onTap: () { widget.onCartClick(widget.itemModel); }, @@ -89,80 +86,5 @@ class PackagesItemCardState extends State { ), ), ); - // Stack( - // children: [ - // Column( - // mainAxisSize: MainAxisSize.max, - // children: [ - // AspectRatio( - // aspectRatio:1 / 1, - // child: applyShadow( - // child: ClipRRect( - // borderRadius: BorderRadius.circular(10), - // child: Utils.loadNetworkImage( - // url: imageUrl(), - // )), - // )), - // Texts( - // widget.itemModel.getName(), - // fontWeight: FontWeight.normal, - // color: Colors.black, - // fontSize: 15 - // ), - // Padding( - // padding: const EdgeInsets.only(left: 10, right: 10), - // child: Row( - // crossAxisAlignment: CrossAxisAlignment.end, - // mainAxisSize: MainAxisSize.max, - // children: [ - // Stack( - // children: [ - // Texts( - // '${widget.itemModel.oldPrice} ${'SAR'}', - // fontWeight: FontWeight.normal, - // decoration: TextDecoration.lineThrough, - // color: Colors.grey, - // fontSize: 12 - // ), - // Padding( - // padding: const EdgeInsets.only(top: 8), - // child: Texts( - // '${widget.itemModel.price} ${'SAR'}', - // fontWeight: FontWeight.bold, - // color: Colors.green, - // fontSize: 18 - // ), - // ), - // Padding( - // padding: const EdgeInsets.only(top: 35), - // child: StarRating( - // size: 15, - // totalCount: null, - // totalAverage: widget.itemModel.approvedRatingSum.toDouble(), - // forceStars: true), - // ) - // ], - // ), - // Spacer( - // flex: 1, - // ), - // InkWell( - // child: Icon( - // Icons.add_shopping_cart_rounded, - // size: 30.0, - // color: Colors.grey, - // ), - // onTap: () { - // widget.onCartClick(widget.itemModel); - // }, - // ), - // ], - // ), - // ), - // ], - // ), - // ], - // ), - // ); } } From d2834bb3dde06a649b186ff39304b5d221717c0d Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 8 Nov 2021 18:30:05 +0300 Subject: [PATCH 5/8] Health calculator fixes --- .../bmi_calculator/bmi_calculator.dart | 16 +-- .../bmi_calculator/result_page.dart | 124 +++++++++++++----- .../bmr_calculator/bmr_calculator.dart | 30 ++--- .../bmr_calculator/bmr_result_page.dart | 50 +++---- .../health_calculator/body_fat/body_fat.dart | 10 +- .../calorie_calculator.dart | 20 +-- .../calorie_result_page.dart | 21 +-- .../ideal_body/ideal_body.dart | 11 +- 8 files changed, 137 insertions(+), 145 deletions(-) diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart index c06d77db..86382fe7 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart @@ -99,23 +99,9 @@ class _BMICalculatorState extends State { return AppScaffold( isShowAppBar: true, isShowDecPage: false, - showHomeAppBarIcon: false, + showHomeAppBarIcon: true, showNewAppBar: true, showNewAppBarTitle: true, - appBarIcons: [ - IconButton( - icon: Icon(Icons.info_outline), - color: Colors.black, - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => HealthDescPage("${TranslationBase.of(context).bmi} ${TranslationBase.of(context).calcHealth}", TranslationBase.of(context).bmiCalcDesc, - "assets/images/AlHabibMedicalService/health_calculator/bmi.png")), - ); - }, - ) - ], appBarTitle: "${TranslationBase.of(context).bmi} ${TranslationBase.of(context).calcHealth}", body: Column( children: [ diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart index 68126b4d..81fba296 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart @@ -1,49 +1,58 @@ +import 'dart:collection'; + import 'package:auto_size_text/auto_size_text.dart'; -import 'package:diplomaticquarterapp/config/size_config.dart'; +import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart'; import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bariatrics-screen.dart'; +import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart'; +import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart'; import 'package:diplomaticquarterapp/theme/colors.dart'; +import 'package:diplomaticquarterapp/uitl/app_toast.dart'; +import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/borderedButton.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; -import 'package:percent_indicator/percent_indicator.dart'; -class ResultPage extends StatelessWidget { +class ResultPage extends StatefulWidget { final double finalResult; final String textResult; final String msg; ResultPage({this.finalResult, this.textResult, this.msg}); + @override + _ResultPageState createState() => _ResultPageState(); +} + +class _ResultPageState extends State { Color inductorColor; + double percent; Color colorInductor() { - if (finalResult >= 30) { + if (widget.finalResult >= 30) { inductorColor = Color(0xffC70D00); - } else if (finalResult < 30 && finalResult >= 25) { + } else if (widget.finalResult < 30 && widget.finalResult >= 25) { inductorColor = Color(0xffC25400); - } else if (finalResult < 25 && finalResult >= 18.5) { + } else if (widget.finalResult < 25 && widget.finalResult >= 18.5) { inductorColor = Color(0xff36D600); - } else if (finalResult < 18.5) { + } else if (widget.finalResult < 18.5) { inductorColor = Color(0xff1BE0EE); } return inductorColor; } double percentInductor() { - if (finalResult >= 30) { + if (widget.finalResult >= 30) { percent = 1.0; - } else if (finalResult < 30 && finalResult >= 25) { + } else if (widget.finalResult < 30 && widget.finalResult >= 25) { percent = 0.73; - } else if (finalResult < 25 && finalResult >= 18.5) { + } else if (widget.finalResult < 25 && widget.finalResult >= 18.5) { percent = 0.5; - } else if (finalResult < 18.5) { + } else if (widget.finalResult < 18.5) { percent = 0.25; } return percent; @@ -69,7 +78,7 @@ class ResultPage extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Text( - TranslationBase.of(context).bodyMassIndex + finalResult.toString(), + TranslationBase.of(context).bodyMassIndex + widget.finalResult.toString(), style: TextStyle( fontSize: 16, letterSpacing: -0.64, @@ -81,21 +90,21 @@ class ResultPage extends StatelessWidget { height: MediaQuery.of(context).size.width / 2.8, child: Row( children: [ - showMass(context, TranslationBase.of(context).underWeight, "< 18.5", finalResult <= 18.5 ? Colors.red : Colors.black, 8), + showMass(context, TranslationBase.of(context).underWeight, "< 18.5", widget.finalResult <= 18.5 ? Colors.red : Colors.black, 8), mWidth(12), - showMass(context, TranslationBase.of(context).healthy, "18.5 - 24.9", (finalResult > 18.5 && finalResult < 25) ? Colors.red : Colors.black, 6), + showMass(context, TranslationBase.of(context).healthy, "18.5 - 24.9", (widget.finalResult > 18.5 && widget.finalResult < 25) ? Colors.red : Colors.black, 6), mWidth(12), - showMass(context, TranslationBase.of(context).overWeight, "25 - 29.9", (finalResult >= 25 && finalResult < 30) ? Colors.red : Colors.black, 4), + showMass(context, TranslationBase.of(context).overWeight, "25 - 29.9", (widget.finalResult >= 25 && widget.finalResult < 30) ? Colors.red : Colors.black, 4), mWidth(12), - showMass(context, TranslationBase.of(context).obese, "30 - 34.9", (finalResult >= 30 && finalResult < 35) ? Colors.red : Colors.black, 2), + showMass(context, TranslationBase.of(context).obese, "30 - 34.9", (widget.finalResult >= 30 && widget.finalResult < 35) ? Colors.red : Colors.black, 2), mWidth(12), - showMass(context, TranslationBase.of(context).extremeObese, "> 35", (finalResult >= 35) ? Colors.red : Colors.black, 0), + showMass(context, TranslationBase.of(context).extremeObese, "> 35", (widget.finalResult >= 35) ? Colors.red : Colors.black, 0), ], ), ), mHeight(20), Text( - textResult, + widget.textResult, style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.w600, @@ -104,7 +113,7 @@ class ResultPage extends StatelessWidget { ), mHeight(4), Text( - msg, + widget.msg, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.textColor), ), ], @@ -115,14 +124,10 @@ class ResultPage extends StatelessWidget { Container( color: Colors.white, padding: EdgeInsets.all(16), - child: SecondaryButton( - label: TranslationBase.of(context).seeListOfDoctor, - color: CustomColors.accentColor, - onTap: () { - Navigator.push( - context, - FadePage(page: BariatricsPage(1, 1, finalResult)), - ); + child: DefaultButton( + TranslationBase.of(context).seeListOfDoctor, + () { + callDoctorsSearchAPI(); }, ), ), @@ -131,6 +136,65 @@ class ResultPage extends StatelessWidget { ); } + callDoctorsSearchAPI() { + GifLoaderDialogUtils.showMyDialog(context); + List doctorsList = []; + List arr = []; + List arrDistance = []; + List result; + int numAll; + List _patientDoctorAppointmentListHospital = List(); + + DoctorsListService service = new DoctorsListService(); + service.getDoctorsList(108, 0, false, context).then((res) { + GifLoaderDialogUtils.hideDialog(context); + if (res['MessageStatus'] == 1) { + setState(() { + if (res['DoctorList'].length != 0) { + doctorsList.clear(); + res['DoctorList'].forEach((v) { + doctorsList.add(new DoctorList.fromJson(v)); + }); + doctorsList.forEach((element) { + List doctorByHospital = _patientDoctorAppointmentListHospital + .where( + (elementClinic) => elementClinic.filterName == element.projectName, + ) + .toList(); + + if (doctorByHospital.length != 0) { + _patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList.add(element); + } else { + _patientDoctorAppointmentListHospital + .add(PatientDoctorAppointmentList(filterName: element.projectName, distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element)); + } + }); + } else {} + }); + + result = LinkedHashSet.from(arr).toList(); + numAll = result.length; + navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital); + } else { + AppToast.showErrorToast(message: res['ErrorEndUserMessage']); + } + }).catchError((err) { + GifLoaderDialogUtils.hideDialog(context); + print(err); + AppToast.showErrorToast(message: err); + }); + } + + Future navigateToSearchResults(context, List docList, List patientDoctorAppointmentListHospital) async { + Navigator.push(context, FadePage(page: SearchResults(isLiveCareAppointment: false, doctorsList: docList, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital))) + .then((value) { + setState(() { + // dropdownValue = null; + }); + // getProjectsList(); + }); + } + Widget showMass(BuildContext context, String title, String weight, Color color, int f) { return Expanded( flex: 1, diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart index 3512b4de..a2d96d89 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart @@ -2,8 +2,7 @@ import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -148,16 +147,7 @@ class _BmrCalculatorState extends State { showNewAppBarTitle: true, showNewAppBar: true, appBarTitle: TranslationBase.of(context).bmr, - showHomeAppBarIcon: false, - appBarIcons: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0), - child: Icon( - Icons.info_outline, - color: Colors.white, - ), - ) - ], + showHomeAppBarIcon: true, body: Container( height: double.infinity, width: double.infinity, @@ -406,22 +396,20 @@ class _BmrCalculatorState extends State { Container( margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), color: Colors.white, - child: SecondaryButton( - label: TranslationBase.of(context).calculate, - color: CustomColors.accentColor, - onTap: () { + child: DefaultButton( + TranslationBase.of(context).calculate, + () { setState(() { calculateBmr(); calculateCalories(); - { Navigator.push( context, FadePage( page: BmrResultPage( - bmrResult: bmrResult, - calories: calories, - )), + bmrResult: bmrResult, + calories: calories, + )), ); } }); @@ -661,5 +649,3 @@ class CommonDropDownView extends StatelessWidget { ); } } - - diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_result_page.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_result_page.dart index 53426f94..aee77829 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_result_page.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_result_page.dart @@ -5,9 +5,7 @@ import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/button.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -26,6 +24,7 @@ class BmrResultPage extends StatelessWidget { isShowDecPage: false, showNewAppBarTitle: true, showNewAppBar: true, + showHomeAppBarIcon: true, appBarTitle: TranslationBase.of(context).bmr, body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -80,31 +79,23 @@ class BmrResultPage extends StatelessWidget { ), mHeight(20), Text( - 'This means the body will burn ( ${bmrResult.toStringAsFixed(1)} ) calories each day, if engaged in no activity for the entire day.. Note: Daily calorie requirement is ( ${calories.toStringAsFixed(1)} ) calories, to maintain the current weight.', - style: TextStyle( - fontSize: 14, - letterSpacing: -0.56, - fontWeight: FontWeight.w600, - color: CustomColors.textColor - ), + 'This means the body will burn (${bmrResult.toStringAsFixed(1)}) calories each day, if engaged in no activity for the entire day.. Note: Daily calorie requirement is (${calories.toStringAsFixed(1)}) calories, to maintain the current weight.', + style: TextStyle(fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600, color: CustomColors.textColor), ), ], ).withBorderedContainer, ), mFlex(1), - Container( margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), color: Colors.white, - child: SecondaryButton( - label: TranslationBase.of(context).viewDocList, - color: CustomColors.accentColor, - onTap: () { + child: DefaultButton( + TranslationBase.of(context).viewDocList, + () { getDoctorsList(context); }, ), ), - ], ), ); @@ -163,18 +154,19 @@ class BmrResultPage extends StatelessWidget { }); } } + extension BorderedContainer on Widget { Widget get withBorderedContainer => Container( - padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(15), - color: Colors.white, - border: Border.all( - color: Color(0xffefefef), - width: 1, - ), - ), - child: this, - ); -} \ No newline at end of file + padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(15), + color: Colors.white, + border: Border.all( + color: Color(0xffefefef), + width: 1, + ), + ), + child: this, + ); +} diff --git a/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart b/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart index 1442afbd..22f915b0 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart @@ -227,16 +227,8 @@ class _BodyFatState extends State { isShowDecPage: false, showNewAppBarTitle: true, showNewAppBar: true, + showHomeAppBarIcon: true, appBarTitle: TranslationBase.of(context).bodyFatTitle, - appBarIcons: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0), - child: Icon( - Icons.info_outline, - color: Colors.white, - ), - ) - ], body: Column( children: [ Expanded( diff --git a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart index 74db1a30..2052e58f 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart @@ -2,8 +2,8 @@ import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -85,16 +85,8 @@ class _CalorieCalculatorState extends State { isShowDecPage: false, showNewAppBar: true, showNewAppBarTitle: true, + showHomeAppBarIcon: true, appBarTitle: "${TranslationBase.of(context).calories} ${TranslationBase.of(context).calcHealth}", - appBarIcons: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0), - child: Icon( - Icons.info_outline, - color: Colors.black, - ), - ) - ], body: Column( children: [ Expanded( @@ -261,7 +253,6 @@ class _CalorieCalculatorState extends State { SizedBox( height: 12.0, ), - InkWell( onTap: () { // dropdownKey.currentState; @@ -337,10 +328,9 @@ class _CalorieCalculatorState extends State { Container( margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), color: Colors.white, - child: SecondaryButton( - label: TranslationBase.of(context).calculate, - color: CustomColors.accentColor, - onTap: () { + child: DefaultButton( + TranslationBase.of(context).calculate, + () { setState(() { calculateCalories(); print(calories); diff --git a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart index dc27e051..ec19a91e 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart @@ -5,9 +5,7 @@ import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/button.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -75,18 +73,13 @@ class CalorieResultPage extends StatelessWidget { ], ), progressColor: CustomColors.accentColor, - backgroundColor: Colors.white, + backgroundColor: CustomColors.darkGreyColor, ), ), mHeight(20), Text( 'Daily intake is ${calorie.toStringAsFixed(1)} calories', - style: TextStyle( - fontSize: 14, - letterSpacing: -0.56, - fontWeight: FontWeight.w600, - color: CustomColors.textColor - ), + style: TextStyle(fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600, color: CustomColors.textColor), ), ], ).withBorderedContainer, @@ -95,15 +88,13 @@ class CalorieResultPage extends StatelessWidget { Container( margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), color: Colors.white, - child: SecondaryButton( - label: TranslationBase.of(context).viewDocList, - color: CustomColors.accentColor, - onTap: () { + child: DefaultButton( + TranslationBase.of(context).viewDocList, + () { getDoctorsList(context); }, ), ), - ], ), ); diff --git a/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart b/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart index e414f028..7e4e3b4f 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart @@ -84,16 +84,7 @@ class _IdealBodyState extends State { showNewAppBarTitle: true, showNewAppBar: true, appBarTitle: TranslationBase.of(context).idealBody, - showHomeAppBarIcon: false, - appBarIcons: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0), - child: Icon( - Icons.info_outline, - color: Colors.white, - ), - ) - ], + showHomeAppBarIcon: true, body: Column( children: [ Expanded( From 90b821a37d14d2fbf9e827851364da5afd625996 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 9 Nov 2021 12:43:36 +0300 Subject: [PATCH 6/8] Offers & packages UI completed --- lib/core/service/client/base_app_client.dart | 3 +- .../PackagesOffersServices.dart | 197 +++--- .../PackagesOffersViewModel.dart | 2 + .../BillAmount.dart | 7 - .../OfferAndPackagesCartPage.dart | 565 +++++++++--------- 5 files changed, 373 insertions(+), 401 deletions(-) diff --git a/lib/core/service/client/base_app_client.dart b/lib/core/service/client/base_app_client.dart index 206c45c6..23558ed1 100644 --- a/lib/core/service/client/base_app_client.dart +++ b/lib/core/service/client/base_app_client.dart @@ -481,7 +481,7 @@ class BaseAppClient { simplePost( String fullUrl, { - Map body, + Map body, Map headers, Function(dynamic response, int statusCode) onSuccess, Function(String error, int statusCode) onFailure, @@ -496,7 +496,6 @@ class BaseAppClient { body: json.encode(body), headers: headers, ); - final int statusCode = response.statusCode; print("statusCode :$statusCode"); if (await handleUnauthorized(statusCode, forUrl: fullUrl)) simplePost(fullUrl, onFailure: onFailure, onSuccess: onSuccess, body: body, headers: headers); diff --git a/lib/core/service/packages_offers/PackagesOffersServices.dart b/lib/core/service/packages_offers/PackagesOffersServices.dart index 238cb611..ae5396a7 100644 --- a/lib/core/service/packages_offers/PackagesOffersServices.dart +++ b/lib/core/service/packages_offers/PackagesOffersServices.dart @@ -4,6 +4,7 @@ import 'dart:developer'; import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/model/ResponseModel.dart'; +import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/CreateCustomerRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart'; @@ -15,13 +16,11 @@ import 'package:diplomaticquarterapp/core/model/packages_offers/responses/Packag import 'package:diplomaticquarterapp/core/model/packages_offers/responses/order_response_model.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/tamara_payment_option.dart'; import 'package:diplomaticquarterapp/core/service/base_service.dart'; -import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; -import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:flutter/cupertino.dart'; -var packagesAuthHeader = {'Authorization': ''}; +Map packagesAuthHeader = {}; class OffersAndPackagesServices extends BaseService { AuthenticatedUser patientUser; @@ -32,64 +31,52 @@ class OffersAndPackagesServices extends BaseService { List bestSellerList = List(); List bannersList = List(); List cartItemList = List(); + List _hospitals = List(); + List get hospitals => _hospitals; String cartItemCount = ""; PackagesCustomerResponseModel customer; - Future> getAllCategories( - OffersCategoriesRequestModel request) async { + Future> getAllCategories(OffersCategoriesRequestModel request) async { Future errorThrow; var url = EXA_CART_API_BASE_URL + PACKAGES_CATEGORIES; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['categories'].forEach((json) { categoryList.add(PackagesCategoriesResponseModel().fromJson(json)); }); } - }, - onFailure: (String error, int statusCode) {}, - queryParams: request.toFlatMap()); + }, onFailure: (String error, int statusCode) {}, queryParams: request.toFlatMap()); return categoryList; } - Future> getAllProducts( - {@required OffersProductsRequestModel request, - @required BuildContext context, - @required bool showLoading = true}) async { + Future> getAllProducts({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { Future errorThrow; request.sinceId = (productList.isNotEmpty) ? productList.last.id : 0; productList = List(); var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { productList.add(PackagesResponseModel().fromJson(json)); }); } - }, - onFailure: (String error, int statusCode) {}, - queryParams: request.toFlatMap()); + }, onFailure: (String error, int statusCode) {}, queryParams: request.toFlatMap()); return productList; } - Future> getTamaraOptions( - {@required BuildContext context, - @required bool showLoading = true}) async { - if (tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty) - return tamaraPaymentOptions; + Future> getTamaraOptions({@required BuildContext context, @required bool showLoading = true}) async { + if (tamaraPaymentOptions != null && tamaraPaymentOptions.isNotEmpty) return tamaraPaymentOptions; var url = EXA_CART_API_BASE_URL + PACKAGES_TAMARA_OPT; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['payment_option'].forEach((json) { @@ -103,14 +90,10 @@ class OffersAndPackagesServices extends BaseService { return tamaraPaymentOptions; } - Future> getLatestOffers( - {@required OffersProductsRequestModel request, - @required BuildContext context, - @required bool showLoading = true}) async { + Future> getLatestOffers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { - latestOffersList.clear(); + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + latestOffersList.clear(); if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -124,14 +107,10 @@ class OffersAndPackagesServices extends BaseService { return latestOffersList; } - Future> getBestSellers( - {@required OffersProductsRequestModel request, - @required BuildContext context, - @required bool showLoading = true}) async { + Future> getBestSellers({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { - bestSellerList.clear(); + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { + bestSellerList.clear(); if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -145,13 +124,9 @@ class OffersAndPackagesServices extends BaseService { return bestSellerList; } - Future> getBanners( - {@required OffersProductsRequestModel request, - @required BuildContext context, - @required bool showLoading = true}) async { + Future> getBanners({@required OffersProductsRequestModel request, @required BuildContext context, @required bool showLoading = true}) async { var url = EXA_CART_API_BASE_URL + PACKAGES_PRODUCTS; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { if (statusCode == 200) { var jsonResponse = json.decode(stringResponse); jsonResponse['products'].forEach((json) { @@ -165,10 +140,7 @@ class OffersAndPackagesServices extends BaseService { return bannersList; } - Future loadOffersPackagesDataForMainPage( - {@required BuildContext context, - bool showLoading = true, - Function completion}) async { + Future loadOffersPackagesDataForMainPage({@required BuildContext context, bool showLoading = true, Function completion}) async { var finished = 0; var totalCalls = 2; @@ -190,30 +162,20 @@ class OffersAndPackagesServices extends BaseService { // Check and Create Customer if (patientUser != null) { - customer = - await getCurrentCustomer(context: context, showLoading: showLoading); + customer = await getCurrentCustomer(context: context, showLoading: showLoading); if (customer == null) { - createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), - context: context); + createCustomer(PackagesCustomerRequestModel.fromUser(patientUser), context: context); } } // Performing Parallel Request on same time // # 1 - getBestSellers( - request: OffersProductsRequestModel(), - context: context, - showLoading: false) - .then((value) { + getBestSellers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value) { completedAll(); }); // # 2 - getLatestOffers( - request: OffersProductsRequestModel(), - context: context, - showLoading: false) - .then((value) { + getLatestOffers(request: OffersProductsRequestModel(), context: context, showLoading: false).then((value) { completedAll(); }); @@ -230,10 +192,7 @@ class OffersAndPackagesServices extends BaseService { // -------------------- // Create Customer // -------------------- - Future createCustomer(PackagesCustomerRequestModel request, - {@required BuildContext context, - bool showLoading = true, - Function(bool) completion}) async { + Future createCustomer(PackagesCustomerRequestModel request, {@required BuildContext context, bool showLoading = true, Function(bool) completion}) async { if (customer != null) return Future.value(customer); customer = null; @@ -241,9 +200,7 @@ class OffersAndPackagesServices extends BaseService { _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER; - await baseAppClient - .simplePost(url, headers: packagesAuthHeader, body: request.json(), - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) { var jsonResponse = json.decode(stringResponse); var customerJson = jsonResponse['customers'].first; customer = PackagesCustomerResponseModel.fromJson(customerJson); @@ -258,16 +215,12 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? customer; } - Future getCurrentCustomer( - {@required BuildContext context, bool showLoading = true}) async { + Future getCurrentCustomer({@required BuildContext context, bool showLoading = true}) async { if (customer != null) return Future.value(customer); _showLoading(context, showLoading); - var url = EXA_CART_API_BASE_URL + - PACKAGES_CUSTOMER + - "/username/${patientUser.patientID}"; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + var url = EXA_CART_API_BASE_URL + PACKAGES_CUSTOMER + "/username/${patientUser.patientID}"; + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { var jsonResponse = json.decode(stringResponse); var customerJson = jsonResponse['customers'].first; customer = PackagesCustomerResponseModel.fromJson(customerJson); @@ -282,17 +235,14 @@ class OffersAndPackagesServices extends BaseService { // -------------------- // Shopping Cart // -------------------- - Future> cartItems( - {@required BuildContext context, bool showLoading = true}) async { + Future> cartItems({@required BuildContext context, bool showLoading = true}) async { Future errorThrow; cartItemList.clear(); _showLoading(context, showLoading); - var url = - EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}'; + var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/${customer.id}'; Map jsonResponse; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); jsonResponse = json.decode(stringResponse); @@ -308,10 +258,7 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? jsonResponse; } - Future> addProductToCart( - AddProductToCartRequestModel request, - {@required BuildContext context, - bool showLoading = true}) async { + Future> addProductToCart(AddProductToCartRequestModel request, {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; ResponseModel response; @@ -319,38 +266,27 @@ class OffersAndPackagesServices extends BaseService { _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART; - await baseAppClient - .simplePost(url, headers: packagesAuthHeader, body: request.json(), - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); var jsonCartItem = jsonResponse["shopping_carts"][0]; - response = ResponseModel( - status: true, - data: PackagesCartItemsResponseModel.fromJson(jsonCartItem), - error: null); + response = ResponseModel(status: true, data: PackagesCartItemsResponseModel.fromJson(jsonCartItem), error: null); cartItemCount = (jsonResponse['count'] ?? 0).toString(); }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); - errorThrow = - Future.error(ResponseModel(status: true, data: null, error: error)); + errorThrow = Future.error(ResponseModel(status: true, data: null, error: error)); }); return errorThrow ?? response; } - Future updateProductToCart(int cartItemID, - {UpdateProductToCartRequestModel request, - @required BuildContext context, - bool showLoading = true}) async { + Future updateProductToCart(int cartItemID, {UpdateProductToCartRequestModel request, @required BuildContext context, bool showLoading = true}) async { Future errorThrow; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; - await baseAppClient - .simplePut(url, headers: packagesAuthHeader, body: request.json(), - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simplePut(url, headers: packagesAuthHeader, body: request.json(), onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); @@ -363,16 +299,13 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? bannersList; } - Future deleteProductFromCart(int cartItemID, - {@required BuildContext context, bool showLoading = true}) async { + Future deleteProductFromCart(int cartItemID, {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_SHOPPING_CART + '/$cartItemID'; - await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleDelete(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); - // var jsonResponse = json.decode(stringResponse); }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); log(error); @@ -385,28 +318,23 @@ class OffersAndPackagesServices extends BaseService { // -------------------- // Place Order // -------------------- - Future placeOrder( - {@required Map paymentParams, - @required BuildContext context, - bool showLoading = true}) async { + Future placeOrder({@required Map paymentParams, @required int projectID, @required BuildContext context, bool showLoading = true}) async { Future errorThrow; Map jsonBody = { "customer_id": customer.id, - "billing_address": { - "email": patientUser.emailAddress, - "phone_number": patientUser.mobileNumber - }, + "project_id": projectID, + "billing_address": {"email": patientUser.emailAddress, "phone_number": patientUser.mobileNumber}, }; jsonBody.addAll(paymentParams); jsonBody = {'order': jsonBody}; + print(jsonBody); + int order_id; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS; - await baseAppClient.simplePost(url, - headers: packagesAuthHeader, - body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simplePost(url, headers: packagesAuthHeader, body: jsonBody, onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); @@ -420,21 +348,18 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? order_id; } - Future> getOrderById(int id, - {@required BuildContext context, bool showLoading = true}) async { + Future> getOrderById(int id, {@required BuildContext context, bool showLoading = true}) async { Future errorThrow; ResponseModel response; _showLoading(context, showLoading); var url = EXA_CART_API_BASE_URL + PACKAGES_ORDERS + '/$id'; - await baseAppClient.simpleGet(url, headers: packagesAuthHeader, - onSuccess: (dynamic stringResponse, int statusCode) { + await baseAppClient.simpleGet(url, headers: packagesAuthHeader, onSuccess: (dynamic stringResponse, int statusCode) { _hideLoading(context, showLoading); var jsonResponse = json.decode(stringResponse); var jsonOrder = jsonResponse['orders'][0]; - response = ResponseModel( - status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder)); + response = ResponseModel(status: true, data: PackagesOrderResponseModel.fromJson(jsonOrder)); }, onFailure: (String error, int statusCode) { _hideLoading(context, showLoading); errorThrow = Future.error(ResponseModel(status: false, error: error)); @@ -442,6 +367,26 @@ class OffersAndPackagesServices extends BaseService { return errorThrow ?? response; } + + Future getHospitals({bool isResBasedOnLoc = true}) async { + Map body = Map(); + body['Latitude'] = await this.sharedPref.getDouble(USER_LAT); + body['Longitude'] = await this.sharedPref.getDouble(USER_LONG); + body['IsOnlineCheckIn'] = isResBasedOnLoc; + body['PatientOutSA'] = 0; + + await baseAppClient.post(GET_PROJECT, + onSuccess: (dynamic response, int statusCode) { + _hospitals.clear(); + response['ListProject'].forEach((hospital) { + _hospitals.add(HospitalsModel.fromJson(hospital)); + }); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }, body: body); + } + } _showLoading(BuildContext context, bool flag) { diff --git a/lib/core/viewModels/packages_offers/PackagesOffersViewModel.dart b/lib/core/viewModels/packages_offers/PackagesOffersViewModel.dart index 1b68e9d7..af750eab 100644 --- a/lib/core/viewModels/packages_offers/PackagesOffersViewModel.dart +++ b/lib/core/viewModels/packages_offers/PackagesOffersViewModel.dart @@ -1,3 +1,4 @@ +import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCartItemsResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCategoriesResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart'; @@ -22,6 +23,7 @@ class PackagesViewModel extends BaseViewModel { List get bestSellerList => service.bestSellerList; List get bannersList => service.bannersList; List get cartItemList => service.cartItemList; + List get hospitals => service.hospitals; String _cartItemCount = ""; diff --git a/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart b/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart index e571e4e8..bacc9c38 100644 --- a/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart +++ b/lib/pages/ErService/AmbulanceRequestIndexPages/BillAmount.dart @@ -59,13 +59,6 @@ class _BillAmountState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Text(TranslationBase.of(context).testFee, - // style: TextStyle( - // color: Colors.black, - // fontSize: 16.0, - // fontWeight: FontWeight.w600, - // letterSpacing: -0.64, - // )), Container( width: double.infinity, padding: EdgeInsets.only(top: 10, bottom: 3), diff --git a/lib/pages/packages_offers/OfferAndPackagesCartPage.dart b/lib/pages/packages_offers/OfferAndPackagesCartPage.dart index e28110a8..4b42774b 100644 --- a/lib/pages/packages_offers/OfferAndPackagesCartPage.dart +++ b/lib/pages/packages_offers/OfferAndPackagesCartPage.dart @@ -1,19 +1,23 @@ import 'package:after_layout/after_layout.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/model/ResponseModel.dart'; +import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart'; import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart'; -import 'package:diplomaticquarterapp/core/model/packages_offers/responses/tamara_payment_option.dart'; import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart'; +import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart'; import 'package:diplomaticquarterapp/pages/base/base_view.dart'; import 'package:diplomaticquarterapp/pages/packages_offers/PackageOrderCompletedPage.dart'; import 'package:diplomaticquarterapp/pages/pharmacies/screens/pharmacy-terms-conditions-page.dart'; +import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart' as utils; +import 'package:diplomaticquarterapp/uitl/utils_new.dart'; +import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; +import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart'; import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart'; import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesCartItemCard.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; -import 'package:diplomaticquarterapp/widgets/single_selection_dialog.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -22,6 +26,9 @@ import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; dynamic languageID; const _columnCount = 1; +bool _agreeTerms = false; +String _selectedPaymentMethod; +Map _selectedPaymentParams; AnimationController _animationController; @@ -38,6 +45,8 @@ class _PackagesCartPageState extends State with AfterLayoutMix } double subtotal, tax, total; + int _selectedHospitalIndex = -1; + HospitalsModel _selectedHospital; @override void initState() { @@ -67,9 +76,8 @@ class _PackagesCartPageState extends State with AfterLayoutMix } onPayNowClick() async { - await viewModel.service.placeOrder(context: context, paymentParams: _selectedPaymentParams).then((orderId) { + await viewModel.service.placeOrder(context: context, projectID: _selectedHospital.iD, paymentParams: _selectedPaymentParams).then((orderId) { if (orderId.runtimeType == int) { - // result == order_id var browser = MyInAppBrowser(context: context, onExitCallback: (data, isDone) => paymentClosed(orderId: orderId, withStatus: isDone, data: data)); browser.openPackagesPaymentBrowser(customer_id: viewModel.service.customer.id, order_id: orderId); } else { @@ -83,100 +91,248 @@ class _PackagesCartPageState extends State with AfterLayoutMix @override void afterFirstLayout(BuildContext context) { fetchData(); + viewModel.service.getHospitals(); } @override Widget build(BuildContext context) { return BaseView( - allowAny: true, - onModelReady: (model) => viewModel = model, - builder: (_, model, wi) { - return AppScaffold( - appBarTitle: TranslationBase.of(context).offerAndPackages, - isShowAppBar: true, - isPharmacy: false, - showPharmacyCart: false, - showHomeAppBarIcon: false, - isOfferPackages: true, - showOfferPackagesCart: false, - isShowDecPage: false, - showNewAppBar: true, - showNewAppBarTitle: true, - body: Column( - children: [ - Expanded( - child: StaggeredGridView.countBuilder( - crossAxisCount: (_columnCount * _columnCount), - itemCount: viewModel.cartItemList.length, - itemBuilder: (BuildContext context, int index) { - var item = viewModel.cartItemList[index]; - return Dismissible( - key: Key(index.toString()), - direction: DismissDirection.startToEnd, - background: _cartItemDeleteContainer(), - secondaryBackground: _cartItemDeleteContainer(), - confirmDismiss: (direction) async { - bool status = await viewModel.service.deleteProductFromCart(item.id, context: context, showLoading: false); - return status; - }, - onDismissed: (direction) { - viewModel.cartItemList.removeAt(index); - }, - child: PackagesCartItemCard( - itemModel: item, - viewModel: viewModel, - getCartItems: fetchData, - shouldStepperChangeApply: (apply, total) async { - var request = AddProductToCartRequestModel(product_id: item.productId, quantity: apply); - ResponseModel response = await viewModel.service.addProductToCart(request, context: context, showLoading: false).catchError((error) { - utils.Utils.showErrorToast(error); - }); - if (response.status) { - fetchData(); - } - return response.status ?? false; - }, - )); - }, - staggeredTileBuilder: (int index) => StaggeredTile.fit(_columnCount), - mainAxisSpacing: 0, - crossAxisSpacing: 10, - ), - ), - Container( - height: 0.25, - color: Theme.of(context).primaryColor, - ), - Container( + allowAny: true, + onModelReady: (model) => viewModel = model, + builder: (_, model, wi) { + return AppScaffold( + appBarTitle: TranslationBase.of(context).offerAndPackages, + isShowAppBar: true, + isPharmacy: false, + showPharmacyCart: false, + showHomeAppBarIcon: false, + isOfferPackages: true, + showOfferPackagesCart: false, + isShowDecPage: false, + showNewAppBar: true, + showNewAppBarTitle: true, + body: viewModel.cartItemList.length > 0 + ? Column( + children: [ + Expanded( + child: StaggeredGridView.countBuilder( + crossAxisCount: (_columnCount * _columnCount), + itemCount: viewModel.cartItemList.length, + itemBuilder: (BuildContext context, int index) { + var item = viewModel.cartItemList[index]; + return Dismissible( + key: Key(index.toString()), + direction: DismissDirection.startToEnd, + background: _cartItemDeleteContainer(), + secondaryBackground: _cartItemDeleteContainer(), + confirmDismiss: (direction) async { + bool status = await viewModel.service.deleteProductFromCart(item.id, context: context, showLoading: false); + return status; + }, + onDismissed: (direction) { + viewModel.cartItemList.removeAt(index); + }, + child: PackagesCartItemCard( + itemModel: item, + viewModel: viewModel, + getCartItems: fetchData, + shouldStepperChangeApply: (apply, total) async { + var request = AddProductToCartRequestModel(product_id: item.productId, quantity: apply); + ResponseModel response = await viewModel.service.addProductToCart(request, context: context, showLoading: false).catchError((error) { + utils.Utils.showErrorToast(error); + }); + if (response.status) { + fetchData(); + } + return response.status ?? false; + }, + )); + }, + staggeredTileBuilder: (int index) => StaggeredTile.fit(_columnCount), + mainAxisSpacing: 0, + crossAxisSpacing: 10, + ), + ), + Container( + height: 0.25, + color: Theme.of(context).primaryColor, + ), + ], + ) + : getNoDataWidget(context), + bottomSheet: viewModel.cartItemList.length > 0 + ? Container( + padding: EdgeInsets.all(21.0), + width: double.infinity, color: Colors.white, child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - Texts(TranslationBase.of(context).selectPaymentOption, fontSize: 10, fontWeight: FontWeight.bold), Container( - height: 0.25, - width: 100, - color: Colors.grey[300], + margin: EdgeInsets.only(bottom: 12.0), + child: InkWell( + onTap: () => confirmSelectHospitalDialog(model.hospitals), + child: Container( + padding: EdgeInsets.all(12), + width: double.infinity, + height: 50, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), border: Border.all(color: CustomColors.devider), color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + getHospitalName(), + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + letterSpacing: -0.46, + ), + ), + Icon(Icons.arrow_drop_down), + ], + ), + ), + ), + ), + Container( + margin: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0), + child: Text(TranslationBase.of(context).YouCanPayByTheFollowingOptions, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600)), + ), + Container( + width: MediaQuery.of(context).size.width * 0.75, + margin: EdgeInsets.fromLTRB(0.0, 8.0, 20.0, 5.0), + child: getPaymentMethods(), + ), + Container( + margin: EdgeInsets.only(top: 14.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + SizedBox( + height: 24.0, + width: 24.0, + child: Checkbox( + value: _agreeTerms, + onChanged: (v) { + setState(() => _agreeTerms = v); + }), + ), + Expanded( + child: Text( + TranslationBase.of(context).iAcceptTermsConditions, + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: CustomColors.textColor, letterSpacing: -0.48), + ), + ), + ], + ), ), - _paymentOptions(context, (paymentMethod) { - setState(() => _selectedPaymentMethod = paymentMethod); - }, viewModel: viewModel), Container( - height: 0.25, - color: Colors.grey[300], + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: double.infinity, + padding: EdgeInsets.only(top: 12, bottom: 3), + child: Row( + children: [ + Expanded( + child: _getNormalText(TranslationBase.of(context).patientShareToDo), + ), + Expanded( + child: _getNormalText(TranslationBase.of(context).sar + " " + (subtotal ?? 0.0).toStringAsFixed(2), isBold: true), + ) + ], + ), + ), + mDivider(Colors.grey[200]), + Container( + width: double.infinity, + padding: EdgeInsets.only(top: 3, bottom: 3), + child: Row( + children: [ + Expanded( + child: _getNormalText(TranslationBase.of(context).patientTaxToDo), + ), + Expanded( + child: _getNormalText(TranslationBase.of(context).sar + ' ' + (tax ?? 0.0).toStringAsFixed(2), isBold: true), + ) + ], + ), + ), + mDivider(Colors.grey[200]), + Container( + width: double.infinity, + padding: EdgeInsets.only(top: 3, bottom: 3), + child: Row( + children: [ + Expanded( + child: _getNormalText(TranslationBase.of(context).patientShareTotalToDo), + ), + Expanded( + child: _getNormalText(TranslationBase.of(context).sar + ' ' + (total ?? 0.0).toStringAsFixed(2), isBold: true, isTotal: true), + ) + ], + ), + ), + ], + ), ), - Container(height: 40, child: _termsAndCondition(context, onSelected: onTermsClick, onInfoClick: onTermsInfoClick)), Container( - height: 0.25, - color: Colors.grey[300], + padding: EdgeInsets.only(top: 21, bottom: 21), + child: DefaultButton( + TranslationBase.of(context).payNow, + (_agreeTerms && _selectedHospital != null) + ? () { + Navigator.push(context, FadePage(page: PaymentMethod(onSelectedMethod: (String metohd) { + setState(() {}); + }))).then((value) { + print(value); + if (value != null) { + _selectedPaymentMethod = value; + _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": value}; + onPayNowClick(); + } + }); + } + : null, + color: CustomColors.green, + disabledColor: CustomColors.grey2, + ), ), - _payNow(context, subtotal: subtotal, tax: tax, total: total, onPayNowClick: onPayNowClick) ], ), ) - ], - ), - ); - }); + : SizedBox(), + ); + }, + ); + } + + void confirmSelectHospitalDialog(List hospitals) { + List list = [ + for (int i = 0; i < hospitals.length; i++) RadioSelectionDialogModel(hospitals[i].name + ' ${hospitals[i].distanceInKilometers} ' + TranslationBase.of(context).km, i), + ]; + showDialog( + context: context, + child: RadioSelectionDialog( + listData: list, + selectedIndex: _selectedHospitalIndex, + isScrollable: true, + onValueSelected: (index) { + _selectedHospitalIndex = index; + _selectedHospital = hospitals[index]; + setState(() {}); + }, + ), + ); + } + + String getHospitalName() { + if (_selectedHospital != null) + return _selectedHospital.name; + else + return TranslationBase.of(context).selectHospital; } fetchData() async { @@ -201,196 +357,73 @@ class _PackagesCartPageState extends State with AfterLayoutMix } } -// /* Payment Footer Widgets */ -// --------------------------- -String _selectedPaymentMethod; -Map _selectedPaymentParams; +// Widget _payNow(BuildContext context, {double subtotal, double tax, double total, @required VoidCallback onPayNowClick}) { +// bool isPayNowAQctive = (_agreeTerms && (_selectedPaymentMethod != null)); +// +// String _subtotal = (subtotal ?? 0.0).toStringAsFixed(2); +// String _tax = (tax ?? 0.0).toStringAsFixed(2); +// String _total = (total ?? 0).toStringAsFixed(2); +// +// return Padding( +// padding: const EdgeInsets.all(5), +// child: Container( +// child: Row( +// crossAxisAlignment: CrossAxisAlignment.end, +// children: [ +// Padding( +// padding: const EdgeInsets.all(5), +// child: Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// children: [ +// Texts('${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), +// Texts('${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), +// Padding( +// padding: const EdgeInsets.all(3), +// child: Container( +// height: 0.25, +// width: 120, +// color: Colors.grey[300], +// ), +// ), +// Texts('${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 15) +// ], +// ), +// ), +// Expanded(child: Container()), +// RaisedButton( +// elevation: 0, +// child: Texts( +// TranslationBase.of(context).payNow, +// fontSize: 15, +// color: Colors.white, +// fontWeight: FontWeight.bold, +// ), +// padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0), +// shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5), side: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)), +// color: Theme.of(context).primaryColor, +// onPressed: isPayNowAQctive ? onPayNowClick : null, +// ), +// ], +// )), +// ); +// } -Widget _paymentOptions(BuildContext context, Function(String) onSelected, {PackagesViewModel viewModel}) { - double height = 30; - - Widget buttonContent(bool isSelected, String imageName) { - return Container( - decoration: BoxDecoration( - color: Colors.white, - boxShadow: [ - BoxShadow( - color: isSelected ? Colors.green[50] : Colors.grey[200], - blurRadius: 1, - spreadRadius: 2, - ), - ], - borderRadius: BorderRadius.all(Radius.circular(5)), - border: Border.all(color: isSelected ? Colors.green : Colors.grey, width: isSelected ? 1 : 0.5)), - child: Padding( - padding: const EdgeInsets.all(4), - child: Image.asset('assets/images/new-design/$imageName'), - )); - } - - Future selectTamaraPaymentOption() async { - final tamara_options = await viewModel.service.getTamaraOptions(context: context, showLoading: true); - final selected = - await SingleSelectionDialog(tamara_options, icon: Image.asset('assets/images/new-design/tamara.png'), title: TranslationBase.of(context).tamaraInstPlan).show(context); - return selected.name; - } - - return Padding( - padding: const EdgeInsets.all(5), - child: Container( - height: height, - color: Colors.transparent, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - InkWell( - child: buttonContent(_selectedPaymentMethod == "tamara", 'tamara.png'), - onTap: () async { - final tamara_option = await selectTamaraPaymentOption(); - _selectedPaymentParams = {"channel": "Web", "payment_method_system_name": "Payments.Tamara", "payment_option": tamara_option}; - onSelected("tamara"); - }, - ), - SizedBox( - width: 5, - ), - InkWell( - child: buttonContent(_selectedPaymentMethod == "mada", 'mada.png'), - onTap: () { - _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MADA"}; - onSelected("mada"); - }, - ), - SizedBox( - width: 5, - ), - InkWell( - child: buttonContent(_selectedPaymentMethod == "visa", 'visa.png'), - onTap: () { - _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "VISA"}; - onSelected("visa"); - }, - ), - SizedBox( - width: 5, - ), - InkWell( - child: buttonContent(_selectedPaymentMethod == "mastercard", 'mastercard.png'), - onTap: () { - _selectedPaymentParams = {"payment_method_system_name": "Payments.PayFort", "payment_option": "MASTERCARD"}; - onSelected("mastercard"); - }, - ), - // SizedBox( - // width: 5, - // ), - // InkWell( - // child: buttonContent( - // _selectedPaymentMethod == "installment", 'installment.png'), - // onTap: () { - // _selectedPaymentParams = {"payment_method_system_name" : "Payments.PayFort", "payment_option" : "INSTALLMENT"}; - // onSelected("installment"); - // }, - // ), - ], - ), +_getNormalText(text, {bool isBold = false, bool isTotal = false}) { + return Text( + text, + style: TextStyle( + fontSize: isBold + ? isTotal + ? 16 + : 12 + : 10, + letterSpacing: -0.5, + color: isBold ? Colors.black : Colors.grey[700], + fontWeight: FontWeight.w600, ), ); } -bool _agreeTerms = false; - -Widget _termsAndCondition(BuildContext context, {@required Function(bool) onSelected, @required VoidCallback onInfoClick}) { - return Padding( - padding: const EdgeInsets.all(5), - child: Row( - children: [ - InkWell( - child: Icon( - _agreeTerms ? Icons.check_circle : Icons.radio_button_unchecked_sharp, - size: 20, - color: _agreeTerms ? Colors.green[600] : Colors.grey[400], - ), - onTap: () { - onSelected(!_agreeTerms); - }, - ), - Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: Texts( - TranslationBase.of(context).pharmacyServiceTermsCondition, - fontWeight: FontWeight.normal, - fontSize: 13, - ), - )), - InkWell( - child: Icon( - Icons.info, - size: 20, - color: Colors.grey[600], - ), - onTap: () { - onInfoClick(); - }, - ), - ], - ), - ); -} - -Widget _payNow(BuildContext context, {double subtotal, double tax, double total, @required VoidCallback onPayNowClick}) { - bool isPayNowAQctive = (_agreeTerms && (_selectedPaymentMethod != null)); - - String _subtotal = (subtotal ?? 0.0).toStringAsFixed(2); - String _tax = (tax ?? 0.0).toStringAsFixed(2); - String _total = (total ?? 0).toStringAsFixed(2); - - return Padding( - padding: const EdgeInsets.all(5), - child: Container( - child: Row( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Padding( - padding: const EdgeInsets.all(5), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Texts('${TranslationBase.of(context).subtotal}: $_subtotal ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), - Texts('${TranslationBase.of(context).vat}: $_tax ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 8), - Padding( - padding: const EdgeInsets.all(3), - child: Container( - height: 0.25, - width: 120, - color: Colors.grey[300], - ), - ), - Texts('${TranslationBase.of(context).total}: $_total ${TranslationBase.of(context).sar}', heightFactor: 1.5, fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 15) - ], - ), - ), - Expanded(child: Container()), - RaisedButton( - elevation: 0, - child: Texts( - TranslationBase.of(context).payNow, - fontSize: 15, - color: Colors.white, - fontWeight: FontWeight.bold, - ), - padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5), side: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)), - color: Theme.of(context).primaryColor, - onPressed: isPayNowAQctive ? onPayNowClick : null, - ), - ], - )), - ); -} -// ------------------- - Widget _cartItemDeleteContainer() { _animationController.duration = Duration(milliseconds: 500); _animationController.repeat(reverse: true); From 75989bdc0191e76e5bc09f691a9c1032e7364788 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 9 Nov 2021 14:06:44 +0300 Subject: [PATCH 7/8] Health Calculators translations --- lib/config/localized_values.dart | 31 +++++- .../bmi_calculator/bmi_calculator.dart | 9 +- .../bmi_calculator/result_page.dart | 2 +- .../bmr_calculator/bmr_calculator.dart | 23 ++-- .../health_calculator/body_fat/body_fat.dart | 104 ++++++++---------- .../calorie_calculator.dart | 12 +- .../calorie_result_page.dart | 7 +- .../health_calculator/carbs/carbs.dart | 33 +++--- .../ideal_body/ideal_body.dart | 30 ++--- lib/uitl/translations_delegate_base.dart | 64 +++++++++++ 10 files changed, 204 insertions(+), 111 deletions(-) diff --git a/lib/config/localized_values.dart b/lib/config/localized_values.dart index ff719027..46f010bd 100644 --- a/lib/config/localized_values.dart +++ b/lib/config/localized_values.dart @@ -1631,11 +1631,40 @@ const Map localizedValues = { "RRTTitle": {"en": "RRT", "ar": "خدمة فريق"}, "RRTSubTitle": {"en": "Service", "ar": "الاستجابة السريع"}, "transportation": {"en": "Transportation", "ar": "النقل"}, - "neck": {"en": "Neck", "ar": "رقبه"}, "waist": {"en": "Waist", "ar": "وسط"}, "hip": {"en": "Hip", "ar": "ورك او نتوء"}, "carbsProtin": {"en": "Carbs, Protein and Fat", "ar": "الكربوهيدرات والبروتينات والدهون"}, "myCart": {"en": "Cart", "ar": "عربة التسوق"}, "browseOffers": {"en": "Browse offers by clinic", "ar": "تصفح العروض حسب العيادة"}, + "inactiveAct":{"en":"Almost inactive (little or no exercise)","ar":"غير نشط تقريبا (ممارسة الرياضة قليلة أو منعدمة)"}, + "light":{"en":"Lightly active (1-3) days per week","ar":"خفيف النشاط (1-3 أيام في الأسبوع)"}, + "moderate":{"en":"Moderately active (3-5) days per week)","ar":"معتدل النشاط (3-5 أيام في الأسبوع)"}, + "very":{"en":"Very active (6-7) days per week)","ar":"نشط جداُ (6-7 أيام في الأسبوع)"}, + "super":{"en":"Super active (very hard exercise)","ar":"عالي النشاط (ممارسة الرياضة الصعبة)"}, + "resultCalories": {"en": "Daily intake is (#) calories", "ar": "الإحتياج اليومي (#) سعرة حرارية"}, + "bmrDesc": {"en": "Calculates the amount of energy that the person’s body expends in a day", "ar": "معدل الأيض القاعدي: هو حساب كمية الطاقة التي يحتاجها الجسم في اليوم الواحد"}, + "idealWeightDesc": {"en": "Calculates the ideal body weight based on height, Weight, and Body Size", "ar": "حساب الوزن المثالي والوزن الصحي للجسم على أساس الطول، والوزن ،والجسم"}, + "bodyFrame": {"en": "Body Frame Size", "ar": "مقاس هيكل الجسم"}, + "bodyFrameSmall": {"en": "Small (fingers overlap)", "ar": "رفيع (الأصابع تتداخل)"}, + "bodyFrameMedium": {"en": "Medium (fingers touch)", "ar": "متوسط (الأصابع تتلامس)"}, + "bodyFrameLarge": {"en": "Large (fingers don't touch)", "ar": "عريض (الأصابع لا تتلامس)"}, + "bodyFatDesc": {"en": "Estimates the total body fat based on the size", "ar": "حساب الدهون في الجسم بناءاً على الحجم"}, + "essential":{"en":"The category falls under Essential Fat.","ar":"تندرج تحت فئة دهون أساسية"}, + "athlete":{"en":" The category falls under Athlete.","ar":"تندرج تحت فئة دهون جسم رياضي"}, + "fitness":{"en":" The category falls under Fitness.","ar":"تندرج تحت فئة دهون جسم صحي"}, + "acceptable":{"en":"The category falls under Acceptable","ar":"تندرج تحت فئة دهون مقبولة"}, + "obeseBodyFat":{"en":"The category falls under Obese.","ar":"تندرج تحت فئة دهون جسم سمين"}, + "invalid":{"en":"Invalid input for calculation.","ar":"البيانات المدخلة غير صالحة للحساب"}, + "more":{"en":"Please check the value you have entered, since the body fat percentage has crossed the limits.","ar":"يرجى التحقق من القيمة التي أدخلتها ، نظرًا لأن نسبة الدهون في الجسم قد تجاوزت الحدود"}, + "less":{"en":"Please check the value you have entered, since the body fat percentage cannot be this low.","ar":"يرجى التحقق من القيمة التي أدخلتها ، نظرًا لأن نسبة الدهون في الجسم لا يمكن أن تكون منخفضة"}, + "carbProteinDesc": {"en": "Calculates carbohydrate protein and fat ratio in calories and grams according to a pre-set ratio", "ar": "حساب نسب الكربوهيدرات و البروتينات و الدهون بالسعرات الحرارية والغرامات وفقا لنسب محددة مسبقا"}, + "calDay": {"en": "Calories Per Day", "ar": "السعرات الحرارية في اليوم الواحد"}, + "notSure": {"en": "Not sure? click here", "ar": "غير متأكد؟ اضغط هنا"}, + "selectDiet": {"en": "Select Diet Type", "ar": "حدد نوع النظام الغذائي"}, + "dietVeryLow":{"en":"Very Low Carb","ar":"حمية منخفضة جدا في الكربوهيدرات"}, + "dietLow":{"en":"Low Carb","ar":"حمية منخفضة الكربوهيدرات"}, + "dietModerate":{"en":"Moderate Carb","ar":"حمية معتدلة الكربوهيدرات"}, + "dietUSDA":{"en":"USDA Guidelines","ar":"ارشادات وزارة الزراعة الأمريكية"}, + "dietZone":{"en":"Zone Diet","ar":"حمية زون"}, }; diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart index 86382fe7..08b756ee 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/bmi_calculator.dart @@ -4,13 +4,11 @@ import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../health_calc_desc.dart'; import 'result_page.dart'; const activeCardColor = Color(0xff70777A); @@ -47,9 +45,10 @@ class _BMICalculatorState extends State { } double calculateBMI() { - if (_isHeightCM) { - convertToCm(_heightValue.toDouble()); - } + if (!_isHeightCM) _heightValue = convertToCm(_heightValue.toDouble()); + + if (!_isWeightKG) _weightValue = convertToKg(_weightValue); + bmiResult = _weightValue / pow(_heightValue / 100, 2); return bmiResult; diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart index 81fba296..fa12a9fe 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmi_calculator/result_page.dart @@ -78,7 +78,7 @@ class _ResultPageState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - TranslationBase.of(context).bodyMassIndex + widget.finalResult.toString(), + TranslationBase.of(context).bodyMassIndex + widget.finalResult.toStringAsFixed(2), style: TextStyle( fontSize: 16, letterSpacing: -0.64, diff --git a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart index a2d96d89..974cd748 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/bmr_calculator/bmr_calculator.dart @@ -48,7 +48,7 @@ class _BmrCalculatorState extends State { // int height = 0; // int weight = 0; double bmrResult = 0; - String dropdownValue = 'Lighty Active (1-3) days per week'; + String dropdownValue = ''; double calories = 0; void updateColor(int type) { @@ -122,13 +122,13 @@ class _BmrCalculatorState extends State { } void calculateCalories() { - if (dropdownValue == "Almost Inactive(Little or no exercises)") { + if (dropdownValue == TranslationBase.of(context).inactiveAct) { calories = bmrResult * 1.2; - } else if (dropdownValue == "Lighty Active (1-3) days per week") { + } else if (dropdownValue == TranslationBase.of(context).light) { calories = bmrResult * 1.375; - } else if (dropdownValue == "very Active(6-7) days per week") { + } else if (dropdownValue == TranslationBase.of(context).very) { calories = bmrResult * 1.55; - } else if (dropdownValue == "Super Active(very hard exercises)") { + } else if (dropdownValue == TranslationBase.of(context).superAct) { calories = bmrResult * 1.725; } else if (dropdownValue == "") { calories = bmrResult * 10.725; @@ -137,6 +137,7 @@ class _BmrCalculatorState extends State { @override Widget build(BuildContext context) { + dropdownValue = TranslationBase.of(context).light; ProjectViewModel projectViewModel = Provider.of(context); _weightPopupList = [PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)]; _heightPopupList = [PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)]; @@ -161,7 +162,7 @@ class _BmrCalculatorState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - 'Calculates the amount of energy that the person’s body expends in a day', + TranslationBase.of(context).bmrDesc, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, @@ -362,14 +363,14 @@ class _BmrCalculatorState extends State { }); }, items: [ - 'Almost Inactive(Little or no exercises)', - 'Lighty Active (1-3) days per week', - 'very Active(6-7) days per week', - 'Super Active(very hard exercises)' + TranslationBase.of(context).inactiveAct, + TranslationBase.of(context).light, + TranslationBase.of(context).very, + TranslationBase.of(context).superAct, ].map>((String value) { return DropdownMenuItem( value: value, - child: Text(value), + child: Text(value, style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)), ); }).toList(), ), diff --git a/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart b/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart index 22f915b0..a7bdbe0e 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/body_fat/body_fat.dart @@ -4,7 +4,6 @@ import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -23,7 +22,6 @@ class BodyFat extends StatefulWidget { } class _BodyFatState extends State { - final GlobalKey clinicDropdownKey = GlobalKey(); bool _isHeightCM = true; bool _isNeckKG = true; @@ -34,7 +32,6 @@ class _BodyFatState extends State { double _waistValue = 0; double _hipValue = 0; - TextEditingController _heightController = new TextEditingController(); TextEditingController _neckController = TextEditingController(); TextEditingController _waistController = TextEditingController(); @@ -45,12 +42,12 @@ class _BodyFatState extends State { List _waistPopupList = List(); List _hipPopupList = List(); - - bool isMale = false; + // bool isHeightCm = true; Color maleCard = activeCardColorGender; Color femaleCard = inactiveCardColorGender; + // Color neckCmCard = activeCardColor; // Color neckFtCard = inactiveCardColor; Color waistCmCard = activeCardColor; @@ -59,6 +56,7 @@ class _BodyFatState extends State { Color hipFtCard = inactiveCardColor; Color cmCard = activeCardColor; Color ftCard = inactiveCardColor; + // int neck = 10; // int heightCm = 0; // int heightFt = 0; @@ -67,6 +65,7 @@ class _BodyFatState extends State { double minRange; double maxRange; double overWeightBy; + // int waist = 5; double bodyFat = 0; double fat = 0; @@ -74,8 +73,6 @@ class _BodyFatState extends State { double calories = 0; String textResult = ''; - - @override void initState() { _neckController.text = _neckValue.toString(); @@ -105,8 +102,6 @@ class _BodyFatState extends State { } } - - void updateColorWaist(int type) { //MG/DLT card if (type == 1) { @@ -183,33 +178,33 @@ class _BodyFatState extends State { void showTextResult() { if (isMale == false) { if (bodyFat > 9 && bodyFat <= 13) { - textResult = 'The category falls under essential'; + textResult = TranslationBase.of(context).essential; } else if (bodyFat > 13 && bodyFat <= 20) { - textResult = 'The category falls under athlete'; + textResult = TranslationBase.of(context).athlete; } else if (bodyFat > 20 && bodyFat <= 24) { - textResult = 'The category falls under fitness'; + textResult = TranslationBase.of(context).fitness; } else if (bodyFat > 24 && bodyFat <= 31) { - textResult = 'The category falls under acceptable'; + textResult = TranslationBase.of(context).acceptable; } else if (bodyFat > 31 && bodyFat <= 60) { - textResult = 'The category falls under obese'; + textResult = TranslationBase.of(context).obeseBodyFat; } else if (bodyFat > 60) { - textResult = 'Please check the value you have entered, since the body fat percentage has crosed the limits.'; + textResult = TranslationBase.of(context).more; } else if (bodyFat <= 9) { - textResult = 'Please check the value you have entered, since the body fat percentage cannot be this low.'; + textResult = TranslationBase.of(context).less; } } else { if (bodyFat > 5 && fat <= 13) { - textResult = 'The category falls under essential'; + textResult = TranslationBase.of(context).essential; } else if (bodyFat > 13 && bodyFat <= 17) { - textResult = 'The category falls under athlete'; + textResult = TranslationBase.of(context).athlete; } else if (bodyFat > 17 && bodyFat <= 24) { - textResult = 'The category falls under fitness'; + textResult = TranslationBase.of(context).fitness; } else if (bodyFat > 24 && bodyFat <= 45) { - textResult = 'The category falls under obese'; + textResult = TranslationBase.of(context).obeseBodyFat; } else if (bodyFat > 45) { - textResult = 'Please check the value you have entered, since the body fat percentage has crosed the limits.'; + textResult = TranslationBase.of(context).more; } else if (bodyFat <= 5) { - textResult = 'Please check the value you have entered, since the body fat percentage cannot be this low.'; + textResult = TranslationBase.of(context).less; } } } @@ -234,12 +229,12 @@ class _BodyFatState extends State { Expanded( child: SingleChildScrollView( child: Container( - padding: EdgeInsets.all(20), + padding: EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - 'Estimates the total body fat based on\nthe size', + TranslationBase.of(context).bodyFatDesc, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, @@ -346,14 +341,14 @@ class _BodyFatState extends State { 1, 270, _heightValue, - (text) { + (text) { _heightController.text = text; }, - (value) { + (value) { _heightValue = value; }, _isHeightCM ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, - (value) { + (value) { if (_isHeightCM != value) { setState(() { _isHeightCM = value; @@ -371,14 +366,14 @@ class _BodyFatState extends State { 1, 270, _neckValue, - (text) { - _neckController.text = text; + (text) { + _neckController.text = text; }, - (value) { - _neckValue = value; + (value) { + _neckValue = value; }, _isNeckKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, - (value) { + (value) { if (_isNeckKG != value) { setState(() { _isNeckKG = value; @@ -387,7 +382,6 @@ class _BodyFatState extends State { }, _neckPopupList, ), - SizedBox( height: 12.0, ), @@ -397,14 +391,14 @@ class _BodyFatState extends State { 1, 270, _waistValue, - (text) { - _waistController.text = text; + (text) { + _waistController.text = text; }, - (value) { + (value) { _waistValue = value; }, _isWaistKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, - (value) { + (value) { if (_isWaistKG != value) { setState(() { _isWaistKG = value; @@ -422,14 +416,14 @@ class _BodyFatState extends State { 1, 270, _hipValue, - (text) { + (text) { _hipController.text = text; }, - (value) { + (value) { _hipValue = value; }, _isHipKG ? TranslationBase.of(context).cm : TranslationBase.of(context).ft, - (value) { + (value) { if (_isHipKG != value) { setState(() { _isHipKG = value; @@ -438,7 +432,6 @@ class _BodyFatState extends State { }, _hipPopupList, ), - SizedBox( height: 12.0, ), @@ -463,10 +456,10 @@ class _BodyFatState extends State { context, FadePage( page: FatResult( - bodyFat: bodyFat, - fat: fat, - textResult: textResult, - )), + bodyFat: bodyFat, + fat: fat, + textResult: textResult, + )), ); } }); @@ -477,6 +470,7 @@ class _BodyFatState extends State { ), ); } + Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String prefix, bool isEnable = true, bool hasSelection = false}) { return Container( padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15), @@ -534,15 +528,15 @@ class _BodyFatState extends State { prefixIcon: prefix == null ? null : Text( - "+" + prefix, - style: TextStyle( - fontSize: 14, - height: 21 / 14, - fontWeight: FontWeight.w500, - color: Color(0xff2E303A), - letterSpacing: -0.56, - ), - ), + "+" + prefix, + style: TextStyle( + fontSize: 14, + height: 21 / 14, + fontWeight: FontWeight.w500, + color: Color(0xff2E303A), + letterSpacing: -0.56, + ), + ), contentPadding: EdgeInsets.zero, border: InputBorder.none, focusedBorder: InputBorder.none, @@ -683,5 +677,3 @@ class CommonDropDownView extends StatelessWidget { ); } } - - diff --git a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart index 2052e58f..b47ca233 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart @@ -3,7 +3,6 @@ import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; @@ -296,14 +295,15 @@ class _CalorieCalculatorState extends State { }); }, items: [ - 'Almost Inactive(Little or no exercises)', - 'Lighty Active (1-3) days per week', - 'very Active(6-7) days per week', - 'Super Active(very hard exercises)' + TranslationBase.of(context).inactiveAct, + TranslationBase.of(context).light, + TranslationBase.of(context).very, + TranslationBase.of(context).superAct, ].map>((String value) { return DropdownMenuItem( value: value, - child: Text(value), + child: Text(value, + style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)), ); }).toList(), ), diff --git a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart index ec19a91e..9202fdc2 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_result_page.dart @@ -35,7 +35,7 @@ class CalorieResultPage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Calories", + TranslationBase.of(context).calories, style: TextStyle( fontSize: 19, letterSpacing: -1.34, @@ -63,7 +63,7 @@ class CalorieResultPage extends StatelessWidget { height: 5.0, ), Text( - 'Calories', + TranslationBase.of(context).calories, style: TextStyle( fontSize: 18, letterSpacing: -1.08, @@ -78,7 +78,8 @@ class CalorieResultPage extends StatelessWidget { ), mHeight(20), Text( - 'Daily intake is ${calorie.toStringAsFixed(1)} calories', + TranslationBase.of(context).resultCalories.replaceAll("(#)", calorie.toStringAsFixed(1)), + // 'Daily intake is ${calorie.toStringAsFixed(1)} calories', style: TextStyle(fontSize: 14, letterSpacing: -0.56, fontWeight: FontWeight.w600, color: CustomColors.textColor), ), ], diff --git a/lib/pages/AlHabibMedicalService/health_calculator/carbs/carbs.dart b/lib/pages/AlHabibMedicalService/health_calculator/carbs/carbs.dart index fa8e2bc5..31990a6b 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/carbs/carbs.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/carbs/carbs.dart @@ -1,13 +1,13 @@ +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/health_calculator/calorie_calculator/calorie_calculator.dart'; import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; -import 'package:diplomaticquarterapp/widgets/buttons/button.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; import 'carbs_result_page.dart'; @@ -38,27 +38,27 @@ class _CarbsState extends State { double fCalMeal; void calculateDietRatios() { - if (dropdownValue == 'Very Low Carb') { + if (dropdownValue == TranslationBase.of(context).dietVeryLow) { meals = 3; protein = 45; carbs = 10; fat = 45; - } else if (dropdownValue == 'Low Carb') { + } else if (dropdownValue == TranslationBase.of(context).dietLow) { meals = 3; protein = 40; carbs = 30; fat = 30; - } else if (dropdownValue == 'Moderate Carb') { + } else if (dropdownValue == TranslationBase.of(context).dietModerate) { meals = 3; protein = 25; carbs = 50; fat = 25; - } else if (dropdownValue == 'USDA Gudilines') { + } else if (dropdownValue == TranslationBase.of(context).dietUSDA) { meals = 3; protein = 15; carbs = 55; fat = 30; - } else if (dropdownValue == 'Zone Diet') { + } else if (dropdownValue == TranslationBase.of(context).dietZone) { meals = 3; protein = 30; carbs = 40; @@ -82,6 +82,7 @@ class _CarbsState extends State { @override Widget build(BuildContext context) { + ProjectViewModel projectViewModel = Provider.of(context); return AppScaffold( isShowAppBar: true, isShowDecPage: false, @@ -107,7 +108,7 @@ class _CarbsState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - 'Calculates carbohydrate protein and fat ratio in calories and grams according to a pre-set ratio', + TranslationBase.of(context).carbProteinDesc, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, @@ -122,7 +123,7 @@ class _CarbsState extends State { mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ - inputWidget("The Calories per day", "0", textController), + inputWidget(TranslationBase.of(context).calDay, "0", textController), InkWell( onTap: () { Navigator.push( @@ -133,7 +134,7 @@ class _CarbsState extends State { child: Padding( padding: const EdgeInsets.all(12.0), child: Text( - 'NOT SURE? CLICK HERE', + TranslationBase.of(context).notSure, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.56, color: CustomColors.accentColor, decoration: TextDecoration.underline), ), ), @@ -159,7 +160,7 @@ class _CarbsState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Select Diet Type", + TranslationBase.of(context).selectDiet, style: TextStyle( fontSize: 11, letterSpacing: -0.44, @@ -186,10 +187,16 @@ class _CarbsState extends State { calculateDietRatios(); }); }, - items: ['Very Low Carb', 'Low Carb', 'Moderate Carb', 'USDA Gudilines', 'Zone Diet'].map>((String value) { + items: [ + TranslationBase.of(context).dietVeryLow, + TranslationBase.of(context).dietLow, + TranslationBase.of(context).dietModerate, + TranslationBase.of(context).dietUSDA, + TranslationBase.of(context).dietZone + ].map>((String value) { return DropdownMenuItem( value: value, - child: Text(value), + child: Text(value, style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)), ); }).toList(), ), diff --git a/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart b/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart index 7e4e3b4f..24ca617b 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/ideal_body/ideal_body.dart @@ -1,11 +1,13 @@ +import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart'; -import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; import 'ideal_body_result_page.dart'; @@ -34,7 +36,7 @@ class _IdealBodyState extends State { double overWeightBy; int weight = 0; double idealWeight = 0; - String dropdownValue = 'Medium(fingers touch)'; + String dropdownValue = TranslationBase.of(AppGlobal.context).bodyFrameMedium; double calories = 0; String textResult = ''; double maxIdealWeight; @@ -52,17 +54,15 @@ class _IdealBodyState extends State { List _heightPopupList = List(); List _weightPopupList = List(); - - void calculateIdealWeight() { heightInches = int.parse(_heightController.text) * .39370078740157477; heightFeet = heightInches / 12; idealWeight = (50 + 2.3 * (heightInches - 60)); - if (dropdownValue == 'Small(fingers overlap)') { + if (dropdownValue == TranslationBase.of(context).bodyFrameSmall) { idealWeight = idealWeight - 10; - } else if (dropdownValue == 'Medium(fingers touch)') { + } else if (dropdownValue == TranslationBase.of(context).bodyFrameMedium) { idealWeight = idealWeight; - } else if (dropdownValue == 'Large(fingers don\'n touch)') { + } else if (dropdownValue == TranslationBase.of(context).bodyFrameLarge) { idealWeight = idealWeight + 10; } @@ -75,6 +75,7 @@ class _IdealBodyState extends State { @override Widget build(BuildContext context) { + ProjectViewModel projectViewModel = Provider.of(context); _weightPopupList = [PopupMenuItem(child: Text(TranslationBase.of(context).kg), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).lb), value: false)]; _heightPopupList = [PopupMenuItem(child: Text(TranslationBase.of(context).cm), value: true), PopupMenuItem(child: Text(TranslationBase.of(context).ft), value: false)]; @@ -94,7 +95,7 @@ class _IdealBodyState extends State { child: Column( children: [ Text( - 'Calculates the ideal body weight based on height, Weight, and Body Size', + TranslationBase.of(context).idealWeightDesc, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, @@ -177,7 +178,7 @@ class _IdealBodyState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Body Frame Size", + TranslationBase.of(context).bodyFrame, style: TextStyle( fontSize: 11, letterSpacing: -0.44, @@ -204,13 +205,14 @@ class _IdealBodyState extends State { }); }, items: [ - 'Small(fingers overlap)', - 'Medium(fingers touch)', - 'Large(fingers don\'n touch)', + TranslationBase.of(context).bodyFrameSmall, + TranslationBase.of(context).bodyFrameMedium, + TranslationBase.of(context).bodyFrameLarge, ].map>((String value) { return DropdownMenuItem( value: value, - child: Text(value), + child: Text(value, + style: TextStyle(fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins', fontSize: 11, letterSpacing: -0.44, fontWeight: FontWeight.w600)), ); }).toList(), ), @@ -498,5 +500,3 @@ class CommonDropDownView extends StatelessWidget { ); } } - - diff --git a/lib/uitl/translations_delegate_base.dart b/lib/uitl/translations_delegate_base.dart index e9f830e1..a406d420 100644 --- a/lib/uitl/translations_delegate_base.dart +++ b/lib/uitl/translations_delegate_base.dart @@ -2624,10 +2624,74 @@ class TranslationBase { String get browseOffers => localizedValues["browseOffers"][locale.languageCode]; String get myCart => localizedValues["myCart"][locale.languageCode]; + String get neck => localizedValues["neck"][locale.languageCode]; + String get waist => localizedValues["waist"][locale.languageCode]; + String get hip => localizedValues["hip"][locale.languageCode]; + String get carbsProtin => localizedValues["carbsProtin"][locale.languageCode]; + + String get inactiveAct => localizedValues["inactiveAct"][locale.languageCode]; + + String get light => localizedValues["light"][locale.languageCode]; + + String get moderate => localizedValues["moderate"][locale.languageCode]; + + String get very => localizedValues["very"][locale.languageCode]; + + String get superAct => localizedValues["super"][locale.languageCode]; + + String get resultCalories => localizedValues["resultCalories"][locale.languageCode]; + + String get bmrDesc => localizedValues["bmrDesc"][locale.languageCode]; + + String get idealWeightDesc => localizedValues["idealWeightDesc"][locale.languageCode]; + + String get bodyFrame => localizedValues["bodyFrame"][locale.languageCode]; + + String get bodyFrameSmall => localizedValues["bodyFrameSmall"][locale.languageCode]; + + String get bodyFrameMedium => localizedValues["bodyFrameMedium"][locale.languageCode]; + + String get bodyFrameLarge => localizedValues["bodyFrameLarge"][locale.languageCode]; + + String get bodyFatDesc => localizedValues["bodyFatDesc"][locale.languageCode]; + + String get essential => localizedValues["essential"][locale.languageCode]; + + String get athlete => localizedValues["athlete"][locale.languageCode]; + + String get fitness => localizedValues["fitness"][locale.languageCode]; + + String get acceptable => localizedValues["acceptable"][locale.languageCode]; + + String get obeseBodyFat => localizedValues["obeseBodyFat"][locale.languageCode]; + + String get invalid => localizedValues["invalid"][locale.languageCode]; + + String get more => localizedValues["more"][locale.languageCode]; + + String get less => localizedValues["less"][locale.languageCode]; + + String get carbProteinDesc => localizedValues["carbProteinDesc"][locale.languageCode]; + + String get calDay => localizedValues["calDay"][locale.languageCode]; + + String get notSure => localizedValues["notSure"][locale.languageCode]; + + String get selectDiet => localizedValues["selectDiet"][locale.languageCode]; + + String get dietVeryLow => localizedValues["dietVeryLow"][locale.languageCode]; + + String get dietLow => localizedValues["dietLow"][locale.languageCode]; + + String get dietModerate => localizedValues["dietModerate"][locale.languageCode]; + + String get dietUSDA => localizedValues["dietUSDA"][locale.languageCode]; + + String get dietZone => localizedValues["dietZone"][locale.languageCode]; } class TranslationBaseDelegate extends LocalizationsDelegate { From 6ffa07392c847de15ae38f3f05ab3abd461d2858 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 9 Nov 2021 15:36:58 +0300 Subject: [PATCH 8/8] Product detail page updates --- .../product_detail_view_model.dart | 38 ++-- lib/models/pharmacy/productDetailModel.dart | 204 ++++++++--------- .../product-details/footor/footer-widget.dart | 40 ++-- .../product-details/product-detail.dart | 8 +- .../product-name-and-price.dart | 67 ++---- .../product_detail_service.dart | 212 +++++++++--------- 6 files changed, 265 insertions(+), 304 deletions(-) diff --git a/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart b/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart index 98596ee0..2ae935dd 100644 --- a/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart +++ b/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart @@ -1,21 +1,20 @@ import 'package:diplomaticquarterapp/core/enum/viewstate.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart'; +import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.dart'; import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart'; import 'package:diplomaticquarterapp/models/pharmacy/Wishlist.dart'; import 'package:diplomaticquarterapp/models/pharmacy/locationModel.dart'; import 'package:diplomaticquarterapp/models/pharmacy/productDetailModel.dart'; -import 'package:diplomaticquarterapp/services/pharmacy_services/product_detail_service.dart'; import 'package:diplomaticquarterapp/models/pharmacy/specification.dart'; +import 'package:diplomaticquarterapp/services/pharmacy_services/product_detail_service.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/navigation_service.dart'; -import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart'; -import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.dart'; -import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../../locator.dart'; -class ProductDetailViewModel extends BaseViewModel{ +class ProductDetailViewModel extends BaseViewModel { ProductDetailService _productDetailService = locator(); List get productDetailService => _productDetailService.productDetailList; @@ -28,6 +27,11 @@ class ProductDetailViewModel extends BaseViewModel{ bool hasError = false; + num get stockQuantity => _productDetailService.stockQuantity; + + String get stockAvailability => _productDetailService.stockAvailability; + + bool get isStockAvailable => _productDetailService.isStockAvailable; Future getProductReviewsData(productID) async { hasError = false; @@ -72,8 +76,7 @@ class ProductDetailViewModel extends BaseViewModel{ setState(ViewState.ErrorLocal); } else { setState(ViewState.Idle); - Provider.of(locator().navigatorKey.currentContext, listen: false) - .setShoppingCartResponse( object); + Provider.of(locator().navigatorKey.currentContext, listen: false).setShoppingCartResponse(object); } } @@ -103,11 +106,9 @@ class ProductDetailViewModel extends BaseViewModel{ Future addToWishlistData(itemID) async { hasError = false; setState(ViewState.BusyLocal); - GifLoaderDialogUtils.showMyDialog( - locator().navigatorKey.currentContext); + GifLoaderDialogUtils.showMyDialog(locator().navigatorKey.currentContext); await _productDetailService.addToWishlist(itemID); - GifLoaderDialogUtils.hideDialog( - locator().navigatorKey.currentContext); + GifLoaderDialogUtils.hideDialog(locator().navigatorKey.currentContext); if (_productDetailService.hasError) { error = _productDetailService.error; @@ -127,15 +128,12 @@ class ProductDetailViewModel extends BaseViewModel{ setState(ViewState.Idle); } - Future deleteWishlistData(itemID) async { hasError = false; setState(ViewState.BusyLocal); - GifLoaderDialogUtils.showMyDialog( - locator().navigatorKey.currentContext); + GifLoaderDialogUtils.showMyDialog(locator().navigatorKey.currentContext); await _productDetailService.deleteItemFromWishlist(itemID); - GifLoaderDialogUtils.hideDialog( - locator().navigatorKey.currentContext); + GifLoaderDialogUtils.hideDialog(locator().navigatorKey.currentContext); if (_productDetailService.hasError) { error = _productDetailService.error; @@ -144,7 +142,6 @@ class ProductDetailViewModel extends BaseViewModel{ setState(ViewState.Idle); } - Future productSpecificationData(itemID) async { hasError = false; setState(ViewState.Busy); @@ -156,10 +153,7 @@ class ProductDetailViewModel extends BaseViewModel{ setState(ViewState.Idle); } - clearReview(){ - + clearReview() { productDetailService.clear(); - } - -} \ No newline at end of file +} diff --git a/lib/models/pharmacy/productDetailModel.dart b/lib/models/pharmacy/productDetailModel.dart index d2e8f010..724f1190 100644 --- a/lib/models/pharmacy/productDetailModel.dart +++ b/lib/models/pharmacy/productDetailModel.dart @@ -1,7 +1,3 @@ -// To parse this JSON data, do -// -// final productDetail = productDetailFromJson(jsonString); - import 'dart:convert'; List productDetailFromJson(String str) => List.from(json.decode(str).map((x) => ProductDetail.fromJson(x))); @@ -16,12 +12,12 @@ class ProductDetail { List reviews; factory ProductDetail.fromJson(Map json) => ProductDetail( - reviews: List.from(json["reviews"].map((x) => Review.fromJson(x))), - ); + reviews: List.from(json["reviews"].map((x) => Review.fromJson(x))), + ); Map toJson() => { - "reviews": List.from(reviews.map((x) => x.toJson())), - }; + "reviews": List.from(reviews.map((x) => x.toJson())), + }; } class Review { @@ -62,42 +58,42 @@ class Review { dynamic product; factory Review.fromJson(Map json) => Review( - id: json["id"], - position: json["position"], - reviewId: json["review_id"], - customerId: json["customer_id"], - productId: json["product_id"], - storeId: json["store_id"], - isApproved: json["is_approved"], - title: json["title"], - reviewText: json["review_text"], - replyText: json["reply_text"], - rating: json["rating"], - helpfulYesTotal: json["helpful_yes_total"], - helpfulNoTotal: json["helpful_no_total"], - createdOnUtc: DateTime.parse(json["created_on_utc"]), - customer: Customer.fromJson(json["customer"]), - product: json["product"], - ); + id: json["id"], + position: json["position"], + reviewId: json["review_id"], + customerId: json["customer_id"], + productId: json["product_id"], + storeId: json["store_id"], + isApproved: json["is_approved"], + title: json["title"], + reviewText: json["review_text"], + replyText: json["reply_text"], + rating: json["rating"], + helpfulYesTotal: json["helpful_yes_total"], + helpfulNoTotal: json["helpful_no_total"], + createdOnUtc: DateTime.parse(json["created_on_utc"]), + customer: Customer.fromJson(json["customer"]), + product: json["product"], + ); Map toJson() => { - "id": id, - "position": position, - "review_id": reviewId, - "customer_id": customerId, - "product_id": productId, - "store_id": storeId, - "is_approved": isApproved, - "title": title, - "review_text": reviewText, - "reply_text": replyText, - "rating": rating, - "helpful_yes_total": helpfulYesTotal, - "helpful_no_total": helpfulNoTotal, - "created_on_utc": createdOnUtc.toIso8601String(), - "customer": customer.toJson(), - "product": product, - }; + "id": id, + "position": position, + "review_id": reviewId, + "customer_id": customerId, + "product_id": productId, + "store_id": storeId, + "is_approved": isApproved, + "title": title, + "review_text": reviewText, + "reply_text": replyText, + "rating": rating, + "helpful_yes_total": helpfulYesTotal, + "helpful_no_total": helpfulNoTotal, + "created_on_utc": createdOnUtc.toIso8601String(), + "customer": customer.toJson(), + "product": product, + }; } class Customer { @@ -164,75 +160,73 @@ class Customer { dynamic registeredInStoreId; factory Customer.fromJson(Map json) => Customer( - fileNumber: json["file_number"], - iqamaNumber: json["iqama_number"], - isOutSa: json["is_out_sa"], - patientType: json["patient_type"], - gender: json["gender"], - birthDate: DateTime.parse(json["birth_date"]), - phone: json["phone"], - countryCode: json["country_code"], - yahalaAccountno: json["yahala_accountno"], - billingAddress: json["billing_address"], - shippingAddress: json["shipping_address"], - id: json["id"], - username: emailValues.map[json["username"]], - email: emailValues.map[json["email"]], - firstName: json["first_name"], - lastName: json["last_name"], - languageId: json["language_id"], - adminComment: json["admin_comment"], - isTaxExempt: json["is_tax_exempt"], - hasShoppingCartItems: json["has_shopping_cart_items"], - active: json["active"], - deleted: json["deleted"], - isSystemAccount: json["is_system_account"], - systemName: json["system_name"], - lastIpAddress: json["last_ip_address"], - createdOnUtc: json["created_on_utc"], - lastLoginDateUtc: json["last_login_date_utc"], - lastActivityDateUtc: json["last_activity_date_utc"], - registeredInStoreId: json["registered_in_store_id"], - ); + fileNumber: json["file_number"], + iqamaNumber: json["iqama_number"], + isOutSa: json["is_out_sa"], + patientType: json["patient_type"], + gender: json["gender"], + birthDate: DateTime.parse(json["birth_date"]), + phone: json["phone"], + countryCode: json["country_code"], + yahalaAccountno: json["yahala_accountno"], + billingAddress: json["billing_address"], + shippingAddress: json["shipping_address"], + id: json["id"], + username: emailValues.map[json["username"]], + email: emailValues.map[json["email"]], + firstName: json["first_name"], + lastName: json["last_name"], + languageId: json["language_id"], + adminComment: json["admin_comment"], + isTaxExempt: json["is_tax_exempt"], + hasShoppingCartItems: json["has_shopping_cart_items"], + active: json["active"], + deleted: json["deleted"], + isSystemAccount: json["is_system_account"], + systemName: json["system_name"], + lastIpAddress: json["last_ip_address"], + createdOnUtc: json["created_on_utc"], + lastLoginDateUtc: json["last_login_date_utc"], + lastActivityDateUtc: json["last_activity_date_utc"], + registeredInStoreId: json["registered_in_store_id"], + ); Map toJson() => { - "file_number": fileNumber, - "iqama_number": iqamaNumber, - "is_out_sa": isOutSa, - "patient_type": patientType, - "gender": gender, - "birth_date": birthDate.toIso8601String(), - "phone": phone, - "country_code": countryCode, - "yahala_accountno": yahalaAccountno, - "billing_address": billingAddress, - "shipping_address": shippingAddress, - "id": id, - "username": emailValues.reverse[username], - "email": emailValues.reverse[email], - "first_name": firstName, - "last_name": lastName, - "language_id": languageId, - "admin_comment": adminComment, - "is_tax_exempt": isTaxExempt, - "has_shopping_cart_items": hasShoppingCartItems, - "active": active, - "deleted": deleted, - "is_system_account": isSystemAccount, - "system_name": systemName, - "last_ip_address": lastIpAddress, - "created_on_utc": createdOnUtc, - "last_login_date_utc": lastLoginDateUtc, - "last_activity_date_utc": lastActivityDateUtc, - "registered_in_store_id": registeredInStoreId, - }; + "file_number": fileNumber, + "iqama_number": iqamaNumber, + "is_out_sa": isOutSa, + "patient_type": patientType, + "gender": gender, + "birth_date": birthDate.toIso8601String(), + "phone": phone, + "country_code": countryCode, + "yahala_accountno": yahalaAccountno, + "billing_address": billingAddress, + "shipping_address": shippingAddress, + "id": id, + "username": emailValues.reverse[username], + "email": emailValues.reverse[email], + "first_name": firstName, + "last_name": lastName, + "language_id": languageId, + "admin_comment": adminComment, + "is_tax_exempt": isTaxExempt, + "has_shopping_cart_items": hasShoppingCartItems, + "active": active, + "deleted": deleted, + "is_system_account": isSystemAccount, + "system_name": systemName, + "last_ip_address": lastIpAddress, + "created_on_utc": createdOnUtc, + "last_login_date_utc": lastLoginDateUtc, + "last_activity_date_utc": lastActivityDateUtc, + "registered_in_store_id": registeredInStoreId, + }; } enum Email { STEVE_GATES_NOP_COMMERCE_COM } -final emailValues = EnumValues({ - "steve_gates@nopCommerce.com": Email.STEVE_GATES_NOP_COMMERCE_COM -}); +final emailValues = EnumValues({"steve_gates@nopCommerce.com": Email.STEVE_GATES_NOP_COMMERCE_COM}); class EnumValues { Map map; diff --git a/lib/pages/pharmacies/screens/product-details/footor/footer-widget.dart b/lib/pages/pharmacies/screens/product-details/footor/footer-widget.dart index 14dab3e5..72399498 100644 --- a/lib/pages/pharmacies/screens/product-details/footor/footer-widget.dart +++ b/lib/pages/pharmacies/screens/product-details/footor/footer-widget.dart @@ -68,7 +68,7 @@ class _FooterWidgetState extends State { Padding( padding: const EdgeInsets.all(8.0), child: Text( - "Quantity", + TranslationBase.of(context).quantity, style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold), ), ), @@ -157,17 +157,19 @@ class _FooterWidgetState extends State { ), ], ), - onPressed: () { - setState(() { - if (showUI) { - quantityUI = 80; - showUI = false; - } else { - quantityUI = 160; - showUI = true; - } - }); - }, + onPressed: widget.isAvailable && !widget.item.isRx + ? () { + setState(() { + if (showUI) { + quantityUI = 80; + showUI = false; + } else { + quantityUI = 160; + showUI = true; + } + }); + } + : null, ), ), SizedBox( @@ -207,20 +209,20 @@ class _FooterWidgetState extends State { ); } else { await widget.addToShoppingCartFunction(quantity: widget.quantity, itemID: widget.item.id, model: widget.model); - Navigator.of(context).pushNamed( - CART_ORDER_PAGE, - ); - // Navigator.push( - // context, - // FadePage(page: CartOrderPage()), + // Navigator.of(context).pushNamed( + // CART_ORDER_PAGE, // ); + Navigator.push( + context, + FadePage(page: CartOrderPage()), + ); } }, fontWeight: FontWeight.w600, borderColor: Colors.grey[800], borderRadius: 3, disableColor: Colors.grey[700], - color: !widget.isAvailable && widget.quantity > 0 || widget.quantity > widget.quantityLimit || widget.item.rxMessage != null ? Colors.grey : Colors.grey[800], + color: !widget.isAvailable && widget.quantity > 0 || widget.quantity > widget.quantityLimit || widget.item.isRx ? Colors.grey : Colors.grey[800], ), ), ], diff --git a/lib/pages/pharmacies/screens/product-details/product-detail.dart b/lib/pages/pharmacies/screens/product-details/product-detail.dart index d33e3178..015df6ed 100644 --- a/lib/pages/pharmacies/screens/product-details/product-detail.dart +++ b/lib/pages/pharmacies/screens/product-details/product-detail.dart @@ -87,6 +87,9 @@ class __ProductDetailPageState extends State { Widget build(BuildContext context) { return BaseView( allowAny: true, + onModelReady: (model) { + model.getProductReviewsData(widget.product.id); + }, builder: (_, model, wi) => AppScaffold( appBarTitle: TranslationBase.of(context).productDetails, isShowAppBar: true, @@ -146,6 +149,7 @@ class __ProductDetailPageState extends State { notifyMeWhenAvailable(itemId: itemId, customerId: customerId, model: model); }, isInWishList: isInWishList, + isStockAvailable: model.isStockAvailable, ), ), SizedBox( @@ -302,10 +306,10 @@ class __ProductDetailPageState extends State { ), ), bottomSheet: FooterWidget( - widget.product.stockAvailability != 'Out of stock', + model.isStockAvailable, widget.product.orderMaximumQuantity, widget.product.orderMinimumQuantity, - widget.product.stockQuantity, + model.stockQuantity, widget.product, quantity: quantity, isOverQuantity: isOverQuantity, diff --git a/lib/pages/pharmacies/screens/product-details/product-name-and-price.dart b/lib/pages/pharmacies/screens/product-details/product-name-and-price.dart index 6d8ea11d..9401f3e0 100644 --- a/lib/pages/pharmacies/screens/product-details/product-name-and-price.dart +++ b/lib/pages/pharmacies/screens/product-details/product-name-and-price.dart @@ -1,7 +1,6 @@ import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart'; import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart'; import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; -import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:flutter/material.dart'; @@ -20,16 +19,12 @@ class ProductNameAndPrice extends StatefulWidget { final Function notifyMeWhenAvailable; final Function addToWishlistFunction; final Function deleteFromWishlistFunction; + final bool isStockAvailable; - AuthenticatedUserObject authenticatedUserObject = - locator(); + AuthenticatedUserObject authenticatedUserObject = locator(); ProductNameAndPrice(this.context, this.item, - {this.customerId, - this.isInWishList, - this.notifyMeWhenAvailable, - this.addToWishlistFunction, - this.deleteFromWishlistFunction}); + {this.customerId, this.isInWishList, this.notifyMeWhenAvailable, this.addToWishlistFunction, this.deleteFromWishlistFunction, @required this.isStockAvailable}); @override _ProductNameAndPriceState createState() => _ProductNameAndPriceState(); @@ -51,25 +46,18 @@ class _ProductNameAndPriceState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Texts(widget.item.price.toString() + " " + "SR", - fontWeight: FontWeight.bold, fontSize: 20), + Texts(widget.item.price.toString() + " " + TranslationBase.of(context).sar, fontWeight: FontWeight.bold, fontSize: 20), Texts( - projectViewModel.isArabic - ? widget.item.stockAvailabilityn - : widget.item.stockAvailability, + projectViewModel.isArabic ? widget.item.stockAvailabilityn : widget.item.stockAvailability, fontWeight: FontWeight.bold, fontSize: 15, - color: widget.item.stockAvailability == 'Out of stock' - ? Colors.red - : Colors.green, + color: widget.isStockAvailable ? Colors.green : Colors.red, ), // SizedBox(width: 20), if (widget.authenticatedUserObject.isLogin) - widget.item.stockAvailability == 'Out of stock' && - widget.customerId != null + widget.isStockAvailable && widget.customerId != null ? InkWell( - onTap: () => widget.notifyMeWhenAvailable( - context, widget.item.id), + onTap: () => widget.notifyMeWhenAvailable(context, widget.item.id), child: Row(children: [ Texts( TranslationBase.of(context).notifyMe, @@ -85,23 +73,15 @@ class _ProductNameAndPriceState extends State { ]), ) : IconWithBg( - icon: !widget.isInWishList - ? Icons.favorite_border - : Icons.favorite, - color: !widget.isInWishList - ? Colors.white - : Colors.red[800], + icon: !widget.isInWishList ? Icons.favorite_border : Icons.favorite, + color: !widget.isInWishList ? Colors.white : Colors.red[800], onPress: () async { { if (widget.customerId != null) { if (!widget.isInWishList) { - - await widget - .addToWishlistFunction(widget.item.id); - + await widget.addToWishlistFunction(widget.item.id); } else { - await widget - .deleteFromWishlistFunction(widget.item.id); + await widget.deleteFromWishlistFunction(widget.item.id); } } else { return; @@ -118,13 +98,9 @@ class _ProductNameAndPriceState extends State { child: Container( margin: EdgeInsets.only(left: 5), child: Align( - alignment: projectViewModel.isArabic - ? Alignment.topRight - : Alignment.topLeft, + alignment: projectViewModel.isArabic ? Alignment.topRight : Alignment.topLeft, child: Text( - projectViewModel.isArabic - ? widget.item.namen - : widget.item.name, + projectViewModel.isArabic ? widget.item.namen : widget.item.name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), ), ), @@ -140,8 +116,7 @@ class _ProductNameAndPriceState extends State { child: Row( children: [ RatingBar.readOnly( - initialRating: double.parse( - widget.item.approvedRatingSum.toString()), + initialRating: double.parse(widget.item.approvedRatingSum.toString()), size: 15.0, filledColor: Colors.yellow[700], emptyColor: Colors.grey[400], @@ -172,19 +147,9 @@ class _ProductNameAndPriceState extends State { Row( children: [ Text( - projectViewModel.isArabic - ? widget.item.rxMessagen.toString() - : widget.item.rxMessage.toString(), + projectViewModel.isArabic ? widget.item.rxMessagen.toString() : widget.item.rxMessage.toString(), style: TextStyle(color: Colors.red, fontSize: 10), ), - SizedBox( - width: 5, - ), - Icon( - FontAwesomeIcons.questionCircle, - color: Colors.red, - size: 15.0, - ) ], ) ], diff --git a/lib/services/pharmacy_services/product_detail_service.dart b/lib/services/pharmacy_services/product_detail_service.dart index 47673eab..23379914 100644 --- a/lib/services/pharmacy_services/product_detail_service.dart +++ b/lib/services/pharmacy_services/product_detail_service.dart @@ -15,36 +15,53 @@ import 'package:diplomaticquarterapp/uitl/app_toast.dart'; class ProductDetailService extends BaseService { bool isLogin = false; + num _stockQuantity; + + num get stockQuantity => _stockQuantity; + + String _stockAvailability; + + String get stockAvailability => _stockAvailability; + + bool _isStockAvailable; + + bool get isStockAvailable => _isStockAvailable; + List _productDetailList = List(); + List get productDetailList => _productDetailList; List _productLocationList = List(); + List get productLocationList => _productLocationList; List _addToCartModel = List(); + List get addToCartModel => _addToCartModel; List _wishListProducts = List(); + List get wishListProducts => _wishListProducts; List _productSpecification = List(); - List get productSpecification => _productSpecification; - + List get productSpecification => _productSpecification; Future getProductReviews(productID) async { hasError = false; - await baseAppClient.getPharmacy(GET_PRODUCT_DETAIL+productID+"?fields=reviews", - onSuccess: (dynamic response, int statusCode) { - _productDetailList.clear(); - response['products'].forEach((item) { - _productDetailList.add(ProductDetail.fromJson(item)); - print(response); - }); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - }); + await baseAppClient.getPharmacy(GET_PRODUCT_DETAIL + productID + "?fields=reviews,stock_quantity,stock_availability,IsStockAvailable", onSuccess: (dynamic response, int statusCode) { + _productDetailList.clear(); + response['products'].forEach((item) { + _productDetailList.add(ProductDetail.fromJson(item)); + print(response); + }); + _stockQuantity = response['products'][0]['stock_quantity']; + _stockAvailability = response['products'][0]['stock_availability']; + _isStockAvailable = response['products'][0]['IsStockAvailable']; + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }); } Future getProductAvailabiltyDetail() async { @@ -52,29 +69,28 @@ class ProductDetailService extends BaseService { Map request; request = { - "Channel": 3, - "DeviceTypeID": 2, - "IPAdress": "10.20.10.20", - "LanguageID": 2, - "PatientOutSA": 0, - "SKU": "6720020025", - "SessionID": null, - "VersionID": 5.6, - "generalid": "Cs2020@2016\$2958", - "isDentalAllowedBackend": false + // "Channel": 3, + // "DeviceTypeID": 2, + // "IPAdress": "10.20.10.20", + // "LanguageID": 2, + // "PatientOutSA": 0, + // "SKU": "6720020025", + // "SessionID": null, + // "VersionID": 5.6, + // "generalid": "Cs2020@2016\$2958", + // "isDentalAllowedBackend": false }; - await baseAppClient.post(GET_LOCATION, - onSuccess: (dynamic response, int statusCode) { - _productLocationList.clear(); - response['PharmList'].forEach((item) { - _productLocationList.add(LocationModel.fromJson(item)); - print(_productLocationList); - print(response); - }); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - }, body: request); + await baseAppClient.post(GET_LOCATION, onSuccess: (dynamic response, int statusCode) { + _productLocationList.clear(); + response['PharmList'].forEach((item) { + _productLocationList.add(LocationModel.fromJson(item)); + print(_productLocationList); + print(response); + }); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }, body: request); } Future addToCart(quantity, itemID) async { @@ -83,30 +99,22 @@ class ProductDetailService extends BaseService { Map request; request = { - "shopping_cart_item": - { - "quantity": quantity, - "shopping_cart_type": "1", - "product_id": itemID, - "customer_id": customerId, - "language_id": 1 - } + "shopping_cart_item": {"quantity": quantity, "shopping_cart_type": "1", "product_id": itemID, "customer_id": customerId, "language_id": 1} }; dynamic localRes; - - await baseAppClient.pharmacyPost(GET_SHOPPING_CART, isExternal: false, - onSuccess: (dynamic response, int statusCode) { - _addToCartModel.clear(); - response['shopping_carts'].forEach((item) { - _addToCartModel.add(Wishlist.fromJson(item)); - }); - AppToast.showSuccessToast(message: 'You have added a product to the cart'); - localRes = response; - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); - }, body: request); + + await baseAppClient.pharmacyPost(GET_SHOPPING_CART, isExternal: false, onSuccess: (dynamic response, int statusCode) { + _addToCartModel.clear(); + response['shopping_carts'].forEach((item) { + _addToCartModel.add(Wishlist.fromJson(item)); + }); + AppToast.showSuccessToast(message: 'You have added a product to the cart'); + localRes = response; + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage()); + }, body: request); return Future.value(localRes); } @@ -118,7 +126,7 @@ class ProductDetailService extends BaseService { }, onFailure: (String error, int statusCode) { hasError = true; super.error = error; - AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); + AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage()); }); } @@ -130,67 +138,61 @@ class ProductDetailService extends BaseService { request = { "shopping_cart_item": {"quantity": 1, "shopping_cart_type": "Wishlist", "product_id": itemID, "customer_id": customerId, "language_id": 1} }; - await baseAppClient.pharmacyPost(GET_SHOPPING_CART, - onSuccess: (dynamic response, int statusCode) { - _wishListProducts.clear(); - response['shopping_carts'].forEach((item) { - _wishListProducts.add(Wishlist.fromJson(item)); - }); - AppToast.showSuccessToast(message: 'You have added a product to the Wishlist'); - - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); - }, body: request); + await baseAppClient.pharmacyPost(GET_SHOPPING_CART, onSuccess: (dynamic response, int statusCode) { + _wishListProducts.clear(); + response['shopping_carts'].forEach((item) { + _wishListProducts.add(Wishlist.fromJson(item)); + }); + AppToast.showSuccessToast(message: 'You have added a product to the Wishlist'); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage()); + }, body: request); } Future getWishlistItems() async { var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID); hasError = false; - await baseAppClient.getPharmacy(GET_WISHLIST+customerId+"?shopping_cart_type=2", - onSuccess: (dynamic response, int statusCode) { - _wishListProducts.clear(); - response['shopping_carts'].forEach((item) { - _wishListProducts.add(Wishlist.fromJson(item)); - }); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - }); + await baseAppClient.getPharmacy(GET_WISHLIST + customerId + "?shopping_cart_type=2", onSuccess: (dynamic response, int statusCode) { + _wishListProducts.clear(); + response['shopping_carts'].forEach((item) { + _wishListProducts.add(Wishlist.fromJson(item)); + }); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }); } Future deleteItemFromWishlist(itemID) async { var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID); hasError = false; - await baseAppClient.getPharmacy(DELETE_WISHLIST+customerId+"+&product_id="+itemID+"&cart_type=Wishlist", - onSuccess: (dynamic response, int statusCode) { - _wishListProducts.clear(); - response['shopping_carts'].forEach((item) { - _wishListProducts.add(Wishlist.fromJson(item)); - }); - AppToast.showSuccessToast(message: 'You have removed a product from the Wishlist'); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - AppToast.showErrorToast(message: error??Utils.generateContactAdminMessage()); - }); + await baseAppClient.getPharmacy(DELETE_WISHLIST + customerId + "+&product_id=" + itemID + "&cart_type=Wishlist", onSuccess: (dynamic response, int statusCode) { + _wishListProducts.clear(); + response['shopping_carts'].forEach((item) { + _wishListProducts.add(Wishlist.fromJson(item)); + }); + AppToast.showSuccessToast(message: 'You have removed a product from the Wishlist'); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + AppToast.showErrorToast(message: error ?? Utils.generateContactAdminMessage()); + }); } Future productSpecificationData(itemID) async { hasError = false; - await baseAppClient.getPharmacy(GET_SPECIFICATION+itemID, - onSuccess: (dynamic response, int statusCode) { - _productSpecification.clear(); - response['specification'].forEach((item) { - _productSpecification.add(SpecificationModel.fromJson(item)); - print(_productSpecification); - }); - }, onFailure: (String error, int statusCode) { - hasError = true; - super.error = error; - }); + await baseAppClient.getPharmacy(GET_SPECIFICATION + itemID, onSuccess: (dynamic response, int statusCode) { + _productSpecification.clear(); + response['specification'].forEach((item) { + _productSpecification.add(SpecificationModel.fromJson(item)); + print(_productSpecification); + }); + }, onFailure: (String error, int statusCode) { + hasError = true; + super.error = error; + }); } - }