diff --git a/android/app/src/main/res/ic_launcher-web.png b/android/app/src/main/res/ic_launcher-web.png
new file mode 100644
index 0000000..97553a3
Binary files /dev/null and b/android/app/src/main/res/ic_launcher-web.png differ
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
index 345888d..79d695e 100644
--- a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -1,6 +1,4 @@
-
-
+
-
\ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..79d695e
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..62a0b51
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..263b3ed
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..bdf769a
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/android/app/src/main/res/play_store_512.png b/android/app/src/main/res/play_store_512.png
deleted file mode 100644
index f0c67d2..0000000
Binary files a/android/app/src/main/res/play_store_512.png and /dev/null differ
diff --git a/android/app/src/main/res/playstore-icon.png b/android/app/src/main/res/playstore-icon.png
new file mode 100644
index 0000000..566d741
Binary files /dev/null and b/android/app/src/main/res/playstore-icon.png differ
diff --git a/android/app/src/main/res/values/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml
new file mode 100644
index 0000000..4db2c8a
--- /dev/null
+++ b/android/app/src/main/res/values/ic_launcher_background.xml
@@ -0,0 +1,3 @@
+
+ #ff643c
+
\ No newline at end of file
diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml
deleted file mode 100644
index d2aa524..0000000
--- a/android/app/src/main/res/values/styles.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
diff --git a/assets/translations/en_En.json b/assets/translations/en-US.json
similarity index 96%
rename from assets/translations/en_En.json
rename to assets/translations/en-US.json
index 3552d0d..bdb591d 100644
--- a/assets/translations/en_En.json
+++ b/assets/translations/en-US.json
@@ -102,5 +102,7 @@
"rideHistory": "Ride History",
"plsLoginToAcc": "Please Log In to Continue",
"youAreNotLoggedIn": "You’re not logged in. Please sign in to access your account and explore all features.",
- "noOrderfound": "No order found"
+ "noOrderfound": "No order found",
+ "reset_password_link_sent": "A reset link has been sent to {email}",
+ "pay_amount": "Pay Amount: {amount}"
}
\ No newline at end of file
diff --git a/assets/translations/ru-RU.json b/assets/translations/ru-RU.json
new file mode 100644
index 0000000..bdb591d
--- /dev/null
+++ b/assets/translations/ru-RU.json
@@ -0,0 +1,108 @@
+{
+ "loginToExplore" : "Log in to explore your all in one vendor app favourites and shop effortlessly.",
+ "emailAddress": "Email Address*",
+ "password": "Password*",
+ "enterPassword": "Enter password",
+ "forgotPassword": "Forgot Password",
+ "login": "Log in",
+ "orContinueWith": "or continue with",
+
+
+ "withGoogle": "with Google",
+ "withApple": "with Apple",
+ "dontHaveAccount": "Didn't have an account?",
+ "signUp": "Sign up",
+ "skip": "Skip",
+ "signUpToExplore": "Sign up to explore all our services and start shopping, riding, and more.",
+ "firstName": "First Name*",
+ "lastName": "Last Name*",
+ "enterMobileNumber": "Enter Mobile number",
+ "confirmPassword": "Confirm Password*",
+ "enterConfirmPassword": "Enter confirm password",
+ "referralCode": "Referral Code",
+ "enterReferralCode": "Enter referral code",
+ "alreadyHaveAccount":"Already have an account?",
+ "enterYourregisteredEmail": "Enter your registered email to receive a reset link.",
+ "sendLink": "Send Link",
+ "rememberPassword": "Remember Password?",
+ "enterOtpSent": "Enter the OTP sent to your mobile",
+ "resendOTP": "Resend OTP",
+ "verify": "Verify",
+ "useYourMobileNumber": "Use your mobile number to Log in easily and securely.",
+ "sendCode":"Send Code",
+ "serviceIsUnavailable": "Service is unavailable at the selected address.",
+ "pickUpLocation": "Pickup Location",
+ "destinationLocation": "Destination Location",
+ "continueT":"Continue",
+ "plsSelectSourceLocation": "Please select source location",
+ "plsSelectDestinationLocations": "Please select destination location",
+ "selectVehicleType": "Select Your Vehicle Type",
+ "plsSelectVehicleTypeFirst": "Please select a vehicle type first.",
+ "plsSelectPaymentMethod": "Please select a payment method",
+ "insufficientWallet": "Insufficient wallet balance. Please select another payment method.",
+ "promoCode": "Promo code",
+ "thisOfferNotEligible": "This offer not eligible for this booking",
+ "viewAll": "View All",
+ "writeCoupon": "Write coupon Code",
+ "redeemNow": "Redeem now",
+ "plsEnterCouponCode":"Please enter a coupon code",
+ "couponApplied": "Coupon applied successfully",
+ "couponExpired": "This coupon code has been expired",
+ "invalidCouponCode": "Invalid coupon code",
+ "orderSummary": "Order Summary",
+ "subtotal": "Subtotal",
+ "discount": "Discount",
+ "orderTotal": "Order Total",
+ "confirmBooking": "Confirm Booking",
+ "waitingForDriver": "Waiting for driver....",
+ "cancelRide": "Cancel Ride",
+ "riderCancelledSucces": "Ride cancelled successfully",
+ "failedToCancel": "Failed to cancel ride",
+ "pleaseWait": "Please wait...",
+ "change": "Change",
+ "yourSosRequest": "Your SOS request has been submitted to admin",
+ "yourSosrequestAlreadySubmitted": "Your SOS request is already submitted",
+ "payNow": "Pay Now",
+ "youDoNothaveSufficientwalletBalance": "You do not have sufficient wallet balance",
+ "somethingWentWrong": "Something went wrong, please contact admin.",
+ "cash": "Cash",
+ "coupon": "Coupon",
+ "couponNotFound": "Coupon not found.",
+ "tapToApply": "Tap To Apply",
+ "home": "Home",
+ "myBookings": "My Bookings",
+ "profile": "profile",
+ "wallet": "Wallet",
+ "cabServiceType": "Cab Service Type",
+ "everyRideVerified": "Every Ride. Every Driver. Verified.",
+ "allDriversIDCheck": "All drivers go through ID checks and background verification for your safety.",
+ "intercity": "Intercity",
+ "aroundTheCity": "Around the city",
+ "rideDetails": "Ride Details",
+ "orderId": "Order Id:",
+ "bookingData": "Booking Date:",
+ "rideAndFareSummary": "Ride & Fare Summary",
+ "updateReview": "Update Review",
+ "addReview": "Add Review",
+ "complain": "Complain",
+ "distance": "Distance",
+ "km": "KM",
+ "duration": "Duration",
+ "howWasTrip": "How was your trip?",
+ "yourFeedbackWillHelp": "Your feedback will help us improve \n driving experience better",
+ "rateFor": "Rate for",
+ "typeComment": "Type comment....",
+ "title": "Title",
+ "typeDescription": "Type Description...",
+ "save": "Save",
+ "popularDestinations": "Popular Destinations",
+ "selectPaymentMethod": "Select Payment Method",
+ "prefferedPayment": "Preferred Payment",
+ "otherPaymentOptions": "Other Payment Options",
+ "rideHistory": "Ride History",
+ "plsLoginToAcc": "Please Log In to Continue",
+ "youAreNotLoggedIn": "You’re not logged in. Please sign in to access your account and explore all features.",
+ "noOrderfound": "No order found",
+ "reset_password_link_sent": "A reset link has been sent to {email}",
+ "pay_amount": "Pay Amount: {amount}"
+}
\ No newline at end of file
diff --git a/assets/translations/ru_RU.json b/assets/translations/ru_RU.json
deleted file mode 100644
index e69de29..0000000
diff --git a/assets/translations/uz-UZ.json b/assets/translations/uz-UZ.json
new file mode 100644
index 0000000..bdb591d
--- /dev/null
+++ b/assets/translations/uz-UZ.json
@@ -0,0 +1,108 @@
+{
+ "loginToExplore" : "Log in to explore your all in one vendor app favourites and shop effortlessly.",
+ "emailAddress": "Email Address*",
+ "password": "Password*",
+ "enterPassword": "Enter password",
+ "forgotPassword": "Forgot Password",
+ "login": "Log in",
+ "orContinueWith": "or continue with",
+
+
+ "withGoogle": "with Google",
+ "withApple": "with Apple",
+ "dontHaveAccount": "Didn't have an account?",
+ "signUp": "Sign up",
+ "skip": "Skip",
+ "signUpToExplore": "Sign up to explore all our services and start shopping, riding, and more.",
+ "firstName": "First Name*",
+ "lastName": "Last Name*",
+ "enterMobileNumber": "Enter Mobile number",
+ "confirmPassword": "Confirm Password*",
+ "enterConfirmPassword": "Enter confirm password",
+ "referralCode": "Referral Code",
+ "enterReferralCode": "Enter referral code",
+ "alreadyHaveAccount":"Already have an account?",
+ "enterYourregisteredEmail": "Enter your registered email to receive a reset link.",
+ "sendLink": "Send Link",
+ "rememberPassword": "Remember Password?",
+ "enterOtpSent": "Enter the OTP sent to your mobile",
+ "resendOTP": "Resend OTP",
+ "verify": "Verify",
+ "useYourMobileNumber": "Use your mobile number to Log in easily and securely.",
+ "sendCode":"Send Code",
+ "serviceIsUnavailable": "Service is unavailable at the selected address.",
+ "pickUpLocation": "Pickup Location",
+ "destinationLocation": "Destination Location",
+ "continueT":"Continue",
+ "plsSelectSourceLocation": "Please select source location",
+ "plsSelectDestinationLocations": "Please select destination location",
+ "selectVehicleType": "Select Your Vehicle Type",
+ "plsSelectVehicleTypeFirst": "Please select a vehicle type first.",
+ "plsSelectPaymentMethod": "Please select a payment method",
+ "insufficientWallet": "Insufficient wallet balance. Please select another payment method.",
+ "promoCode": "Promo code",
+ "thisOfferNotEligible": "This offer not eligible for this booking",
+ "viewAll": "View All",
+ "writeCoupon": "Write coupon Code",
+ "redeemNow": "Redeem now",
+ "plsEnterCouponCode":"Please enter a coupon code",
+ "couponApplied": "Coupon applied successfully",
+ "couponExpired": "This coupon code has been expired",
+ "invalidCouponCode": "Invalid coupon code",
+ "orderSummary": "Order Summary",
+ "subtotal": "Subtotal",
+ "discount": "Discount",
+ "orderTotal": "Order Total",
+ "confirmBooking": "Confirm Booking",
+ "waitingForDriver": "Waiting for driver....",
+ "cancelRide": "Cancel Ride",
+ "riderCancelledSucces": "Ride cancelled successfully",
+ "failedToCancel": "Failed to cancel ride",
+ "pleaseWait": "Please wait...",
+ "change": "Change",
+ "yourSosRequest": "Your SOS request has been submitted to admin",
+ "yourSosrequestAlreadySubmitted": "Your SOS request is already submitted",
+ "payNow": "Pay Now",
+ "youDoNothaveSufficientwalletBalance": "You do not have sufficient wallet balance",
+ "somethingWentWrong": "Something went wrong, please contact admin.",
+ "cash": "Cash",
+ "coupon": "Coupon",
+ "couponNotFound": "Coupon not found.",
+ "tapToApply": "Tap To Apply",
+ "home": "Home",
+ "myBookings": "My Bookings",
+ "profile": "profile",
+ "wallet": "Wallet",
+ "cabServiceType": "Cab Service Type",
+ "everyRideVerified": "Every Ride. Every Driver. Verified.",
+ "allDriversIDCheck": "All drivers go through ID checks and background verification for your safety.",
+ "intercity": "Intercity",
+ "aroundTheCity": "Around the city",
+ "rideDetails": "Ride Details",
+ "orderId": "Order Id:",
+ "bookingData": "Booking Date:",
+ "rideAndFareSummary": "Ride & Fare Summary",
+ "updateReview": "Update Review",
+ "addReview": "Add Review",
+ "complain": "Complain",
+ "distance": "Distance",
+ "km": "KM",
+ "duration": "Duration",
+ "howWasTrip": "How was your trip?",
+ "yourFeedbackWillHelp": "Your feedback will help us improve \n driving experience better",
+ "rateFor": "Rate for",
+ "typeComment": "Type comment....",
+ "title": "Title",
+ "typeDescription": "Type Description...",
+ "save": "Save",
+ "popularDestinations": "Popular Destinations",
+ "selectPaymentMethod": "Select Payment Method",
+ "prefferedPayment": "Preferred Payment",
+ "otherPaymentOptions": "Other Payment Options",
+ "rideHistory": "Ride History",
+ "plsLoginToAcc": "Please Log In to Continue",
+ "youAreNotLoggedIn": "You’re not logged in. Please sign in to access your account and explore all features.",
+ "noOrderfound": "No order found",
+ "reset_password_link_sent": "A reset link has been sent to {email}",
+ "pay_amount": "Pay Amount: {amount}"
+}
\ No newline at end of file
diff --git a/assets/translations/uz_UZ.json b/assets/translations/uz_UZ.json
deleted file mode 100644
index e69de29..0000000
diff --git a/lib/constant/constant.dart b/lib/constant/constant.dart
index 4d13a6b..6becfc0 100644
--- a/lib/constant/constant.dart
+++ b/lib/constant/constant.dart
@@ -19,7 +19,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart' as geolocator;
import 'package:geolocator/geolocator.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:intl/intl.dart';
import 'package:mailer/mailer.dart';
@@ -172,7 +172,10 @@ class Constant {
static bool checkZoneCheck(double latitude, double longLatitude) {
bool isZoneAvailable = false;
for (var element in Constant.zoneList) {
- if (Constant.isPointInPolygon(LatLng(latitude, longLatitude), element.area!)) {
+ if (Constant.isPointInPolygon(
+ LatLng(latitude, longLatitude),
+ element.area!,
+ )) {
isZoneAvailable = true;
break;
} else {
@@ -185,7 +188,10 @@ class Constant {
static String? getZoneId(double latitude, double longLatitude) {
String? zoneId;
for (var element in Constant.zoneList) {
- if (Constant.isPointInPolygon(LatLng(latitude, longLatitude), element.area!)) {
+ if (Constant.isPointInPolygon(
+ LatLng(latitude, longLatitude),
+ element.area!,
+ )) {
zoneId = element.id;
break;
}
@@ -198,13 +204,18 @@ class Constant {
return (rng.nextInt(900000) + 100000).toString(); // 6 digit
}
- static Future checkPermission({required BuildContext context, required Function() onTap}) async {
+ static Future checkPermission({
+ required BuildContext context,
+ required Function() onTap,
+ }) async {
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied) {
- ShowToastDialog.showToast("You have to allow location permission to use your location");
+ ShowToastDialog.showToast(
+ "You have to allow location permission to use your location",
+ );
} else if (permission == LocationPermission.deniedForever) {
showDialog(
context: context,
@@ -241,7 +252,10 @@ class Constant {
return isPlanExpire;
}
- static bool isExpireDate({required bool expiryDay, Timestamp? subscriptionExpiryDate}) {
+ static bool isExpireDate({
+ required bool expiryDay,
+ Timestamp? subscriptionExpiryDate,
+ }) {
bool isPlanExpire = false;
if (expiryDay == true) {
isPlanExpire = false;
@@ -301,17 +315,49 @@ class Constant {
String commission = "0";
if (sectionConstantModel!.adminCommision!.isEnabled == true) {
if (vendorModel.adminCommission == null) {
- if (sectionConstantModel!.adminCommision!.commissionType!.toLowerCase() == "Percent".toLowerCase() ||
- sectionConstantModel!.adminCommision!.commissionType?.toLowerCase() == "Percentage".toLowerCase()) {
- commission = (double.parse(price) + (double.parse(price) * double.parse(sectionConstantModel!.adminCommision!.amount.toString()) / 100)).toString();
+ if (sectionConstantModel!.adminCommision!.commissionType!
+ .toLowerCase() ==
+ "Percent".toLowerCase() ||
+ sectionConstantModel!.adminCommision!.commissionType
+ ?.toLowerCase() ==
+ "Percentage".toLowerCase()) {
+ commission =
+ (double.parse(price) +
+ (double.parse(price) *
+ double.parse(
+ sectionConstantModel!.adminCommision!.amount
+ .toString(),
+ ) /
+ 100))
+ .toString();
} else {
- commission = (double.parse(price) + double.parse(sectionConstantModel!.adminCommision!.amount.toString())).toString();
+ commission =
+ (double.parse(price) +
+ double.parse(
+ sectionConstantModel!.adminCommision!.amount.toString(),
+ ))
+ .toString();
}
} else {
- if (vendorModel.adminCommission!.commissionType!.toLowerCase() == "Percent".toLowerCase() || vendorModel.adminCommission!.commissionType?.toLowerCase() == "Percentage".toLowerCase()) {
- commission = (double.parse(price) + (double.parse(price) * double.parse(vendorModel.adminCommission!.amount.toString()) / 100)).toString();
+ if (vendorModel.adminCommission!.commissionType!.toLowerCase() ==
+ "Percent".toLowerCase() ||
+ vendorModel.adminCommission!.commissionType?.toLowerCase() ==
+ "Percentage".toLowerCase()) {
+ commission =
+ (double.parse(price) +
+ (double.parse(price) *
+ double.parse(
+ vendorModel.adminCommission!.amount.toString(),
+ ) /
+ 100))
+ .toString();
} else {
- commission = (double.parse(price) + double.parse(vendorModel.adminCommission!.amount.toString())).toString();
+ commission =
+ (double.parse(price) +
+ double.parse(
+ vendorModel.adminCommission!.amount.toString(),
+ ))
+ .toString();
}
}
} else {
@@ -327,7 +373,10 @@ class Constant {
if (taxModel.type == "fix") {
taxAmount = double.parse(taxModel.tax.toString());
} else {
- taxAmount = (double.parse(amount.toString()) * double.parse(taxModel.tax!.toString())) / 100;
+ taxAmount =
+ (double.parse(amount.toString()) *
+ double.parse(taxModel.tax!.toString())) /
+ 100;
}
}
return taxAmount;
@@ -336,8 +385,12 @@ class Constant {
static double calculateDiscount({String? amount, CouponModel? offerModel}) {
double taxAmount = 0.0;
if (offerModel != null) {
- if (offerModel.discountType == "Percentage" || offerModel.discountType == "percentage") {
- taxAmount = (double.parse(amount.toString()) * double.parse(offerModel.discount.toString())) / 100;
+ if (offerModel.discountType == "Percentage" ||
+ offerModel.discountType == "percentage") {
+ taxAmount =
+ (double.parse(amount.toString()) *
+ double.parse(offerModel.discount.toString())) /
+ 100;
} else {
taxAmount = double.parse(offerModel.discount.toString());
}
@@ -345,11 +398,17 @@ class Constant {
return taxAmount;
}
- static String calculateReview({required String? reviewCount, required String? reviewSum}) {
- if (0 == double.parse(reviewSum.toString()) && 0 == double.parse(reviewSum.toString())) {
+ static String calculateReview({
+ required String? reviewCount,
+ required String? reviewSum,
+ }) {
+ if (0 == double.parse(reviewSum.toString()) &&
+ 0 == double.parse(reviewSum.toString())) {
return "0";
}
- return (double.parse(reviewSum.toString()) / double.parse(reviewCount.toString())).toStringAsFixed(1);
+ return (double.parse(reviewSum.toString()) /
+ double.parse(reviewCount.toString()))
+ .toStringAsFixed(1);
}
static String getUuid() {
@@ -357,13 +416,24 @@ class Constant {
}
static Widget loader() {
- return Center(child: CircularProgressIndicator(color: AppThemeData.primary300));
+ return Center(
+ child: CircularProgressIndicator(color: AppThemeData.primary300),
+ );
}
static Widget showEmptyView({required String message}) {
final themeController = Get.find();
final isDark = themeController.isDark.value;
- return Center(child: Text(message, style: TextStyle(fontFamily: AppThemeData.fontFamily, fontSize: 18, color: isDark ? AppThemeData.greyDark900 : AppThemeData.grey900)));
+ return Center(
+ child: Text(
+ message,
+ style: TextStyle(
+ fontFamily: AppThemeData.fontFamily,
+ fontSize: 18,
+ color: isDark ? AppThemeData.greyDark900 : AppThemeData.grey900,
+ ),
+ ),
+ );
}
static String maskingString(String documentId, int maskingDigit) {
@@ -382,7 +452,8 @@ class Constant {
}
String? validateEmail(String? value) {
- String pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
+ String pattern =
+ r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regExp = RegExp(pattern);
if (value == null || value.isEmpty) {
return "Email is Required";
@@ -393,9 +464,19 @@ class Constant {
}
}
- static String getDistance({required String lat1, required String lng1, required String lat2, required String lng2}) {
+ static String getDistance({
+ required String lat1,
+ required String lng1,
+ required String lat2,
+ required String lng2,
+ }) {
double distance;
- double distanceInMeters = Geolocator.distanceBetween(double.parse(lat1), double.parse(lng1), double.parse(lat2), double.parse(lng2));
+ double distanceInMeters = Geolocator.distanceBetween(
+ double.parse(lat1),
+ double.parse(lng1),
+ double.parse(lat2),
+ double.parse(lng2),
+ );
if (distanceType == "miles") {
distance = distanceInMeters / 1609;
} else {
@@ -405,7 +486,8 @@ class Constant {
}
bool hasValidUrl(String? value) {
- String pattern = r'(http|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?';
+ String pattern =
+ r'(http|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?';
RegExp regExp = RegExp(pattern);
if (value == null || value.isEmpty) {
return false;
@@ -415,10 +497,17 @@ class Constant {
return true;
}
- static Future uploadUserImageToFireStorage(File image, String filePath, String fileName) async {
- Reference upload = FirebaseStorage.instance.ref().child('$filePath/$fileName');
+ static Future uploadUserImageToFireStorage(
+ File image,
+ String filePath,
+ String fileName,
+ ) async {
+ Reference upload = FirebaseStorage.instance.ref().child(
+ '$filePath/$fileName',
+ );
UploadTask uploadTask = upload.putFile(image);
- var downloadUrl = await (await uploadTask.whenComplete(() {})).ref.getDownloadURL();
+ var downloadUrl =
+ await (await uploadTask.whenComplete(() {})).ref.getDownloadURL();
return downloadUrl.toString();
}
@@ -435,14 +524,22 @@ class Constant {
Future getBytesFromAsset(String path, int width) async {
ByteData data = await rootBundle.load(path);
- ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);
+ ui.Codec codec = await ui.instantiateImageCodec(
+ data.buffer.asUint8List(),
+ targetWidth: width,
+ );
ui.FrameInfo fi = await codec.getNextFrame();
- return (await fi.image.toByteData(format: ui.ImageByteFormat.png))!.buffer.asUint8List();
+ return (await fi.image.toByteData(
+ format: ui.ImageByteFormat.png,
+ ))!.buffer.asUint8List();
}
static Future selectTime(context) async {
FocusScope.of(context).requestFocus(FocusNode()); //remove focus
- TimeOfDay? newTime = await showTimePicker(context: context, initialTime: TimeOfDay.now());
+ TimeOfDay? newTime = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay.now(),
+ );
if (newTime != null) {
return newTime;
}
@@ -480,7 +577,11 @@ class Constant {
static int calculateDifference(DateTime date) {
DateTime now = DateTime.now();
- return DateTime(date.year, date.month, date.day).difference(DateTime(now.year, now.month, now.day)).inDays;
+ return DateTime(
+ date.year,
+ date.month,
+ date.day,
+ ).difference(DateTime(now.year, now.month, now.day)).inDays;
}
static String timestampToDate(Timestamp timestamp) {
@@ -509,7 +610,15 @@ class Constant {
}
static DateTime stringToDate(String openDineTime) {
- return DateFormat('HH:mm').parse(DateFormat('HH:mm').format(DateFormat("hh:mm a").parse((Intl.getCurrentLocale() == "en_US") ? openDineTime : openDineTime.toLowerCase())));
+ return DateFormat('HH:mm').parse(
+ DateFormat('HH:mm').format(
+ DateFormat("hh:mm a").parse(
+ (Intl.getCurrentLocale() == "en_US")
+ ? openDineTime
+ : openDineTime.toLowerCase(),
+ ),
+ ),
+ );
}
static LanguageModel getLanguage() {
@@ -527,7 +636,10 @@ class Constant {
int crossings = 0;
for (int i = 0; i < polygon.length; i++) {
int next = (i + 1) % polygon.length;
- if (polygon[i].latitude <= point.latitude && polygon[next].latitude > point.latitude || polygon[i].latitude > point.latitude && polygon[next].latitude <= point.latitude) {
+ if (polygon[i].latitude <= point.latitude &&
+ polygon[next].latitude > point.latitude ||
+ polygon[i].latitude > point.latitude &&
+ polygon[next].latitude <= point.latitude) {
double edgeLong = polygon[next].longitude - polygon[i].longitude;
double edgeLat = polygon[next].latitude - polygon[i].latitude;
double interpol = (point.latitude - polygon[i].latitude) / edgeLat;
@@ -549,7 +661,12 @@ class Constant {
allowInsecure: true,
);
- static Future sendMail({String? subject, String? body, bool? isAdmin = false, List? recipients}) async {
+ static Future sendMail({
+ String? subject,
+ String? body,
+ bool? isAdmin = false,
+ List? recipients,
+ }) async {
// Create our message.
if (mailSettings != null) {
if (isAdmin == true) {
@@ -557,7 +674,10 @@ class Constant {
}
final message =
Message()
- ..from = Address(mailSettings!.userName.toString(), mailSettings!.fromName.toString())
+ ..from = Address(
+ mailSettings!.userName.toString(),
+ mailSettings!.fromName.toString(),
+ )
..recipients = recipients!
..subject = subject
..text = body
@@ -581,10 +701,17 @@ class Constant {
// await connection.send(message);
}
- static Uri createCoordinatesUrl(double latitude, double longitude, [String? label]) {
+ static Uri createCoordinatesUrl(
+ double latitude,
+ double longitude, [
+ String? label,
+ ]) {
Uri uri;
if (kIsWeb) {
- uri = Uri.https('www.google.com', '/maps/search/', {'api': '1', 'query': '$latitude,$longitude'});
+ uri = Uri.https('www.google.com', '/maps/search/', {
+ 'api': '1',
+ 'query': '$latitude,$longitude',
+ });
} else if (Platform.isAndroid) {
var query = '$latitude,$longitude';
if (label != null) query += '($label)';
@@ -594,14 +721,18 @@ class Constant {
if (label != null) params['q'] = label;
uri = Uri.https('maps.apple.com', '/', params);
} else {
- uri = Uri.https('www.google.com', '/maps/search/', {'api': '1', 'query': '$latitude,$longitude'});
+ uri = Uri.https('www.google.com', '/maps/search/', {
+ 'api': '1',
+ 'query': '$latitude,$longitude',
+ });
}
return uri;
}
static Future sendOrderEmail({required OrderModel orderModel}) async {
- EmailTemplateModel? emailTemplateModel = await FireStoreUtils.getEmailTemplates(newOrderPlaced);
+ EmailTemplateModel? emailTemplateModel =
+ await FireStoreUtils.getEmailTemplates(newOrderPlaced);
if (emailTemplateModel != null) {
String firstHTML = """
@@ -618,11 +749,23 @@ class Constant {
""";
String newString = emailTemplateModel.message.toString();
- newString = newString.replaceAll("{username}", "${Constant.userModel!.firstName} ${Constant.userModel!.lastName}");
+ newString = newString.replaceAll(
+ "{username}",
+ "${Constant.userModel!.firstName} ${Constant.userModel!.lastName}",
+ );
newString = newString.replaceAll("{orderid}", orderModel.id.toString());
- newString = newString.replaceAll("{date}", DateFormat('yyyy-MM-dd').format(orderModel.createdAt!.toDate()));
- newString = newString.replaceAll("{address}", orderModel.address!.getFullAddress());
- newString = newString.replaceAll("{paymentmethod}", orderModel.paymentMethod.toString());
+ newString = newString.replaceAll(
+ "{date}",
+ DateFormat('yyyy-MM-dd').format(orderModel.createdAt!.toDate()),
+ );
+ newString = newString.replaceAll(
+ "{address}",
+ orderModel.address!.getFullAddress(),
+ );
+ newString = newString.replaceAll(
+ "{paymentmethod}",
+ orderModel.paymentMethod.toString(),
+ );
double deliveryCharge = 0.0;
double total = 0.0;
@@ -630,7 +773,8 @@ class Constant {
double discount = 0.0;
double taxAmount = 0.0;
double tipValue = 0.0;
- String specialLabel = '(${orderModel.specialDiscount!['special_discount_label']}${orderModel.specialDiscount!['specialType'] == "amount" ? currencyModel!.symbol : "%"})';
+ String specialLabel =
+ '(${orderModel.specialDiscount!['special_discount_label']}${orderModel.specialDiscount!['specialType'] == "amount" ? currencyModel!.symbol : "%"})';
List htmlList = [];
if (orderModel.deliveryCharge != null) {
@@ -640,15 +784,22 @@ class Constant {
tipValue = double.parse(orderModel.tipAmount.toString());
}
for (var element in orderModel.products!) {
- if (element.extrasPrice != null && element.extrasPrice!.isNotEmpty && double.parse(element.extrasPrice!) != 0.0) {
- total += double.parse(element.quantity.toString()) * double.parse(element.extrasPrice!);
+ if (element.extrasPrice != null &&
+ element.extrasPrice!.isNotEmpty &&
+ double.parse(element.extrasPrice!) != 0.0) {
+ total +=
+ double.parse(element.quantity.toString()) *
+ double.parse(element.extrasPrice!);
}
- total += double.parse(element.quantity.toString()) * double.parse(element.price.toString());
+ total +=
+ double.parse(element.quantity.toString()) *
+ double.parse(element.price.toString());
List? addon = element.extras;
String extrasDisVal = '';
for (int i = 0; i < addon!.length; i++) {
- extrasDisVal += '${addon[i].toString().replaceAll("\"", "")} ${(i == addon.length - 1) ? "" : ","}';
+ extrasDisVal +=
+ '${addon[i].toString().replaceAll("\"", "")} ${(i == addon.length - 1) ? "" : ","}';
}
String product = """
@@ -666,7 +817,9 @@ class Constant {
}
if (orderModel.specialDiscount!.isNotEmpty) {
- specialDiscount = double.parse(orderModel.specialDiscount!['special_discount'].toString());
+ specialDiscount = double.parse(
+ orderModel.specialDiscount!['special_discount'].toString(),
+ );
}
if (orderModel.couponId != null && orderModel.couponId!.isNotEmpty) {
@@ -675,35 +828,81 @@ class Constant {
List taxHtmlList = [];
for (var element in taxList) {
- taxAmount = taxAmount + calculateTax(amount: (total - discount - specialDiscount).toString(), taxModel: element);
+ taxAmount =
+ taxAmount +
+ calculateTax(
+ amount: (total - discount - specialDiscount).toString(),
+ taxModel: element,
+ );
String taxHtml =
"""${element.title}: ${amountShow(amount: calculateTax(amount: (total - discount - specialDiscount).toString(), taxModel: element).toString())}${taxList.indexOf(element) == taxList.length - 1 ? "" : "
"}""";
taxHtmlList.add(taxHtml);
}
var totalamount =
- orderModel.deliveryCharge == null || orderModel.deliveryCharge!.isEmpty
+ orderModel.deliveryCharge == null ||
+ orderModel.deliveryCharge!.isEmpty
? total + taxAmount - discount - specialDiscount
- : total + taxAmount + double.parse(orderModel.deliveryCharge!) + double.parse(orderModel.tipAmount!) - discount - specialDiscount;
+ : total +
+ taxAmount +
+ double.parse(orderModel.deliveryCharge!) +
+ double.parse(orderModel.tipAmount!) -
+ discount -
+ specialDiscount;
- newString = newString.replaceAll("{subtotal}", amountShow(amount: total.toString()));
- newString = newString.replaceAll("{coupon}", orderModel.couponId.toString());
- newString = newString.replaceAll("{discountamount}", amountShow(amount: orderModel.discount.toString()));
+ newString = newString.replaceAll(
+ "{subtotal}",
+ amountShow(amount: total.toString()),
+ );
+ newString = newString.replaceAll(
+ "{coupon}",
+ orderModel.couponId.toString(),
+ );
+ newString = newString.replaceAll(
+ "{discountamount}",
+ amountShow(amount: orderModel.discount.toString()),
+ );
newString = newString.replaceAll("{specialcoupon}", specialLabel);
- newString = newString.replaceAll("{specialdiscountamount}", amountShow(amount: specialDiscount.toString()));
- newString = newString.replaceAll("{shippingcharge}", amountShow(amount: deliveryCharge.toString()));
- newString = newString.replaceAll("{tipamount}", amountShow(amount: tipValue.toString()));
- newString = newString.replaceAll("{totalAmount}", amountShow(amount: totalamount.toString()));
+ newString = newString.replaceAll(
+ "{specialdiscountamount}",
+ amountShow(amount: specialDiscount.toString()),
+ );
+ newString = newString.replaceAll(
+ "{shippingcharge}",
+ amountShow(amount: deliveryCharge.toString()),
+ );
+ newString = newString.replaceAll(
+ "{tipamount}",
+ amountShow(amount: tipValue.toString()),
+ );
+ newString = newString.replaceAll(
+ "{totalAmount}",
+ amountShow(amount: totalamount.toString()),
+ );
String tableHTML = htmlList.join();
String lastHTML = "
";
- newString = newString.replaceAll("{productdetails}", firstHTML + tableHTML + lastHTML);
+ newString = newString.replaceAll(
+ "{productdetails}",
+ firstHTML + tableHTML + lastHTML,
+ );
newString = newString.replaceAll("{taxdetails}", taxHtmlList.join());
- newString = newString.replaceAll("{newwalletbalance}.", amountShow(amount: Constant.userModel!.walletAmount.toString()));
+ newString = newString.replaceAll(
+ "{newwalletbalance}.",
+ amountShow(amount: Constant.userModel!.walletAmount.toString()),
+ );
String subjectNewString = emailTemplateModel.subject.toString();
- subjectNewString = subjectNewString.replaceAll("{orderid}", orderModel.id.toString());
- await sendMail(subject: subjectNewString, isAdmin: emailTemplateModel.isSendToAdmin, body: newString, recipients: [Constant.userModel!.email]);
+ subjectNewString = subjectNewString.replaceAll(
+ "{orderid}",
+ orderModel.id.toString(),
+ );
+ await sendMail(
+ subject: subjectNewString,
+ isAdmin: emailTemplateModel.isSendToAdmin,
+ body: newString,
+ recipients: [Constant.userModel!.email],
+ );
}
}
@@ -711,7 +910,12 @@ class Constant {
const R = 6371; // Earth's radius in km
final dLat = _degToRad(lat2 - lat1);
final dLon = _degToRad(lon2 - lon1);
- final a = sin(dLat / 2) * sin(dLat / 2) + cos(_degToRad(lat1)) * cos(_degToRad(lat2)) * sin(dLon / 2) * sin(dLon / 2);
+ final a =
+ sin(dLat / 2) * sin(dLat / 2) +
+ cos(_degToRad(lat1)) *
+ cos(_degToRad(lat2)) *
+ sin(dLon / 2) *
+ sin(dLon / 2);
final c = 2 * atan2(sqrt(a), sqrt(1 - a));
return R * c;
}
@@ -725,13 +929,19 @@ class Constant {
}
/// Calculate tax amount for a single tax model
- static double getTaxValue({required String amount, required TaxModel taxModel}) {
+ static double getTaxValue({
+ required String amount,
+ required TaxModel taxModel,
+ }) {
double taxVal = 0.0;
if (taxModel.enable == true) {
if (taxModel.type == "fix") {
taxVal = double.tryParse(taxModel.tax.toString()) ?? 0.0;
} else {
- taxVal = (double.tryParse(amount) ?? 0.0) * (double.tryParse(taxModel.tax.toString()) ?? 0.0) / 100;
+ taxVal =
+ (double.tryParse(amount) ?? 0.0) *
+ (double.tryParse(taxModel.tax.toString()) ?? 0.0) /
+ 100;
}
}
return taxVal;
@@ -743,10 +953,15 @@ class Constant {
if (response.statusCode != 200) throw Exception("Failed to load image");
final Uint8List bytes = response.bodyBytes;
- final ui.Codec codec = await ui.instantiateImageCodec(bytes, targetWidth: width);
+ final ui.Codec codec = await ui.instantiateImageCodec(
+ bytes,
+ targetWidth: width,
+ );
final ui.FrameInfo frameInfo = await codec.getNextFrame();
- final ByteData? byteData = await frameInfo.image.toByteData(format: ui.ImageByteFormat.png);
+ final ByteData? byteData = await frameInfo.image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
return byteData!.buffer.asUint8List();
} catch (e) {
print("⚠️ getBytesFromUrl error: $e — using default cab icon");
diff --git a/lib/controllers/0n_demand_payment_controller.dart b/lib/controllers/0n_demand_payment_controller.dart
index 6a8e3cd..e53d848 100644
--- a/lib/controllers/0n_demand_payment_controller.dart
+++ b/lib/controllers/0n_demand_payment_controller.dart
@@ -1,7 +1,7 @@
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:easy_localization/easy_localization.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:http/http.dart' as http;
import '../../models/onprovider_order_model.dart';
import '../models/wallet_transaction_model.dart';
@@ -48,7 +48,9 @@ import '../utils/preferences.dart';
import 'on_demand_dashboard_controller.dart';
class OnDemandPaymentController extends GetxController {
- Rx onDemandOrderModel = Rx(null);
+ Rx onDemandOrderModel = Rx(
+ null,
+ );
RxDouble totalAmount = 0.0.obs;
late bool isExtra;
@@ -76,19 +78,37 @@ class OnDemandPaymentController extends GetxController {
ShowToastDialog.showLoader("Please wait...".tr());
onDemandOrderModel.value?.payment_method = selectedPaymentMethod.value;
- onDemandOrderModel.value?.paymentStatus = onDemandOrderModel.value?.provider.priceUnit == "Fixed" && selectedPaymentMethod.value == "cod" ? false : true;
+ onDemandOrderModel.value?.paymentStatus =
+ onDemandOrderModel.value?.provider.priceUnit == "Fixed" &&
+ selectedPaymentMethod.value == "cod"
+ ? false
+ : true;
onDemandOrderModel.value?.extraPaymentStatus = true;
- await FireStoreUtils.onDemandOrderPlace(onDemandOrderModel.value!, totalAmount.value);
+ await FireStoreUtils.onDemandOrderPlace(
+ onDemandOrderModel.value!,
+ totalAmount.value,
+ );
if (onDemandOrderModel.value?.status == Constant.orderPlaced) {
- await FireStoreUtils.sendOrderOnDemandServiceEmail(orderModel: onDemandOrderModel.value!);
+ await FireStoreUtils.sendOrderOnDemandServiceEmail(
+ orderModel: onDemandOrderModel.value!,
+ );
- final providerUser = await FireStoreUtils.getUserProfile(onDemandOrderModel.value!.provider.author!);
+ final providerUser = await FireStoreUtils.getUserProfile(
+ onDemandOrderModel.value!.provider.author!,
+ );
if (providerUser != null) {
- final payLoad = {"type": 'provider_order', "orderId": onDemandOrderModel.value?.id};
- await SendNotification.sendFcmMessage(Constant.bookingPlaced, providerUser.fcmToken ?? '', payLoad);
+ final payLoad = {
+ "type": 'provider_order',
+ "orderId": onDemandOrderModel.value?.id,
+ };
+ await SendNotification.sendFcmMessage(
+ Constant.bookingPlaced,
+ providerUser.fcmToken ?? '',
+ payLoad,
+ );
}
ShowToastDialog.showToast("OnDemand Service successfully booked".tr());
@@ -107,16 +127,23 @@ class OnDemandPaymentController extends GetxController {
paymentStatus: "success".tr(),
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-${totalAmount.value.toString()}", userId: FireStoreUtils.getCurrentUid()).then((value) {});
+ await FireStoreUtils.updateUserWallet(
+ amount: "-${totalAmount.value.toString()}",
+ userId: FireStoreUtils.getCurrentUid(),
+ ).then((value) {});
}
});
}
ShowToastDialog.closeLoader();
Get.offAll(const OnDemandDashboardScreen());
- OnDemandDashboardController controller = Get.put(OnDemandDashboardController());
+ OnDemandDashboardController controller = Get.put(
+ OnDemandDashboardController(),
+ );
controller.selectedIndex.value = 2;
} else {
// Extra Charges Flow
@@ -137,9 +164,14 @@ class OnDemandPaymentController extends GetxController {
paymentStatus: "success".tr(),
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-${totalAmount.value.toString()}", userId: FireStoreUtils.getCurrentUid()).then((value) {});
+ await FireStoreUtils.updateUserWallet(
+ amount: "-${totalAmount.value.toString()}",
+ userId: FireStoreUtils.getCurrentUid(),
+ ).then((value) {});
}
});
}
@@ -160,9 +192,14 @@ class OnDemandPaymentController extends GetxController {
paymentStatus: "success".tr(),
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-$totalAmount", userId: FireStoreUtils.getCurrentUid());
+ await FireStoreUtils.updateUserWallet(
+ amount: "-$totalAmount",
+ userId: FireStoreUtils.getCurrentUid(),
+ );
}
});
}
@@ -171,7 +208,9 @@ class OnDemandPaymentController extends GetxController {
ShowToastDialog.closeLoader();
Get.offAll(const OnDemandDashboardScreen());
- OnDemandDashboardController controller = Get.put(OnDemandDashboardController());
+ OnDemandDashboardController controller = Get.put(
+ OnDemandDashboardController(),
+ );
controller.selectedIndex.value = 2;
}
}
@@ -194,19 +233,45 @@ class OnDemandPaymentController extends GetxController {
Future getPaymentSettings() async {
isLoading.value = true;
await FireStoreUtils.getPaymentSettingsData().then((value) {
- stripeModel.value = StripeModel.fromJson(jsonDecode(Preferences.getString(Preferences.stripeSettings)));
- payPalModel.value = PayPalModel.fromJson(jsonDecode(Preferences.getString(Preferences.paypalSettings)));
- payStackModel.value = PayStackModel.fromJson(jsonDecode(Preferences.getString(Preferences.payStack)));
- mercadoPagoModel.value = MercadoPagoModel.fromJson(jsonDecode(Preferences.getString(Preferences.mercadoPago)));
- flutterWaveModel.value = FlutterWaveModel.fromJson(jsonDecode(Preferences.getString(Preferences.flutterWave)));
- paytmModel.value = PaytmModel.fromJson(jsonDecode(Preferences.getString(Preferences.paytmSettings)));
- payFastModel.value = PayFastModel.fromJson(jsonDecode(Preferences.getString(Preferences.payFastSettings)));
- razorPayModel.value = RazorPayModel.fromJson(jsonDecode(Preferences.getString(Preferences.razorpaySettings)));
- midTransModel.value = MidTrans.fromJson(jsonDecode(Preferences.getString(Preferences.midTransSettings)));
- orangeMoneyModel.value = OrangeMoney.fromJson(jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)));
- xenditModel.value = Xendit.fromJson(jsonDecode(Preferences.getString(Preferences.xenditSettings)));
- walletSettingModel.value = WalletSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.walletSettings)));
- cashOnDeliverySettingModel.value = CodSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.codSettings)));
+ stripeModel.value = StripeModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.stripeSettings)),
+ );
+ payPalModel.value = PayPalModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paypalSettings)),
+ );
+ payStackModel.value = PayStackModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payStack)),
+ );
+ mercadoPagoModel.value = MercadoPagoModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.mercadoPago)),
+ );
+ flutterWaveModel.value = FlutterWaveModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.flutterWave)),
+ );
+ paytmModel.value = PaytmModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paytmSettings)),
+ );
+ payFastModel.value = PayFastModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payFastSettings)),
+ );
+ razorPayModel.value = RazorPayModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.razorpaySettings)),
+ );
+ midTransModel.value = MidTrans.fromJson(
+ jsonDecode(Preferences.getString(Preferences.midTransSettings)),
+ );
+ orangeMoneyModel.value = OrangeMoney.fromJson(
+ jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)),
+ );
+ xenditModel.value = Xendit.fromJson(
+ jsonDecode(Preferences.getString(Preferences.xenditSettings)),
+ );
+ walletSettingModel.value = WalletSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.walletSettings)),
+ );
+ cashOnDeliverySettingModel.value = CodSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.codSettings)),
+ );
if (walletSettingModel.value.isEnabled == true) {
selectedPaymentMethod.value = PaymentGateway.wallet.name;
@@ -249,20 +314,32 @@ class OnDemandPaymentController extends GetxController {
Future stripeMakePayment({required String amount}) async {
log(double.parse(amount).toStringAsFixed(0));
try {
- Map? paymentIntentData = await createStripeIntent(amount: amount);
+ Map? paymentIntentData = await createStripeIntent(
+ amount: amount,
+ );
log("stripe Responce====>$paymentIntentData");
if (paymentIntentData!.containsKey("error")) {
Get.back();
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
} else {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentData['client_secret'],
allowsDelayedPaymentMethods: false,
- googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'US', testEnv: true, currencyCode: "USD"),
+ googlePay: const PaymentSheetGooglePay(
+ merchantCountryCode: 'US',
+ testEnv: true,
+ currencyCode: "USD",
+ ),
customFlow: true,
style: ThemeMode.system,
- appearance: PaymentSheetAppearance(colors: PaymentSheetAppearanceColors(primary: AppThemeData.primary300)),
+ appearance: PaymentSheetAppearance(
+ colors: PaymentSheetAppearanceColors(
+ primary: AppThemeData.primary300,
+ ),
+ ),
merchantDisplayName: 'GoRide',
),
);
@@ -308,7 +385,10 @@ class OnDemandPaymentController extends GetxController {
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
body: body,
- headers: {'Authorization': 'Bearer $stripeSecret', 'Content-Type': 'application/x-www-form-urlencoded'},
+ headers: {
+ 'Authorization': 'Bearer $stripeSecret',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
);
return jsonDecode(response.body);
@@ -318,8 +398,14 @@ class OnDemandPaymentController extends GetxController {
}
//mercadoo
- Future mercadoPagoMakePayment({required BuildContext context, required String amount}) async {
- final headers = {'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}', 'Content-Type': 'application/json'};
+ Future mercadoPagoMakePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
+ final headers = {
+ 'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"items": [
@@ -332,12 +418,20 @@ class OnDemandPaymentController extends GetxController {
},
],
"payer": {"email": Constant.userModel?.email},
- "back_urls": {"failure": "${Constant.globalUrl}payment/failure", "pending": "${Constant.globalUrl}payment/pending", "success": "${Constant.globalUrl}payment/success"},
+ "back_urls": {
+ "failure": "${Constant.globalUrl}payment/failure",
+ "pending": "${Constant.globalUrl}payment/pending",
+ "success": "${Constant.globalUrl}payment/success",
+ },
"auto_return": "approved",
// Automatically return after payment is approved
});
- final response = await http.post(Uri.parse("https://api.mercadopago.com/checkout/preferences"), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse("https://api.mercadopago.com/checkout/preferences"),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
final data = jsonDecode(response.body);
@@ -420,15 +514,23 @@ class OnDemandPaymentController extends GetxController {
}
});
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
}
});
}
//flutter wave Payment Method
- Future flutterWaveInitiatePayment({required BuildContext context, required String amount}) async {
+ Future flutterWaveInitiatePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
final url = Uri.parse('https://api.flutterwave.com/v3/payments');
- final headers = {'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}', 'Content-Type': 'application/json'};
+ final headers = {
+ 'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"tx_ref": _ref,
@@ -436,15 +538,24 @@ class OnDemandPaymentController extends GetxController {
"currency": "NGN",
"redirect_url": "${Constant.globalUrl}payment/success",
"payment_options": "ussd, card, barter, payattitude",
- "customer": {"email": Constant.userModel?.email.toString(), "phonenumber": Constant.userModel?.phoneNumber, "name": Constant.userModel?.fullName()},
- "customizations": {"title": "Payment for Services", "description": "Payment for XYZ services"},
+ "customer": {
+ "email": Constant.userModel?.email.toString(),
+ "phonenumber": Constant.userModel?.phoneNumber,
+ "name": Constant.userModel?.fullName(),
+ },
+ "customizations": {
+ "title": "Payment for Services",
+ "description": "Payment for XYZ services",
+ },
});
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
- Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((value) {
+ Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((
+ value,
+ ) {
if (value) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -473,8 +584,14 @@ class OnDemandPaymentController extends GetxController {
// payFast
void payFastPayment({required BuildContext context, required String amount}) {
- PayStackURLGen.getPayHTML(payFastSettingData: payFastModel.value, amount: amount.toString(), userModel: Constant.userModel!).then((String? value) async {
- bool isDone = await Get.to(PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value));
+ PayStackURLGen.getPayHTML(
+ payFastSettingData: payFastModel.value,
+ amount: amount.toString(),
+ userModel: Constant.userModel!,
+ ).then((String? value) async {
+ bool isDone = await Get.to(
+ PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value),
+ );
if (isDone) {
Get.back();
ShowToastDialog.showToast("Payment successfully".tr());
@@ -494,26 +611,50 @@ class OnDemandPaymentController extends GetxController {
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString()},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ },
);
final data = jsonDecode(response.body);
- await verifyCheckSum(checkSum: data["code"], amount: amount, orderId: orderId).then((value) {
+ await verifyCheckSum(
+ checkSum: data["code"],
+ amount: amount,
+ orderId: orderId,
+ ).then((value) {
initiatePayment(amount: amount, orderId: orderId).then((value) {
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
GetPaymentTxtTokenModel result = value;
- startTransaction(context, txnTokenBy: result.body.txnToken ?? '', orderId: orderId, amount: amount, callBackURL: callback, isStaging: paytmModel.value.isSandboxEnabled);
+ startTransaction(
+ context,
+ txnTokenBy: result.body.txnToken ?? '',
+ orderId: orderId,
+ amount: amount,
+ callBackURL: callback,
+ isStaging: paytmModel.value.isSandboxEnabled,
+ );
});
});
}
- Future startTransaction(context, {required String txnTokenBy, required orderId, required double amount, required callBackURL, required isStaging}) async {
+ Future startTransaction(
+ context, {
+ required String txnTokenBy,
+ required orderId,
+ required double amount,
+ required callBackURL,
+ required isStaging,
+ }) async {
// try {
// var response = AllInOneSdk.startTransaction(
// paytmModel.value.paytmMID.toString(),
@@ -549,24 +690,38 @@ class OnDemandPaymentController extends GetxController {
// }
}
- Future verifyCheckSum({required String checkSum, required double amount, required orderId}) async {
+ Future verifyCheckSum({
+ required String checkSum,
+ required double amount,
+ required orderId,
+ }) async {
String getChecksum = "${Constant.globalUrl}payments/validatechecksum";
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(), "checksum_value": checkSum},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ "checksum_value": checkSum,
+ },
);
final data = jsonDecode(response.body);
return data['status'];
}
- Future initiatePayment({required double amount, required orderId}) async {
+ Future initiatePayment({
+ required double amount,
+ required orderId,
+ }) async {
String initiateURL = "${Constant.globalUrl}payments/initiatepaytmpayment";
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
final response = await http.post(
Uri.parse(initiateURL),
@@ -584,9 +739,12 @@ class OnDemandPaymentController extends GetxController {
);
log(response.body);
final data = jsonDecode(response.body);
- if (data["body"]["txnToken"] == null || data["body"]["txnToken"].toString().isEmpty) {
+ if (data["body"]["txnToken"] == null ||
+ data["body"]["txnToken"].toString().isEmpty) {
Get.back();
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
}
return GetPaymentTxtTokenModel.fromJson(data);
}
@@ -604,7 +762,10 @@ class OnDemandPaymentController extends GetxController {
'description': 'wallet Topup',
'retry': {'enabled': true, 'max_count': 1},
'send_sms_hash': true,
- 'prefill': {'contact': Constant.userModel?.phoneNumber, 'email': Constant.userModel?.email},
+ 'prefill': {
+ 'contact': Constant.userModel?.phoneNumber,
+ 'email': Constant.userModel?.email,
+ },
'external': {
'wallets': ['paytm'],
},
@@ -639,7 +800,10 @@ class OnDemandPaymentController extends GetxController {
}
//Midtrans payment
- Future midtransMakePayment({required String amount, required BuildContext context}) async {
+ Future midtransMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
await createPaymentLink(amount: amount).then((url) {
ShowToastDialog.closeLoader();
if (url != '') {
@@ -657,15 +821,30 @@ class OnDemandPaymentController extends GetxController {
Future createPaymentLink({required var amount}) async {
var ordersId = const Uuid().v1();
- final url = Uri.parse(midTransModel.value.isSandbox! ? 'https://api.sandbox.midtrans.com/v1/payment-links' : 'https://api.midtrans.com/v1/payment-links');
+ final url = Uri.parse(
+ midTransModel.value.isSandbox!
+ ? 'https://api.sandbox.midtrans.com/v1/payment-links'
+ : 'https://api.midtrans.com/v1/payment-links',
+ );
final response = await http.post(
url,
- headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': generateBasicAuthHeader(midTransModel.value.serverKey!)},
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ 'Authorization': generateBasicAuthHeader(
+ midTransModel.value.serverKey!,
+ ),
+ },
body: jsonEncode({
- 'transaction_details': {'order_id': ordersId, 'gross_amount': double.parse(amount.toString()).toInt()},
+ 'transaction_details': {
+ 'order_id': ordersId,
+ 'gross_amount': double.parse(amount.toString()).toInt(),
+ },
'usage_limit': 2,
- "callbacks": {"finish": "https://www.google.com?merchant_order_id=$ordersId"},
+ "callbacks": {
+ "finish": "https://www.google.com?merchant_order_id=$ordersId",
+ },
}),
);
@@ -673,7 +852,9 @@ class OnDemandPaymentController extends GetxController {
final responseData = jsonDecode(response.body);
return responseData['payment_url'];
} else {
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -692,16 +873,33 @@ class OnDemandPaymentController extends GetxController {
static String orderId = '';
static String amount = '';
- Future orangeMakePayment({required String amount, required BuildContext context}) async {
+ Future orangeMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
reset();
var id = const Uuid().v4();
- var paymentURL = await fetchToken(context: context, orderId: id, amount: amount, currency: 'USD');
+ var paymentURL = await fetchToken(
+ context: context,
+ orderId: id,
+ amount: amount,
+ currency: 'USD',
+ );
ShowToastDialog.closeLoader();
if (paymentURL.toString().isNotEmpty) {
- Get.to(() => OrangeMoneyScreen(initialURl: paymentURL, accessToken: accessToken, amount: amount, orangePay: orangeMoneyModel.value, orderId: orderId, payToken: payToken))!.then((value) {
+ Get.to(
+ () => OrangeMoneyScreen(
+ initialURl: paymentURL,
+ accessToken: accessToken,
+ amount: amount,
+ orangePay: orangeMoneyModel.value,
+ orderId: orderId,
+ payToken: payToken,
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -712,13 +910,22 @@ class OnDemandPaymentController extends GetxController {
}
}
- Future fetchToken({required String orderId, required String currency, required BuildContext context, required String amount}) async {
+ Future fetchToken({
+ required String orderId,
+ required String currency,
+ required BuildContext context,
+ required String amount,
+ }) async {
String apiUrl = 'https://api.orange.com/oauth/v3/token';
Map requestBody = {'grant_type': 'client_credentials'};
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': "Basic ${orangeMoneyModel.value.auth ?? ''}", 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': "Basic ${orangeMoneyModel.value.auth ?? ''}",
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Accept': 'application/json',
+ },
body: requestBody,
);
@@ -731,21 +938,36 @@ class OnDemandPaymentController extends GetxController {
return '';
}
- return await webpayment(context: context, amountData: amount, currency: currency, orderIdData: orderId);
+ return await webpayment(
+ context: context,
+ amountData: amount,
+ currency: currency,
+ orderIdData: orderId,
+ );
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
- Future webpayment({required String orderIdData, required BuildContext context, required String currency, required String amountData}) async {
+ Future webpayment({
+ required String orderIdData,
+ required BuildContext context,
+ required String currency,
+ required String amountData,
+ }) async {
orderId = orderIdData;
amount = amountData;
// ✅ Null-safe handling
bool isSandbox = orangeMoneyModel.value.isSandbox ?? false;
- String apiUrl = isSandbox ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment' : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
+ String apiUrl =
+ isSandbox
+ ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment'
+ : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
Map requestBody = {
"merchant_key": orangeMoneyModel.value.merchantKey ?? '',
@@ -761,7 +983,11 @@ class OnDemandPaymentController extends GetxController {
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': 'Bearer $accessToken',
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ },
body: json.encode(requestBody),
);
@@ -774,7 +1000,9 @@ class OnDemandPaymentController extends GetxController {
return '';
}
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -888,7 +1116,13 @@ class OnDemandPaymentController extends GetxController {
await createXenditInvoice(amount: amount).then((model) {
ShowToastDialog.closeLoader();
if (model.id != null) {
- Get.to(() => XenditScreen(initialURl: model.invoiceUrl ?? '', transId: model.id ?? '', apiKey: xenditModel.value.apiKey!.toString()))!.then((value) {
+ Get.to(
+ () => XenditScreen(
+ initialURl: model.invoiceUrl ?? '',
+ transId: model.id ?? '',
+ apiKey: xenditModel.value.apiKey!.toString(),
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -905,7 +1139,9 @@ class OnDemandPaymentController extends GetxController {
const url = 'https://api.xendit.co/v2/invoices';
var headers = {
'Content-Type': 'application/json',
- 'Authorization': generateBasicAuthHeader(xenditModel.value.apiKey!.toString()),
+ 'Authorization': generateBasicAuthHeader(
+ xenditModel.value.apiKey!.toString(),
+ ),
// 'Cookie': '__cf_bm=yERkrx3xDITyFGiou0bbKY1bi7xEwovHNwxV1vCNbVc-1724155511-1.0.1.1-jekyYQmPCwY6vIJ524K0V6_CEw6O.dAwOmQnHtwmaXO_MfTrdnmZMka0KZvjukQgXu5B.K_6FJm47SGOPeWviQ',
};
@@ -918,7 +1154,11 @@ class OnDemandPaymentController extends GetxController {
});
try {
- final response = await http.post(Uri.parse(url), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse(url),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
XenditModel model = XenditModel.fromJson(jsonDecode(response.body));
diff --git a/lib/controllers/Intercity_home_controller.dart b/lib/controllers/Intercity_home_controller.dart
index 20fef19..ba768de 100644
--- a/lib/controllers/Intercity_home_controller.dart
+++ b/lib/controllers/Intercity_home_controller.dart
@@ -48,7 +48,7 @@ import 'package:flutter_map/flutter_map.dart' as flutterMap;
import 'package:flutter_paypal/flutter_paypal.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:latlong2/latlong.dart' as latlong;
@@ -65,10 +65,13 @@ class IntercityHomeController extends GetxController {
late GoogleMapController mapController;
final flutterMap.MapController mapOsmController = flutterMap.MapController();
- final Rx sourceTextEditController = TextEditingController().obs;
- final Rx destinationTextEditController = TextEditingController().obs;
+ final Rx sourceTextEditController =
+ TextEditingController().obs;
+ final Rx destinationTextEditController =
+ TextEditingController().obs;
- final Rx couponCodeTextEditController = TextEditingController().obs;
+ final Rx couponCodeTextEditController =
+ TextEditingController().obs;
final Rx currentLocation = Location().obs;
@@ -142,64 +145,99 @@ class IntercityHomeController extends GetxController {
await getPaymentSettings();
- FireStoreUtils.fireStore.collection(CollectionName.users).doc(FireStoreUtils.getCurrentUid()).snapshots().listen((userSnapshot) async {
- if (!userSnapshot.exists) return;
+ FireStoreUtils.fireStore
+ .collection(CollectionName.users)
+ .doc(FireStoreUtils.getCurrentUid())
+ .snapshots()
+ .listen((userSnapshot) async {
+ if (!userSnapshot.exists) return;
- userModel.value = UserModel.fromJson(userSnapshot.data()!);
+ userModel.value = UserModel.fromJson(userSnapshot.data()!);
- if (userModel.value.inProgressOrderID != null && userModel.value.inProgressOrderID!.isNotEmpty) {
- String? validRideId;
+ if (userModel.value.inProgressOrderID != null &&
+ userModel.value.inProgressOrderID!.isNotEmpty) {
+ String? validRideId;
- for (String id in userModel.value.inProgressOrderID!) {
- final rideDoc = await FireStoreUtils.fireStore.collection(CollectionName.rides).doc(id).get();
+ for (String id in userModel.value.inProgressOrderID!) {
+ final rideDoc =
+ await FireStoreUtils.fireStore
+ .collection(CollectionName.rides)
+ .doc(id)
+ .get();
- if (rideDoc.exists && (rideDoc.data()?['rideType'] ?? '').toString().toLowerCase() == "intercity") {
- validRideId = userModel.value.inProgressOrderID!.first!;
- break;
- }
- }
-
- FireStoreUtils.fireStore.collection(CollectionName.rides).doc(validRideId).snapshots().listen((rideSnapshot) async {
- if (!rideSnapshot.exists) return;
-
- final rideData = rideSnapshot.data()!;
- currentOrder.value = CabOrderModel.fromJson(rideData);
- final status = currentOrder.value.status;
-
- if (status == Constant.driverAccepted || status == Constant.orderInTransit) {
- FireStoreUtils.fireStore.collection(CollectionName.users).doc(currentOrder.value.driverId).snapshots().listen((event) async {
- if (event.exists && event.data() != null) {
- UserModel driverModel0 = UserModel.fromJson(event.data()!);
- driverModel.value = driverModel0;
- await updateDriverRoute(driverModel0);
+ if (rideDoc.exists &&
+ (rideDoc.data()?['rideType'] ?? '')
+ .toString()
+ .toLowerCase() ==
+ "intercity") {
+ validRideId = userModel.value.inProgressOrderID!.first!;
+ break;
}
- });
- }
+ }
- print("Current Ride Status: $status");
- if (status == Constant.orderPlaced || status == Constant.driverPending || status == Constant.driverRejected || (status == Constant.orderAccepted && currentOrder.value.driverId == null)) {
- bottomSheetType.value = 'waitingForDriver';
- } else if (status == Constant.driverAccepted || status == Constant.orderInTransit) {
- bottomSheetType.value = 'driverDetails';
- sourceTextEditController.value.text = currentOrder.value.sourceLocationName ?? '';
- destinationTextEditController.value.text = currentOrder.value.destinationLocationName ?? '';
- selectedPaymentMethod.value = currentOrder.value.paymentMethod ?? '';
- calculateTotalAmountAfterAccept();
- } else if (status == Constant.orderCompleted) {
- userModel.value.inProgressOrderID!.remove(validRideId);
- await FireStoreUtils.updateUser(userModel.value);
+ FireStoreUtils.fireStore
+ .collection(CollectionName.rides)
+ .doc(validRideId)
+ .snapshots()
+ .listen((rideSnapshot) async {
+ if (!rideSnapshot.exists) return;
+
+ final rideData = rideSnapshot.data()!;
+ currentOrder.value = CabOrderModel.fromJson(rideData);
+ final status = currentOrder.value.status;
+
+ if (status == Constant.driverAccepted ||
+ status == Constant.orderInTransit) {
+ FireStoreUtils.fireStore
+ .collection(CollectionName.users)
+ .doc(currentOrder.value.driverId)
+ .snapshots()
+ .listen((event) async {
+ if (event.exists && event.data() != null) {
+ UserModel driverModel0 = UserModel.fromJson(
+ event.data()!,
+ );
+ driverModel.value = driverModel0;
+ await updateDriverRoute(driverModel0);
+ }
+ });
+ }
+
+ print("Current Ride Status: $status");
+ if (status == Constant.orderPlaced ||
+ status == Constant.driverPending ||
+ status == Constant.driverRejected ||
+ (status == Constant.orderAccepted &&
+ currentOrder.value.driverId == null)) {
+ bottomSheetType.value = 'waitingForDriver';
+ } else if (status == Constant.driverAccepted ||
+ status == Constant.orderInTransit) {
+ bottomSheetType.value = 'driverDetails';
+ sourceTextEditController.value.text =
+ currentOrder.value.sourceLocationName ?? '';
+ destinationTextEditController.value.text =
+ currentOrder.value.destinationLocationName ?? '';
+ selectedPaymentMethod.value =
+ currentOrder.value.paymentMethod ?? '';
+ calculateTotalAmountAfterAccept();
+ } else if (status == Constant.orderCompleted) {
+ userModel.value.inProgressOrderID!.remove(validRideId);
+ await FireStoreUtils.updateUser(userModel.value);
+ bottomSheetType.value = 'location';
+ Get.back();
+ }
+ });
+ } else {
bottomSheetType.value = 'location';
- Get.back();
+ if (Constant.currentLocation != null) {
+ setDepartureMarker(
+ Constant.currentLocation!.latitude,
+ Constant.currentLocation!.longitude,
+ );
+ searchPlaceNameOSM();
+ }
}
});
- } else {
- bottomSheetType.value = 'location';
- if (Constant.currentLocation != null) {
- setDepartureMarker(Constant.currentLocation!.latitude, Constant.currentLocation!.longitude);
- searchPlaceNameOSM();
- }
- }
- });
final coupons = await FireStoreUtils.getCabCoupon();
cabCouponList.value = coupons;
@@ -226,18 +264,30 @@ class IntercityHomeController extends GetxController {
if (order.status == Constant.driverAccepted) {
// DRIVER → PICKUP
- await fetchRouteWithWaypoints([latlong.LatLng(driverLat, driverLng), latlong.LatLng(pickupLat, pickupLng)]);
+ await fetchRouteWithWaypoints([
+ latlong.LatLng(driverLat, driverLng),
+ latlong.LatLng(pickupLat, pickupLng),
+ ]);
} else if (order.status == Constant.orderInTransit) {
// PICKUP → DESTINATION
- await fetchRouteWithWaypoints([latlong.LatLng(pickupLat, pickupLng), latlong.LatLng(destLat, destLng)]);
+ await fetchRouteWithWaypoints([
+ latlong.LatLng(pickupLat, pickupLng),
+ latlong.LatLng(destLat, destLng),
+ ]);
}
updateRouteMarkers(driverModel);
} else {
/// For Google Maps
if (order.status == Constant.driverAccepted) {
- await fetchGoogleRouteBetween(LatLng(driverLat, driverLng), LatLng(pickupLat, pickupLng));
+ await fetchGoogleRouteBetween(
+ LatLng(driverLat, driverLng),
+ LatLng(pickupLat, pickupLng),
+ );
} else if (order.status == Constant.orderInTransit) {
- await fetchGoogleRouteBetween(LatLng(pickupLat, pickupLng), LatLng(destLat, destLng));
+ await fetchGoogleRouteBetween(
+ LatLng(pickupLat, pickupLng),
+ LatLng(destLat, destLng),
+ );
}
updateRouteMarkers(driverModel);
}
@@ -261,12 +311,24 @@ class IntercityHomeController extends GetxController {
markers.clear();
osmMarker.clear();
- final departureBytes = await Constant().getBytesFromAsset('assets/images/location_black3x.png', 50);
- final destinationBytes = await Constant().getBytesFromAsset('assets/images/location_orange3x.png', 50);
+ final departureBytes = await Constant().getBytesFromAsset(
+ 'assets/images/location_black3x.png',
+ 50,
+ );
+ final destinationBytes = await Constant().getBytesFromAsset(
+ 'assets/images/location_orange3x.png',
+ 50,
+ );
final driverBytesRaw =
(Constant.sectionConstantModel?.markerIcon?.isNotEmpty ?? false)
- ? await Constant().getBytesFromUrl(Constant.sectionConstantModel!.markerIcon!, width: 120)
- : await Constant().getBytesFromAsset('assets/images/ic_cab.png', 50);
+ ? await Constant().getBytesFromUrl(
+ Constant.sectionConstantModel!.markerIcon!,
+ width: 120,
+ )
+ : await Constant().getBytesFromAsset(
+ 'assets/images/ic_cab.png',
+ 50,
+ );
departureIcon = BitmapDescriptor.fromBytes(departureBytes);
destinationIcon = BitmapDescriptor.fromBytes(destinationBytes);
@@ -275,7 +337,15 @@ class IntercityHomeController extends GetxController {
if (Constant.selectedMapType == 'osm') {
if (order.status == Constant.driverAccepted) {
osmMarker.addAll([
- flutterMap.Marker(point: latlong.LatLng(pickupLat, pickupLng), width: 40, height: 40, child: Image.asset('assets/images/location_black3x.png', width: 40)),
+ flutterMap.Marker(
+ point: latlong.LatLng(pickupLat, pickupLng),
+ width: 40,
+ height: 40,
+ child: Image.asset(
+ 'assets/images/location_black3x.png',
+ width: 40,
+ ),
+ ),
flutterMap.Marker(
point: latlong.LatLng(driverLat, driverLng),
width: 45,
@@ -286,13 +356,26 @@ class IntercityHomeController extends GetxController {
height: 50,
imageUrl: Constant.sectionConstantModel!.markerIcon.toString(),
placeholder: (context, url) => Constant.loader(),
- errorWidget: (context, url, error) => SizedBox(width: 30, height: 30, child: CircularProgressIndicator(strokeWidth: 2)),
+ errorWidget:
+ (context, url, error) => SizedBox(
+ width: 30,
+ height: 30,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
),
),
]);
} else if (order.status == Constant.orderInTransit) {
osmMarker.addAll([
- flutterMap.Marker(point: latlong.LatLng(destLat, destLng), width: 40, height: 40, child: Image.asset('assets/images/location_orange3x.png', width: 40)),
+ flutterMap.Marker(
+ point: latlong.LatLng(destLat, destLng),
+ width: 40,
+ height: 40,
+ child: Image.asset(
+ 'assets/images/location_orange3x.png',
+ width: 40,
+ ),
+ ),
flutterMap.Marker(
point: latlong.LatLng(driverLat, driverLng),
width: 45,
@@ -303,7 +386,12 @@ class IntercityHomeController extends GetxController {
height: 50,
imageUrl: Constant.sectionConstantModel!.markerIcon.toString(),
placeholder: (context, url) => Constant.loader(),
- errorWidget: (context, url, error) => SizedBox(width: 30, height: 30, child: CircularProgressIndicator(strokeWidth: 2)),
+ errorWidget:
+ (context, url, error) => SizedBox(
+ width: 30,
+ height: 30,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
),
),
]);
@@ -315,9 +403,18 @@ class IntercityHomeController extends GetxController {
markerId: const MarkerId("pickup"),
position: LatLng(pickupLat, pickupLng),
infoWindow: InfoWindow(title: "Pickup Location".tr()),
- icon: departureIcon ?? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
+ icon:
+ departureIcon ??
+ BitmapDescriptor.defaultMarkerWithHue(
+ BitmapDescriptor.hueGreen,
+ ),
+ ),
+ Marker(
+ markerId: const MarkerId("driver"),
+ position: LatLng(driverLat, driverLng),
+ infoWindow: InfoWindow(title: "Driver at Pickup".tr()),
+ icon: taxiIcon ?? BitmapDescriptor.defaultMarker,
),
- Marker(markerId: const MarkerId("driver"), position: LatLng(driverLat, driverLng), infoWindow: InfoWindow(title: "Driver at Pickup".tr()), icon: taxiIcon ?? BitmapDescriptor.defaultMarker),
]);
} else if (order.status == Constant.orderInTransit) {
markers.addAll([
@@ -325,9 +422,18 @@ class IntercityHomeController extends GetxController {
markerId: const MarkerId("destination"),
position: LatLng(destLat, destLng),
infoWindow: InfoWindow(title: "Destination Location".tr()),
- icon: destinationIcon ?? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
+ icon:
+ destinationIcon ??
+ BitmapDescriptor.defaultMarkerWithHue(
+ BitmapDescriptor.hueRed,
+ ),
+ ),
+ Marker(
+ markerId: const MarkerId("driver"),
+ position: LatLng(driverLat, driverLng),
+ infoWindow: InfoWindow(title: "Driver Location".tr()),
+ icon: taxiIcon ?? BitmapDescriptor.defaultMarker,
),
- Marker(markerId: const MarkerId("driver"), position: LatLng(driverLat, driverLng), infoWindow: InfoWindow(title: "Driver Location".tr()), icon: taxiIcon ?? BitmapDescriptor.defaultMarker),
]);
}
}
@@ -338,7 +444,10 @@ class IntercityHomeController extends GetxController {
}
}
- Future fetchGoogleRouteBetween(LatLng originPoint, LatLng destPoint) async {
+ Future fetchGoogleRouteBetween(
+ LatLng originPoint,
+ LatLng destPoint,
+ ) async {
final origin = '${originPoint.latitude},${originPoint.longitude}';
final destination = '${destPoint.latitude},${destPoint.longitude}';
final url = Uri.parse(
@@ -355,7 +464,8 @@ class IntercityHomeController extends GetxController {
final route = data['routes'][0];
final encodedPolyline = route['overview_polyline']['points'];
final decodedPoints = PolylinePoints.decodePolyline(encodedPolyline);
- final coordinates = decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
+ final coordinates =
+ decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
addPolyLine(coordinates);
@@ -382,7 +492,12 @@ class IntercityHomeController extends GetxController {
if (currentOrder.value.taxSetting != null) {
for (var element in currentOrder.value.taxSetting!) {
- taxAmount.value = (taxAmount.value + Constant.calculateTax(amount: (subTotal.value - discount.value).toString(), taxModel: element));
+ taxAmount.value =
+ (taxAmount.value +
+ Constant.calculateTax(
+ amount: (subTotal.value - discount.value).toString(),
+ taxModel: element,
+ ));
}
}
@@ -398,11 +513,19 @@ class IntercityHomeController extends GetxController {
subTotal.value = getAmount(selectedVehicleType.value);
if (selectedCouponModel.value.id != null) {
- discount.value = Constant.calculateDiscount(amount: subTotal.value.toString(), offerModel: selectedCouponModel.value);
+ discount.value = Constant.calculateDiscount(
+ amount: subTotal.value.toString(),
+ offerModel: selectedCouponModel.value,
+ );
}
for (var element in Constant.taxList) {
- taxAmount.value = (taxAmount.value + Constant.calculateTax(amount: (subTotal.value - discount.value).toString(), taxModel: element));
+ taxAmount.value =
+ (taxAmount.value +
+ Constant.calculateTax(
+ amount: (subTotal.value - discount.value).toString(),
+ taxModel: element,
+ ));
}
totalAmount.value = (subTotal.value - discount.value) + taxAmount.value;
@@ -439,9 +562,14 @@ class IntercityHomeController extends GetxController {
serviceType: Constant.parcelServiceType,
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-${totalAmount.value.toString()}", userId: FireStoreUtils.getCurrentUid());
+ await FireStoreUtils.updateUserWallet(
+ amount: "-${totalAmount.value.toString()}",
+ userId: FireStoreUtils.getCurrentUid(),
+ );
}
});
}
@@ -455,13 +583,25 @@ class IntercityHomeController extends GetxController {
Future placeOrder() async {
DestinationLocation sourceLocation = DestinationLocation(
- latitude: Constant.selectedMapType == 'osm' ? departureLatLongOsm.value.latitude : departureLatLong.value.latitude,
- longitude: Constant.selectedMapType == 'osm' ? departureLatLongOsm.value.longitude : departureLatLong.value.longitude,
+ latitude:
+ Constant.selectedMapType == 'osm'
+ ? departureLatLongOsm.value.latitude
+ : departureLatLong.value.latitude,
+ longitude:
+ Constant.selectedMapType == 'osm'
+ ? departureLatLongOsm.value.longitude
+ : departureLatLong.value.longitude,
);
DestinationLocation destinationLocation = DestinationLocation(
- latitude: Constant.selectedMapType == 'osm' ? destinationLatLongOsm.value.latitude : destinationLatLong.value.latitude,
- longitude: Constant.selectedMapType == 'osm' ? destinationLatLongOsm.value.longitude : destinationLatLong.value.longitude,
+ latitude:
+ Constant.selectedMapType == 'osm'
+ ? destinationLatLongOsm.value.latitude
+ : destinationLatLong.value.latitude,
+ longitude:
+ Constant.selectedMapType == 'osm'
+ ? destinationLatLongOsm.value.longitude
+ : destinationLatLong.value.longitude,
);
CabOrderModel orderModel = CabOrderModel();
@@ -472,7 +612,8 @@ class IntercityHomeController extends GetxController {
orderModel.vehicleType = selectedVehicleType.value;
orderModel.authorID = FireStoreUtils.getCurrentUid();
orderModel.sourceLocationName = sourceTextEditController.value.text;
- orderModel.destinationLocationName = destinationTextEditController.value.text;
+ orderModel.destinationLocationName =
+ destinationTextEditController.value.text;
orderModel.sourceLocation = sourceLocation;
orderModel.destinationLocation = destinationLocation;
@@ -484,11 +625,14 @@ class IntercityHomeController extends GetxController {
orderModel.taxSetting = Constant.taxList;
orderModel.adminCommissionType =
- Constant.sectionConstantModel!.adminCommision != null && Constant.sectionConstantModel!.adminCommision!.isEnabled == true
- ? Constant.sectionConstantModel!.adminCommision!.commissionType.toString()
+ Constant.sectionConstantModel!.adminCommision != null &&
+ Constant.sectionConstantModel!.adminCommision!.isEnabled == true
+ ? Constant.sectionConstantModel!.adminCommision!.commissionType
+ .toString()
: null;
orderModel.adminCommission =
- Constant.sectionConstantModel!.adminCommision != null && Constant.sectionConstantModel!.adminCommision!.isEnabled == true
+ Constant.sectionConstantModel!.adminCommision != null &&
+ Constant.sectionConstantModel!.adminCommision!.isEnabled == true
? Constant.sectionConstantModel!.adminCommision!.amount.toString()
: null;
orderModel.couponCode = couponCodeTextEditController.value.text;
@@ -501,7 +645,9 @@ class IntercityHomeController extends GetxController {
orderModel.roundTrip = false;
orderModel.sectionId = Constant.sectionConstantModel!.id;
orderModel.createdAt = Timestamp.now();
- orderModel.otpCode = (maths.Random().nextInt(9000) + 1000).toString(); // Generate a 4-digit OTP
+ orderModel.otpCode =
+ (maths.Random().nextInt(9000) + 1000)
+ .toString(); // Generate a 4-digit OTP
orderModel.status = Constant.orderPlaced;
orderModel.scheduleDateTime = Timestamp.now();
log("Order Model : ${orderModel.toJson()}");
@@ -516,8 +662,10 @@ class IntercityHomeController extends GetxController {
double getAmount(VehicleType vehicleType) {
final double currentDistance = distance.value;
- if (currentDistance <= (vehicleType.minimum_delivery_charges_within_km ?? 0)) {
- return double.tryParse(vehicleType.minimum_delivery_charges.toString()) ?? 0.0;
+ if (currentDistance <=
+ (vehicleType.minimum_delivery_charges_within_km ?? 0)) {
+ return double.tryParse(vehicleType.minimum_delivery_charges.toString()) ??
+ 0.0;
} else {
return (vehicleType.delivery_charges_per_km ?? 0.0) * currentDistance;
}
@@ -542,28 +690,50 @@ class IntercityHomeController extends GetxController {
void setStopMarker(double lat, double lng, int index) {
if (Constant.selectedMapType == 'osm') {
// Add new stop marker without clearing
- osmMarker.add(flutterMap.Marker(point: latlong.LatLng(lat, lng), width: 40, height: 40, child: stopIconOsm!));
+ osmMarker.add(
+ flutterMap.Marker(
+ point: latlong.LatLng(lat, lng),
+ width: 40,
+ height: 40,
+ child: stopIconOsm!,
+ ),
+ );
getDirections(isStopMarker: true);
} else {
final markerId = MarkerId('Stop $index');
markers.removeWhere((marker) => marker.markerId == markerId);
- markers.add(Marker(markerId: markerId, infoWindow: InfoWindow(title: 'Stop ${String.fromCharCode(index + 65)}'), position: LatLng(lat, lng), icon: stopIcon!));
+ markers.add(
+ Marker(
+ markerId: markerId,
+ infoWindow: InfoWindow(
+ title: 'Stop ${String.fromCharCode(index + 65)}',
+ ),
+ position: LatLng(lat, lng),
+ icon: stopIcon!,
+ ),
+ );
getDirections();
}
}
void _setOsmMarker(double lat, double lng, {required bool isDeparture}) {
- final marker = flutterMap.Marker(point: latlong.LatLng(lat, lng), width: 40, height: 40, child: isDeparture ? departureIconOsm! : destinationIconOsm!);
+ final marker = flutterMap.Marker(
+ point: latlong.LatLng(lat, lng),
+ width: 40,
+ height: 40,
+ child: isDeparture ? departureIconOsm! : destinationIconOsm!,
+ );
if (isDeparture) {
departureLatLongOsm.value = latlong.LatLng(lat, lng);
} else {
destinationLatLongOsm.value = latlong.LatLng(lat, lng);
}
osmMarker.add(marker);
- if (departureLatLongOsm.value.latitude != 0 && destinationLatLongOsm.value.latitude != 0) {
+ if (departureLatLongOsm.value.latitude != 0 &&
+ destinationLatLongOsm.value.latitude != 0) {
getDirections();
animateToSource(lat, lng);
}
@@ -585,14 +755,26 @@ class IntercityHomeController extends GetxController {
markers.removeWhere((marker) => marker.markerId == markerId);
// Add new marker
- markers.add(Marker(markerId: markerId, position: pos, icon: icon, infoWindow: InfoWindow(title: title)));
+ markers.add(
+ Marker(
+ markerId: markerId,
+ position: pos,
+ icon: icon,
+ infoWindow: InfoWindow(title: title),
+ ),
+ );
mapController.animateCamera(CameraUpdate.newLatLngZoom(pos, 14));
- if (departureLatLong.value.latitude != 0 && destinationLatLong.value.latitude != 0) {
+ if (departureLatLong.value.latitude != 0 &&
+ destinationLatLong.value.latitude != 0) {
getDirections();
} else {
- mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: LatLng(lat, lng), zoom: 14)));
+ mapController.animateCamera(
+ CameraUpdate.newCameraPosition(
+ CameraPosition(target: LatLng(lat, lng), zoom: 14),
+ ),
+ );
}
}
@@ -601,25 +783,43 @@ class IntercityHomeController extends GetxController {
final wayPoints = [];
// Only add valid source
- if (departureLatLongOsm.value.latitude != 0.0 && departureLatLongOsm.value.longitude != 0.0) {
+ if (departureLatLongOsm.value.latitude != 0.0 &&
+ departureLatLongOsm.value.longitude != 0.0) {
wayPoints.add(departureLatLongOsm.value);
}
// Only add valid destination
- if (destinationLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.longitude != 0.0) {
+ if (destinationLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.longitude != 0.0) {
wayPoints.add(destinationLatLongOsm.value);
}
if (!isStopMarker) osmMarker.clear();
// Add source marker
- if (departureLatLongOsm.value.latitude != 0.0 && departureLatLongOsm.value.longitude != 0.0) {
- osmMarker.add(flutterMap.Marker(point: departureLatLongOsm.value, width: 40, height: 40, child: departureIconOsm!));
+ if (departureLatLongOsm.value.latitude != 0.0 &&
+ departureLatLongOsm.value.longitude != 0.0) {
+ osmMarker.add(
+ flutterMap.Marker(
+ point: departureLatLongOsm.value,
+ width: 40,
+ height: 40,
+ child: departureIconOsm!,
+ ),
+ );
}
// Add destination marker
- if (destinationLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.longitude != 0.0) {
- osmMarker.add(flutterMap.Marker(point: destinationLatLongOsm.value, width: 40, height: 40, child: destinationIconOsm!));
+ if (destinationLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.longitude != 0.0) {
+ osmMarker.add(
+ flutterMap.Marker(
+ point: destinationLatLongOsm.value,
+ width: 40,
+ height: 40,
+ child: destinationIconOsm!,
+ ),
+ );
}
if (wayPoints.length >= 2) {
@@ -632,10 +832,14 @@ class IntercityHomeController extends GetxController {
}
Future fetchGoogleRouteWithWaypoints() async {
- if (departureLatLong.value.latitude == 0.0 || destinationLatLong.value.latitude == 0.0) return;
+ if (departureLatLong.value.latitude == 0.0 ||
+ destinationLatLong.value.latitude == 0.0)
+ return;
- final origin = '${departureLatLong.value.latitude},${departureLatLong.value.longitude}';
- final destination = '${destinationLatLong.value.latitude},${destinationLatLong.value.longitude}';
+ final origin =
+ '${departureLatLong.value.latitude},${departureLatLong.value.longitude}';
+ final destination =
+ '${destinationLatLong.value.latitude},${destinationLatLong.value.longitude}';
final url = Uri.parse(
'https://maps.googleapis.com/maps/api/directions/json'
@@ -654,7 +858,8 @@ class IntercityHomeController extends GetxController {
// Polyline
final encodedPolyline = route['overview_polyline']['points'];
final decodedPoints = PolylinePoints.decodePolyline(encodedPolyline);
- final coordinates = decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
+ final coordinates =
+ decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
addPolyLine(coordinates);
@@ -686,19 +891,26 @@ class IntercityHomeController extends GetxController {
}
Future fetchRouteWithWaypoints(List points) async {
- final coordinates = points.map((p) => '${p.longitude},${p.latitude}').join(';');
- final url = Uri.parse('https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson');
+ final coordinates = points
+ .map((p) => '${p.longitude},${p.latitude}')
+ .join(';');
+ final url = Uri.parse(
+ 'https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson',
+ );
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final decoded = json.decode(response.body);
- final geometry = decoded['routes'][0]['geometry']['coordinates'] as List;
+ final geometry =
+ decoded['routes'][0]['geometry']['coordinates'] as List;
final dist = decoded['routes'][0]['distance'];
final dur = decoded['routes'][0]['duration'];
routePoints.clear();
- routePoints.addAll(geometry.map((coord) => latlong.LatLng(coord[1], coord[0])));
+ routePoints.addAll(
+ geometry.map((coord) => latlong.LatLng(coord[1], coord[0])),
+ );
if (Constant.distanceType.toLowerCase() == "KM".toLowerCase()) {
distance.value = dist / 1000.00;
@@ -723,7 +935,10 @@ class IntercityHomeController extends GetxController {
void zoomToPolylineOSM() {
if (routePoints.isEmpty) return;
// LatLngBounds requires at least two points
- final bounds = flutterMap.LatLngBounds(routePoints.first, routePoints.first);
+ final bounds = flutterMap.LatLngBounds(
+ routePoints.first,
+ routePoints.first,
+ );
for (final point in routePoints) {
bounds.extend(point);
}
@@ -735,8 +950,10 @@ class IntercityHomeController extends GetxController {
double getBoundsZoomLevel(flutterMap.LatLngBounds bounds) {
// Simple heuristic: zoom out for larger bounds
- final latDiff = (bounds.northEast.latitude - bounds.southWest.latitude).abs();
- final lngDiff = (bounds.northEast.longitude - bounds.southWest.longitude).abs();
+ final latDiff =
+ (bounds.northEast.latitude - bounds.southWest.latitude).abs();
+ final lngDiff =
+ (bounds.northEast.longitude - bounds.southWest.longitude).abs();
double maxDiff = math.max(latDiff, lngDiff);
if (maxDiff < 0.005) return 18.0;
if (maxDiff < 0.01) return 16.0;
@@ -748,7 +965,13 @@ class IntercityHomeController extends GetxController {
void addPolyLine(List points) {
final id = const PolylineId("poly");
- final polyline = Polyline(polylineId: id, color: AppThemeData.primary300, points: points, width: 6, geodesic: true);
+ final polyline = Polyline(
+ polylineId: id,
+ color: AppThemeData.primary300,
+ points: points,
+ width: 6,
+ geodesic: true,
+ );
polyLines[id] = polyline;
if (points.length >= 2) {
@@ -757,7 +980,10 @@ class IntercityHomeController extends GetxController {
}
}
- Future updateCameraLocationToFitPolyline(List points, GoogleMapController? mapController) async {
+ Future updateCameraLocationToFitPolyline(
+ List points,
+ GoogleMapController? mapController,
+ ) async {
if (mapController == null || points.isEmpty) return;
double minLat = points.first.latitude, maxLat = points.first.latitude;
double minLng = points.first.longitude, maxLng = points.first.longitude;
@@ -767,16 +993,24 @@ class IntercityHomeController extends GetxController {
if (p.longitude < minLng) minLng = p.longitude;
if (p.longitude > maxLng) maxLng = p.longitude;
}
- final bounds = LatLngBounds(southwest: LatLng(minLat, minLng), northeast: LatLng(maxLat, maxLng));
+ final bounds = LatLngBounds(
+ southwest: LatLng(minLat, minLng),
+ northeast: LatLng(maxLat, maxLng),
+ );
final cameraUpdate = CameraUpdate.newLatLngBounds(bounds, 50);
await checkCameraLocation(cameraUpdate, mapController);
}
Future animateToSource(double lat, double long) async {
- final hasBothCoords = departureLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.latitude != 0.0;
+ final hasBothCoords =
+ departureLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.latitude != 0.0;
if (hasBothCoords) {
- await calculateZoomLevel(source: departureLatLongOsm.value, destination: destinationLatLongOsm.value);
+ await calculateZoomLevel(
+ source: departureLatLongOsm.value,
+ destination: destinationLatLongOsm.value,
+ );
} else {
mapOsmController.move(latlong.LatLng(lat, long), 10);
}
@@ -784,15 +1018,25 @@ class IntercityHomeController extends GetxController {
RxMap polyLines = {}.obs;
- Future calculateZoomLevel({required latlong.LatLng source, required latlong.LatLng destination, double paddingFraction = 0.001}) async {
+ Future calculateZoomLevel({
+ required latlong.LatLng source,
+ required latlong.LatLng destination,
+ double paddingFraction = 0.001,
+ }) async {
final bounds = flutterMap.LatLngBounds.fromPoints([source, destination]);
final screenSize = Size(Get.width, Get.height * 0.5);
const double worldDimension = 256.0;
const double maxZoom = 10.0;
- double latToRad(double lat) => math.log((1 + math.sin(lat * math.pi / 180)) / (1 - math.sin(lat * math.pi / 180))) / 2;
+ double latToRad(double lat) =>
+ math.log(
+ (1 + math.sin(lat * math.pi / 180)) /
+ (1 - math.sin(lat * math.pi / 180)),
+ ) /
+ 2;
- double computeZoom(double screenPx, double worldPx, double fraction) => math.log(screenPx / worldPx / fraction) / math.ln2;
+ double computeZoom(double screenPx, double worldPx, double fraction) =>
+ math.log(screenPx / worldPx / fraction) / math.ln2;
final north = bounds.northEast.latitude;
final south = bounds.southWest.latitude;
@@ -810,27 +1054,48 @@ class IntercityHomeController extends GetxController {
final latFraction = (latToRad(north) - latToRad(south)) / math.pi;
final lngFraction = ((east - west + 360) % 360) / 360;
- final latZoom = computeZoom(screenSize.height, worldDimension, latFraction + paddingFraction);
- final lngZoom = computeZoom(screenSize.width, worldDimension, lngFraction + paddingFraction);
+ final latZoom = computeZoom(
+ screenSize.height,
+ worldDimension,
+ latFraction + paddingFraction,
+ );
+ final lngZoom = computeZoom(
+ screenSize.width,
+ worldDimension,
+ lngFraction + paddingFraction,
+ );
final zoomLevel = math.min(latZoom, lngZoom).clamp(0.0, maxZoom);
mapOsmController.move(center, zoomLevel);
}
}
- Future updateCameraLocation(LatLng source, LatLng destination, GoogleMapController? mapController) async {
+ Future updateCameraLocation(
+ LatLng source,
+ LatLng destination,
+ GoogleMapController? mapController,
+ ) async {
if (mapController == null) return;
final bounds = LatLngBounds(
- southwest: LatLng(math.min(source.latitude, destination.latitude), math.min(source.longitude, destination.longitude)),
- northeast: LatLng(math.max(source.latitude, destination.latitude), math.max(source.longitude, destination.longitude)),
+ southwest: LatLng(
+ math.min(source.latitude, destination.latitude),
+ math.min(source.longitude, destination.longitude),
+ ),
+ northeast: LatLng(
+ math.max(source.latitude, destination.latitude),
+ math.max(source.longitude, destination.longitude),
+ ),
);
final cameraUpdate = CameraUpdate.newLatLngBounds(bounds, 90);
await checkCameraLocation(cameraUpdate, mapController);
}
- Future checkCameraLocation(CameraUpdate cameraUpdate, GoogleMapController mapController) async {
+ Future checkCameraLocation(
+ CameraUpdate cameraUpdate,
+ GoogleMapController mapController,
+ ) async {
await mapController.animateCamera(cameraUpdate);
final l1 = await mapController.getVisibleRegion();
final l2 = await mapController.getVisibleRegion();
@@ -843,16 +1108,44 @@ class IntercityHomeController extends GetxController {
Future setIcons() async {
try {
if (Constant.selectedMapType == 'osm') {
- departureIconOsm = Image.asset("assets/icons/pickup.png", width: 30, height: 30);
- destinationIconOsm = Image.asset("assets/icons/dropoff.png", width: 30, height: 30);
- taxiIconOsm = Image.asset("assets/icons/ic_taxi.png", width: 30, height: 30);
- stopIconOsm = Image.asset("assets/icons/location.png", width: 26, height: 26);
+ departureIconOsm = Image.asset(
+ "assets/icons/pickup.png",
+ width: 30,
+ height: 30,
+ );
+ destinationIconOsm = Image.asset(
+ "assets/icons/dropoff.png",
+ width: 30,
+ height: 30,
+ );
+ taxiIconOsm = Image.asset(
+ "assets/icons/ic_taxi.png",
+ width: 30,
+ height: 30,
+ );
+ stopIconOsm = Image.asset(
+ "assets/icons/location.png",
+ width: 26,
+ height: 26,
+ );
} else {
const config = ImageConfiguration(size: Size(48, 48));
- departureIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/pickup.png");
- destinationIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/dropoff.png");
- taxiIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/ic_taxi.png");
- stopIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/location.png");
+ departureIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/pickup.png",
+ );
+ destinationIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/dropoff.png",
+ );
+ taxiIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/ic_taxi.png",
+ );
+ stopIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/location.png",
+ );
}
} catch (e) {
print('Error loading icons: $e');
@@ -860,8 +1153,12 @@ class IntercityHomeController extends GetxController {
}
void clearMapDataIfLocationsRemoved() {
- final isSourceEmpty = departureLatLongOsm.value.latitude == 0.0 && departureLatLongOsm.value.longitude == 0.0;
- final isDestinationEmpty = destinationLatLongOsm.value.latitude == 0.0 && destinationLatLongOsm.value.longitude == 0.0;
+ final isSourceEmpty =
+ departureLatLongOsm.value.latitude == 0.0 &&
+ departureLatLongOsm.value.longitude == 0.0;
+ final isDestinationEmpty =
+ destinationLatLongOsm.value.latitude == 0.0 &&
+ destinationLatLongOsm.value.longitude == 0.0;
if (isSourceEmpty || isDestinationEmpty) {
// Clear polylines
@@ -890,7 +1187,9 @@ class IntercityHomeController extends GetxController {
// Remove marker
if (Constant.selectedMapType == 'osm') {
- osmMarker.removeWhere((marker) => marker.point == departureLatLongOsm.value);
+ osmMarker.removeWhere(
+ (marker) => marker.point == departureLatLongOsm.value,
+ );
} else {
markers.removeWhere((marker) => marker.markerId.value == 'Departure');
}
@@ -906,7 +1205,9 @@ class IntercityHomeController extends GetxController {
destinationTextEditController.value.clear();
if (Constant.selectedMapType == 'osm') {
- osmMarker.removeWhere((marker) => marker.point == destinationLatLongOsm.value);
+ osmMarker.removeWhere(
+ (marker) => marker.point == destinationLatLongOsm.value,
+ );
} else {
markers.removeWhere((marker) => marker.markerId.value == 'Destination');
}
@@ -916,9 +1217,16 @@ class IntercityHomeController extends GetxController {
}
Future searchPlaceNameOSM() async {
- final url = Uri.parse('https://nominatim.openstreetmap.org/reverse?lat=${departureLatLongOsm.value.latitude}&lon=${departureLatLongOsm.value.longitude}&format=json');
+ final url = Uri.parse(
+ 'https://nominatim.openstreetmap.org/reverse?lat=${departureLatLongOsm.value.latitude}&lon=${departureLatLongOsm.value.longitude}&format=json',
+ );
- final response = await http.get(url, headers: {'User-Agent': 'FlutterMapApp/1.0 (menil.siddhiinfosoft@gmail.com)'});
+ final response = await http.get(
+ url,
+ headers: {
+ 'User-Agent': 'FlutterMapApp/1.0 (menil.siddhiinfosoft@gmail.com)',
+ },
+ );
if (response.statusCode == 200) {
log("response.body :: ${response.body}");
@@ -931,7 +1239,9 @@ class IntercityHomeController extends GetxController {
final lat = departureLatLong.value.latitude;
final lng = departureLatLong.value.longitude;
- final url = Uri.parse('https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=${Constant.mapAPIKey}');
+ final url = Uri.parse(
+ 'https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=${Constant.mapAPIKey}',
+ );
final response = await http.get(url);
@@ -974,19 +1284,45 @@ class IntercityHomeController extends GetxController {
Future getPaymentSettings() async {
await FireStoreUtils.getPaymentSettingsData().then((value) {
- stripeModel.value = StripeModel.fromJson(jsonDecode(Preferences.getString(Preferences.stripeSettings)));
- payPalModel.value = PayPalModel.fromJson(jsonDecode(Preferences.getString(Preferences.paypalSettings)));
- payStackModel.value = PayStackModel.fromJson(jsonDecode(Preferences.getString(Preferences.payStack)));
- mercadoPagoModel.value = MercadoPagoModel.fromJson(jsonDecode(Preferences.getString(Preferences.mercadoPago)));
- flutterWaveModel.value = FlutterWaveModel.fromJson(jsonDecode(Preferences.getString(Preferences.flutterWave)));
- paytmModel.value = PaytmModel.fromJson(jsonDecode(Preferences.getString(Preferences.paytmSettings)));
- payFastModel.value = PayFastModel.fromJson(jsonDecode(Preferences.getString(Preferences.payFastSettings)));
- razorPayModel.value = RazorPayModel.fromJson(jsonDecode(Preferences.getString(Preferences.razorpaySettings)));
- midTransModel.value = MidTrans.fromJson(jsonDecode(Preferences.getString(Preferences.midTransSettings)));
- orangeMoneyModel.value = OrangeMoney.fromJson(jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)));
- xenditModel.value = Xendit.fromJson(jsonDecode(Preferences.getString(Preferences.xenditSettings)));
- walletSettingModel.value = WalletSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.walletSettings)));
- cashOnDeliverySettingModel.value = CodSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.codSettings)));
+ stripeModel.value = StripeModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.stripeSettings)),
+ );
+ payPalModel.value = PayPalModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paypalSettings)),
+ );
+ payStackModel.value = PayStackModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payStack)),
+ );
+ mercadoPagoModel.value = MercadoPagoModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.mercadoPago)),
+ );
+ flutterWaveModel.value = FlutterWaveModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.flutterWave)),
+ );
+ paytmModel.value = PaytmModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paytmSettings)),
+ );
+ payFastModel.value = PayFastModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payFastSettings)),
+ );
+ razorPayModel.value = RazorPayModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.razorpaySettings)),
+ );
+ midTransModel.value = MidTrans.fromJson(
+ jsonDecode(Preferences.getString(Preferences.midTransSettings)),
+ );
+ orangeMoneyModel.value = OrangeMoney.fromJson(
+ jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)),
+ );
+ xenditModel.value = Xendit.fromJson(
+ jsonDecode(Preferences.getString(Preferences.xenditSettings)),
+ );
+ walletSettingModel.value = WalletSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.walletSettings)),
+ );
+ cashOnDeliverySettingModel.value = CodSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.codSettings)),
+ );
if (walletSettingModel.value.isEnabled == true) {
selectedPaymentMethod.value = PaymentGateway.wallet.name;
@@ -1028,20 +1364,32 @@ class IntercityHomeController extends GetxController {
Future stripeMakePayment({required String amount}) async {
log(double.parse(amount).toStringAsFixed(0));
try {
- Map? paymentIntentData = await createStripeIntent(amount: amount);
+ Map? paymentIntentData = await createStripeIntent(
+ amount: amount,
+ );
log("stripe Responce====>$paymentIntentData");
if (paymentIntentData!.containsKey("error")) {
Get.back();
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
} else {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentData['client_secret'],
allowsDelayedPaymentMethods: false,
- googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'US', testEnv: true, currencyCode: "USD"),
+ googlePay: const PaymentSheetGooglePay(
+ merchantCountryCode: 'US',
+ testEnv: true,
+ currencyCode: "USD",
+ ),
customFlow: true,
style: ThemeMode.system,
- appearance: PaymentSheetAppearance(colors: PaymentSheetAppearanceColors(primary: AppThemeData.primary300)),
+ appearance: PaymentSheetAppearance(
+ colors: PaymentSheetAppearanceColors(
+ primary: AppThemeData.primary300,
+ ),
+ ),
merchantDisplayName: 'GoRide',
),
);
@@ -1087,7 +1435,10 @@ class IntercityHomeController extends GetxController {
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
body: body,
- headers: {'Authorization': 'Bearer $stripeSecret', 'Content-Type': 'application/x-www-form-urlencoded'},
+ headers: {
+ 'Authorization': 'Bearer $stripeSecret',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
);
return jsonDecode(response.body);
@@ -1097,8 +1448,14 @@ class IntercityHomeController extends GetxController {
}
//mercadoo
- Future mercadoPagoMakePayment({required BuildContext context, required String amount}) async {
- final headers = {'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}', 'Content-Type': 'application/json'};
+ Future mercadoPagoMakePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
+ final headers = {
+ 'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"items": [
@@ -1111,12 +1468,20 @@ class IntercityHomeController extends GetxController {
},
],
"payer": {"email": userModel.value.email},
- "back_urls": {"failure": "${Constant.globalUrl}payment/failure", "pending": "${Constant.globalUrl}payment/pending", "success": "${Constant.globalUrl}payment/success"},
+ "back_urls": {
+ "failure": "${Constant.globalUrl}payment/failure",
+ "pending": "${Constant.globalUrl}payment/pending",
+ "success": "${Constant.globalUrl}payment/success",
+ },
"auto_return": "approved",
// Automatically return after payment is approved
});
- final response = await http.post(Uri.parse("https://api.mercadopago.com/checkout/preferences"), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse("https://api.mercadopago.com/checkout/preferences"),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
final data = jsonDecode(response.body);
@@ -1174,9 +1539,12 @@ class IntercityHomeController extends GetxController {
///PayStack Payment Method
Future payStackPayment(String totalAmount) async {
- await PayStackURLGen.payStackURLGen(amount: (double.parse(totalAmount) * 100).toString(), currency: "ZAR", secretKey: payStackModel.value.secretKey.toString(), userModel: userModel.value).then((
- value,
- ) async {
+ await PayStackURLGen.payStackURLGen(
+ amount: (double.parse(totalAmount) * 100).toString(),
+ currency: "ZAR",
+ secretKey: payStackModel.value.secretKey.toString(),
+ userModel: userModel.value,
+ ).then((value) async {
if (value != null) {
PayStackUrlModel payStackModel0 = value;
Get.to(
@@ -1196,15 +1564,23 @@ class IntercityHomeController extends GetxController {
}
});
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
}
});
}
//flutter wave Payment Method
- Future flutterWaveInitiatePayment({required BuildContext context, required String amount}) async {
+ Future flutterWaveInitiatePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
final url = Uri.parse('https://api.flutterwave.com/v3/payments');
- final headers = {'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}', 'Content-Type': 'application/json'};
+ final headers = {
+ 'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"tx_ref": _ref,
@@ -1217,14 +1593,19 @@ class IntercityHomeController extends GetxController {
"phonenumber": userModel.value.phoneNumber, // Add a real phone number
"name": userModel.value.fullName(), // Add a real customer name
},
- "customizations": {"title": "Payment for Services", "description": "Payment for XYZ services"},
+ "customizations": {
+ "title": "Payment for Services",
+ "description": "Payment for XYZ services",
+ },
});
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
- Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((value) {
+ Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((
+ value,
+ ) {
if (value) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1253,8 +1634,14 @@ class IntercityHomeController extends GetxController {
// payFast
void payFastPayment({required BuildContext context, required String amount}) {
- PayStackURLGen.getPayHTML(payFastSettingData: payFastModel.value, amount: amount.toString(), userModel: userModel.value).then((String? value) async {
- bool isDone = await Get.to(PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value));
+ PayStackURLGen.getPayHTML(
+ payFastSettingData: payFastModel.value,
+ amount: amount.toString(),
+ userModel: userModel.value,
+ ).then((String? value) async {
+ bool isDone = await Get.to(
+ PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value),
+ );
if (isDone) {
Get.back();
ShowToastDialog.showToast("Payment successfully".tr());
@@ -1293,7 +1680,14 @@ class IntercityHomeController extends GetxController {
// });
}
- Future startTransaction(context, {required String txnTokenBy, required orderId, required double amount, required callBackURL, required isStaging}) async {
+ Future startTransaction(
+ context, {
+ required String txnTokenBy,
+ required orderId,
+ required double amount,
+ required callBackURL,
+ required isStaging,
+ }) async {
// try {
// var response = AllInOneSdk.startTransaction(
// paytmModel.value.paytmMID.toString(),
@@ -1329,24 +1723,38 @@ class IntercityHomeController extends GetxController {
// }
}
- Future verifyCheckSum({required String checkSum, required double amount, required orderId}) async {
+ Future verifyCheckSum({
+ required String checkSum,
+ required double amount,
+ required orderId,
+ }) async {
String getChecksum = "${Constant.globalUrl}payments/validatechecksum";
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(), "checksum_value": checkSum},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ "checksum_value": checkSum,
+ },
);
final data = jsonDecode(response.body);
return data['status'];
}
- Future initiatePayment({required double amount, required orderId}) async {
+ Future initiatePayment({
+ required double amount,
+ required orderId,
+ }) async {
String initiateURL = "${Constant.globalUrl}payments/initiatepaytmpayment";
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
final response = await http.post(
Uri.parse(initiateURL),
@@ -1364,9 +1772,12 @@ class IntercityHomeController extends GetxController {
);
log(response.body);
final data = jsonDecode(response.body);
- if (data["body"]["txnToken"] == null || data["body"]["txnToken"].toString().isEmpty) {
+ if (data["body"]["txnToken"] == null ||
+ data["body"]["txnToken"].toString().isEmpty) {
Get.back();
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
}
return GetPaymentTxtTokenModel.fromJson(data);
}
@@ -1384,7 +1795,10 @@ class IntercityHomeController extends GetxController {
'description': 'wallet Topup',
'retry': {'enabled': true, 'max_count': 1},
'send_sms_hash': true,
- 'prefill': {'contact': userModel.value.phoneNumber, 'email': userModel.value.email},
+ 'prefill': {
+ 'contact': userModel.value.phoneNumber,
+ 'email': userModel.value.email,
+ },
'external': {
'wallets': ['paytm'],
},
@@ -1419,7 +1833,10 @@ class IntercityHomeController extends GetxController {
}
//Midtrans payment
- Future midtransMakePayment({required String amount, required BuildContext context}) async {
+ Future midtransMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
await createPaymentLink(amount: amount).then((url) {
ShowToastDialog.closeLoader();
if (url != '') {
@@ -1437,15 +1854,30 @@ class IntercityHomeController extends GetxController {
Future createPaymentLink({required var amount}) async {
var ordersId = const Uuid().v1();
- final url = Uri.parse(midTransModel.value.isSandbox! ? 'https://api.sandbox.midtrans.com/v1/payment-links' : 'https://api.midtrans.com/v1/payment-links');
+ final url = Uri.parse(
+ midTransModel.value.isSandbox!
+ ? 'https://api.sandbox.midtrans.com/v1/payment-links'
+ : 'https://api.midtrans.com/v1/payment-links',
+ );
final response = await http.post(
url,
- headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': generateBasicAuthHeader(midTransModel.value.serverKey!)},
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ 'Authorization': generateBasicAuthHeader(
+ midTransModel.value.serverKey!,
+ ),
+ },
body: jsonEncode({
- 'transaction_details': {'order_id': ordersId, 'gross_amount': double.parse(amount.toString()).toInt()},
+ 'transaction_details': {
+ 'order_id': ordersId,
+ 'gross_amount': double.parse(amount.toString()).toInt(),
+ },
'usage_limit': 2,
- "callbacks": {"finish": "https://www.google.com?merchant_order_id=$ordersId"},
+ "callbacks": {
+ "finish": "https://www.google.com?merchant_order_id=$ordersId",
+ },
}),
);
@@ -1453,7 +1885,9 @@ class IntercityHomeController extends GetxController {
final responseData = jsonDecode(response.body);
return responseData['payment_url'];
} else {
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -1470,13 +1904,30 @@ class IntercityHomeController extends GetxController {
static String orderId = '';
static String amount = '';
- Future orangeMakePayment({required String amount, required BuildContext context}) async {
+ Future orangeMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
reset();
var id = const Uuid().v4();
- var paymentURL = await fetchToken(context: context, orderId: id, amount: amount, currency: 'USD');
+ var paymentURL = await fetchToken(
+ context: context,
+ orderId: id,
+ amount: amount,
+ currency: 'USD',
+ );
ShowToastDialog.closeLoader();
if (paymentURL.toString() != '') {
- Get.to(() => OrangeMoneyScreen(initialURl: paymentURL, accessToken: accessToken, amount: amount, orangePay: orangeMoneyModel.value, orderId: orderId, payToken: payToken))!.then((value) {
+ Get.to(
+ () => OrangeMoneyScreen(
+ initialURl: paymentURL,
+ accessToken: accessToken,
+ amount: amount,
+ orangePay: orangeMoneyModel.value,
+ orderId: orderId,
+ payToken: payToken,
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1488,13 +1939,22 @@ class IntercityHomeController extends GetxController {
}
}
- Future fetchToken({required String orderId, required String currency, required BuildContext context, required String amount}) async {
+ Future fetchToken({
+ required String orderId,
+ required String currency,
+ required BuildContext context,
+ required String amount,
+ }) async {
String apiUrl = 'https://api.orange.com/oauth/v3/token';
Map requestBody = {'grant_type': 'client_credentials'};
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': "Basic ${orangeMoneyModel.value.auth!}", 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': "Basic ${orangeMoneyModel.value.auth!}",
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Accept': 'application/json',
+ },
body: requestBody,
);
@@ -1505,17 +1965,32 @@ class IntercityHomeController extends GetxController {
accessToken = responseData['access_token'];
// ignore: use_build_context_synchronously
- return await webpayment(context: context, amountData: amount, currency: currency, orderIdData: orderId);
+ return await webpayment(
+ context: context,
+ amountData: amount,
+ currency: currency,
+ orderIdData: orderId,
+ );
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
- Future webpayment({required String orderIdData, required BuildContext context, required String currency, required String amountData}) async {
+ Future webpayment({
+ required String orderIdData,
+ required BuildContext context,
+ required String currency,
+ required String amountData,
+ }) async {
orderId = orderIdData;
amount = amountData;
- String apiUrl = orangeMoneyModel.value.isSandbox! == true ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment' : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
+ String apiUrl =
+ orangeMoneyModel.value.isSandbox! == true
+ ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment'
+ : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
Map requestBody = {
"merchant_key": orangeMoneyModel.value.merchantKey ?? '',
"currency": orangeMoneyModel.value.isSandbox == true ? "OUV" : currency,
@@ -1530,7 +2005,11 @@ class IntercityHomeController extends GetxController {
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': 'Bearer $accessToken',
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ },
body: json.encode(requestBody),
);
@@ -1544,7 +2023,9 @@ class IntercityHomeController extends GetxController {
return '';
}
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -1561,7 +2042,13 @@ class IntercityHomeController extends GetxController {
await createXenditInvoice(amount: amount).then((model) {
ShowToastDialog.closeLoader();
if (model.id != null) {
- Get.to(() => XenditScreen(initialURl: model.invoiceUrl ?? '', transId: model.id ?? '', apiKey: xenditModel.value.apiKey!.toString()))!.then((value) {
+ Get.to(
+ () => XenditScreen(
+ initialURl: model.invoiceUrl ?? '',
+ transId: model.id ?? '',
+ apiKey: xenditModel.value.apiKey!.toString(),
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1578,7 +2065,9 @@ class IntercityHomeController extends GetxController {
const url = 'https://api.xendit.co/v2/invoices';
var headers = {
'Content-Type': 'application/json',
- 'Authorization': generateBasicAuthHeader(xenditModel.value.apiKey!.toString()),
+ 'Authorization': generateBasicAuthHeader(
+ xenditModel.value.apiKey!.toString(),
+ ),
// 'Cookie': '__cf_bm=yERkrx3xDITyFGiou0bbKY1bi7xEwovHNwxV1vCNbVc-1724155511-1.0.1.1-jekyYQmPCwY6vIJ524K0V6_CEw6O.dAwOmQnHtwmaXO_MfTrdnmZMka0KZvjukQgXu5B.K_6FJm47SGOPeWviQ',
};
@@ -1591,7 +2080,11 @@ class IntercityHomeController extends GetxController {
});
try {
- final response = await http.post(Uri.parse(url), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse(url),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
XenditModel model = XenditModel.fromJson(jsonDecode(response.body));
diff --git a/lib/controllers/address_list_controller.dart b/lib/controllers/address_list_controller.dart
index 3a90915..ef1b6a2 100644
--- a/lib/controllers/address_list_controller.dart
+++ b/lib/controllers/address_list_controller.dart
@@ -1,6 +1,5 @@
import 'package:customer/models/user_model.dart';
-import 'package:get/get.dart';
-
+import 'package:get/get.dart' hide Trans;
import '../constant/constant.dart';
import '../service/fire_store_utils.dart';
@@ -18,7 +17,9 @@ class AddressListController extends GetxController {
}
Future getUser() async {
- await FireStoreUtils.getUserProfile(FireStoreUtils.getCurrentUid()).then((value) {
+ await FireStoreUtils.getUserProfile(FireStoreUtils.getCurrentUid()).then((
+ value,
+ ) {
if (value != null) {
userModel.value = value;
if (userModel.value.shippingAddress != null) {
diff --git a/lib/controllers/advertisement_list_controller.dart b/lib/controllers/advertisement_list_controller.dart
index 56ae63b..a8f0e65 100644
--- a/lib/controllers/advertisement_list_controller.dart
+++ b/lib/controllers/advertisement_list_controller.dart
@@ -3,7 +3,7 @@ import 'package:customer/models/advertisement_model.dart';
import 'package:customer/models/favourite_model.dart';
import 'package:customer/models/vendor_model.dart';
import '../service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class AdvertisementListController extends GetxController {
RxBool isLoading = true.obs;
diff --git a/lib/controllers/all_brand_product_controller.dart b/lib/controllers/all_brand_product_controller.dart
index 5ffaec1..8a8867a 100644
--- a/lib/controllers/all_brand_product_controller.dart
+++ b/lib/controllers/all_brand_product_controller.dart
@@ -3,7 +3,7 @@ import 'package:customer/models/brands_model.dart';
import 'package:customer/models/product_model.dart';
import 'package:customer/models/vendor_model.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class AllBrandProductController extends GetxController {
RxList productList = [].obs;
@@ -27,19 +27,27 @@ class AllBrandProductController extends GetxController {
}
Future getProductByCategoryId() async {
- List productDataList = await FireStoreUtils.getProductListByBrandId(brandModel.value.id.toString());
+ List productDataList =
+ await FireStoreUtils.getProductListByBrandId(
+ brandModel.value.id.toString(),
+ );
List vendorList = await FireStoreUtils.getAllStoresFuture();
List allProduct = [];
for (var vendor in vendorList) {
await FireStoreUtils.getAllProducts(vendor.id.toString()).then((value) {
- if (Constant.isSubscriptionModelApplied == true || vendor.adminCommission?.isEnabled == true) {
- if (vendor.subscriptionPlan != null && Constant.isExpire(vendor) == false) {
+ if (Constant.isSubscriptionModelApplied == true ||
+ vendor.adminCommission?.isEnabled == true) {
+ if (vendor.subscriptionPlan != null &&
+ Constant.isExpire(vendor) == false) {
if (vendor.subscriptionPlan?.itemLimit == '-1') {
allProduct.addAll(value);
} else {
int selectedProduct =
- value.length < int.parse(vendor.subscriptionPlan?.itemLimit ?? '0') ? (value.isEmpty ? 0 : (value.length)) : int.parse(vendor.subscriptionPlan?.itemLimit ?? '0');
+ value.length <
+ int.parse(vendor.subscriptionPlan?.itemLimit ?? '0')
+ ? (value.isEmpty ? 0 : (value.length))
+ : int.parse(vendor.subscriptionPlan?.itemLimit ?? '0');
allProduct.addAll(value.sublist(0, selectedProduct));
}
}
@@ -49,7 +57,9 @@ class AllBrandProductController extends GetxController {
});
}
for (var element in productDataList) {
- final bool productIsInList = allProduct.any((product) => product.id == element.id);
+ final bool productIsInList = allProduct.any(
+ (product) => product.id == element.id,
+ );
if (productIsInList) {
productList.add(element);
}
diff --git a/lib/controllers/all_category_product_controller.dart b/lib/controllers/all_category_product_controller.dart
index d5454f6..d609ade 100644
--- a/lib/controllers/all_category_product_controller.dart
+++ b/lib/controllers/all_category_product_controller.dart
@@ -1,7 +1,7 @@
import 'package:customer/models/product_model.dart';
import 'package:customer/models/vendor_category_model.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class AllCategoryProductController extends GetxController {
RxBool isLoading = true.obs;
@@ -25,6 +25,8 @@ class AllCategoryProductController extends GetxController {
}
Future getProductByCategoryId() async {
- productList.value = await FireStoreUtils.getProductListByCategoryId(categoryModel.value.id.toString());
+ productList.value = await FireStoreUtils.getProductListByCategoryId(
+ categoryModel.value.id.toString(),
+ );
}
}
diff --git a/lib/controllers/book_parcel_controller.dart b/lib/controllers/book_parcel_controller.dart
index 825b239..e7d25e1 100644
--- a/lib/controllers/book_parcel_controller.dart
+++ b/lib/controllers/book_parcel_controller.dart
@@ -8,7 +8,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:google_maps_flutter/google_maps_flutter.dart' as latlong;
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
@@ -23,26 +23,39 @@ import '../themes/show_toast_dialog.dart';
class BookParcelController extends GetxController {
// Sender details
- final Rx senderLocationController = TextEditingController().obs;
- final Rx senderNameController = TextEditingController().obs;
- final Rx senderMobileController = TextEditingController().obs;
- final Rx senderWeightController = SingleValueDropDownController().obs;
- final Rx senderNoteController = TextEditingController().obs;
- final Rx senderCountryCodeController = TextEditingController(text: Constant.defaultCountryCode).obs;
+ final Rx senderLocationController =
+ TextEditingController().obs;
+ final Rx senderNameController =
+ TextEditingController().obs;
+ final Rx senderMobileController =
+ TextEditingController().obs;
+ final Rx senderWeightController =
+ SingleValueDropDownController().obs;
+ final Rx senderNoteController =
+ TextEditingController().obs;
+ final Rx senderCountryCodeController =
+ TextEditingController(text: Constant.defaultCountryCode).obs;
// Receiver details
- final Rx receiverLocationController = TextEditingController().obs;
- final Rx receiverNameController = TextEditingController().obs;
- final Rx receiverMobileController = TextEditingController().obs;
- final Rx receiverNoteController = TextEditingController().obs;
- final Rx receiverCountryCodeController = TextEditingController(text: Constant.defaultCountryCode).obs;
+ final Rx receiverLocationController =
+ TextEditingController().obs;
+ final Rx receiverNameController =
+ TextEditingController().obs;
+ final Rx receiverMobileController =
+ TextEditingController().obs;
+ final Rx receiverNoteController =
+ TextEditingController().obs;
+ final Rx receiverCountryCodeController =
+ TextEditingController(text: Constant.defaultCountryCode).obs;
// Delivery type
final RxString selectedDeliveryType = 'now'.obs;
// Scheduled delivery fields
- final Rx scheduledDateController = TextEditingController().obs;
- final Rx scheduledTimeController = TextEditingController().obs;
+ final Rx scheduledDateController =
+ TextEditingController().obs;
+ final Rx scheduledTimeController =
+ TextEditingController().obs;
final RxString scheduledDate = ''.obs;
final RxString scheduledTime = ''.obs;
@@ -83,7 +96,12 @@ class BookParcelController extends GetxController {
}
Future pickScheduledDate(BuildContext context) async {
- final DateTime? picked = await showDatePicker(context: context, initialDate: DateTime.now(), firstDate: DateTime.now(), lastDate: DateTime.now().add(const Duration(days: 365)));
+ final DateTime? picked = await showDatePicker(
+ context: context,
+ initialDate: DateTime.now(),
+ firstDate: DateTime.now(),
+ lastDate: DateTime.now().add(const Duration(days: 365)),
+ );
if (picked != null) {
final formattedDate = "${picked.day}/${picked.month}/${picked.year}";
scheduledDate.value = formattedDate;
@@ -92,7 +110,10 @@ class BookParcelController extends GetxController {
}
Future pickScheduledTime(BuildContext context) async {
- final TimeOfDay? picked = await showTimePicker(context: context, initialTime: TimeOfDay.now());
+ final TimeOfDay? picked = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay.now(),
+ );
if (picked != null) {
final formattedTime = picked.format(context);
scheduledTime.value = formattedTime;
@@ -102,7 +123,10 @@ class BookParcelController extends GetxController {
void onCameraClick(BuildContext context) {
final action = CupertinoActionSheet(
- message: Text('Add your parcel image.'.tr(), style: const TextStyle(fontSize: 15.0)),
+ message: Text(
+ 'Add your parcel image.'.tr(),
+ style: const TextStyle(fontSize: 15.0),
+ ),
actions: [
CupertinoActionSheetAction(
child: Text('Choose image from gallery'.tr()),
@@ -118,14 +142,19 @@ class BookParcelController extends GetxController {
child: Text('Take a picture'.tr()),
onPressed: () async {
Navigator.pop(context);
- final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
+ final XFile? photo = await _picker.pickImage(
+ source: ImageSource.camera,
+ );
if (photo != null) {
images.add(photo);
}
},
),
],
- cancelButton: CupertinoActionSheetAction(child: Text('Cancel'.tr()), onPressed: () => Navigator.pop(context)),
+ cancelButton: CupertinoActionSheetAction(
+ child: Text('Cancel'.tr()),
+ onPressed: () => Navigator.pop(context),
+ ),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
@@ -134,11 +163,18 @@ class BookParcelController extends GetxController {
try {
await Geolocator.requestPermission();
final position = await Geolocator.getCurrentPosition();
- final placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
+ final placemarks = await placemarkFromCoordinates(
+ position.latitude,
+ position.longitude,
+ );
final place = placemarks.first;
- final address = "${place.name}, ${place.subLocality}, ${place.locality}, ${place.administrativeArea}, ${place.postalCode}, ${place.country}";
+ final address =
+ "${place.name}, ${place.subLocality}, ${place.locality}, ${place.administrativeArea}, ${place.postalCode}, ${place.country}";
- final userLocation = UserLocation(latitude: position.latitude, longitude: position.longitude);
+ final userLocation = UserLocation(
+ latitude: position.latitude,
+ longitude: position.longitude,
+ );
senderLocation.value = userLocation;
senderLocationController.value.text = address;
} catch (e) {
@@ -179,7 +215,9 @@ class BookParcelController extends GetxController {
ShowToastDialog.showToast("Please select parcel weight".tr());
return false;
} else if (senderLocation.value == null || receiverLocation.value == null) {
- ShowToastDialog.showToast("Please select both sender and receiver locations".tr());
+ ShowToastDialog.showToast(
+ "Please select both sender and receiver locations".tr(),
+ );
return false;
}
return true;
@@ -193,22 +231,37 @@ class BookParcelController extends GetxController {
if (Constant.selectedMapType == 'osm') {
print("Fetching route using OSM");
- print("Sender Location: ${senderLocation.value?.latitude}, ${senderLocation.value?.longitude}");
- print("Receiver Location: ${receiverLocation.value?.latitude}, ${receiverLocation.value?.longitude}");
+ print(
+ "Sender Location: ${senderLocation.value?.latitude}, ${senderLocation.value?.longitude}",
+ );
+ print(
+ "Receiver Location: ${receiverLocation.value?.latitude}, ${receiverLocation.value?.longitude}",
+ );
await fetchRouteWithWaypoints([
- latlong.LatLng(senderLocation.value?.latitude ?? 0.0, senderLocation.value?.longitude ?? 0.0),
- latlong.LatLng(receiverLocation.value?.latitude ?? 0.0, receiverLocation.value?.longitude ?? 0.0),
+ latlong.LatLng(
+ senderLocation.value?.latitude ?? 0.0,
+ senderLocation.value?.longitude ?? 0.0,
+ ),
+ latlong.LatLng(
+ receiverLocation.value?.latitude ?? 0.0,
+ receiverLocation.value?.longitude ?? 0.0,
+ ),
]);
} else {
await fetchGoogleRouteWithWaypoints();
}
if (distance.value < 0.5) {
- ShowToastDialog.showToast("Sender's location to receiver's location should be more than 1 km.".tr());
+ ShowToastDialog.showToast(
+ "Sender's location to receiver's location should be more than 1 km."
+ .tr(),
+ );
return;
}
- subTotal.value = (distance.value * double.parse(selectedWeight!.deliveryCharge.toString()));
+ subTotal.value =
+ (distance.value *
+ double.parse(selectedWeight!.deliveryCharge.toString()));
goToCart();
} catch (e) {
ShowToastDialog.showToast("Something went wrong while booking.".tr());
@@ -217,7 +270,10 @@ class BookParcelController extends GetxController {
}
void goToCart() {
- DateTime senderPickup = isScheduled.value ? parseScheduledDateTime(scheduledDate.value, scheduledTime.value) : DateTime.now();
+ DateTime senderPickup =
+ isScheduled.value
+ ? parseScheduledDateTime(scheduledDate.value, scheduledTime.value)
+ : DateTime.now();
print("Sender Pickup: $distance");
ParcelOrderModel order = ParcelOrderModel(
@@ -236,22 +292,42 @@ class BookParcelController extends GetxController {
taxSetting: Constant.taxList,
isSchedule: isScheduled.value,
sourcePoint: G(
- geopoint: GeoPoint(senderLocation.value!.latitude ?? 0.0, senderLocation.value!.longitude ?? 0.0),
- geohash: Geoflutterfire().point(latitude: senderLocation.value!.latitude ?? 0.0, longitude: senderLocation.value!.longitude ?? 0.0).hash,
+ geopoint: GeoPoint(
+ senderLocation.value!.latitude ?? 0.0,
+ senderLocation.value!.longitude ?? 0.0,
+ ),
+ geohash:
+ Geoflutterfire()
+ .point(
+ latitude: senderLocation.value!.latitude ?? 0.0,
+ longitude: senderLocation.value!.longitude ?? 0.0,
+ )
+ .hash,
),
destinationPoint: G(
- geopoint: GeoPoint(receiverLocation.value!.latitude ?? 0.0, receiverLocation.value!.longitude ?? 0.0),
- geohash: Geoflutterfire().point(latitude: receiverLocation.value!.latitude ?? 0.0, longitude: receiverLocation.value!.longitude ?? 0.0).hash,
+ geopoint: GeoPoint(
+ receiverLocation.value!.latitude ?? 0.0,
+ receiverLocation.value!.longitude ?? 0.0,
+ ),
+ geohash:
+ Geoflutterfire()
+ .point(
+ latitude: receiverLocation.value!.latitude ?? 0.0,
+ longitude: receiverLocation.value!.longitude ?? 0.0,
+ )
+ .hash,
),
sender: LocationInformation(
address: senderLocationController.value.text,
name: senderNameController.value.text,
- phone: "(${senderCountryCodeController.value.text}) ${senderMobileController.value.text}",
+ phone:
+ "(${senderCountryCodeController.value.text}) ${senderMobileController.value.text}",
),
receiver: LocationInformation(
address: receiverLocationController.value.text,
name: receiverNameController.value.text,
- phone: "(${receiverCountryCodeController.value.text}) ${receiverMobileController.value.text}",
+ phone:
+ "(${receiverCountryCodeController.value.text}) ${receiverMobileController.value.text}",
),
receiverLatLong: receiverLocation.value,
senderLatLong: senderLocation.value,
@@ -262,7 +338,10 @@ class BookParcelController extends GetxController {
debugPrint("Subtotal: ${subTotal.value}");
debugPrint("Order JSON: ${order.toJson()}");
- Get.to(() => ParcelOrderConfirmationScreen(), arguments: {'parcelOrder': order, 'images': images});
+ Get.to(
+ () => ParcelOrderConfirmationScreen(),
+ arguments: {'parcelOrder': order, 'images': images},
+ );
}
DateTime parseScheduledDateTime(String dateStr, String timeStr) {
@@ -272,7 +351,10 @@ class BookParcelController extends GetxController {
final month = int.parse(dateParts[1]);
final year = int.parse(dateParts[2]);
- final time = TimeOfDay(hour: int.parse(timeStr.split(':')[0]), minute: int.parse(timeStr.split(':')[1].split(' ')[0]));
+ final time = TimeOfDay(
+ hour: int.parse(timeStr.split(':')[0]),
+ minute: int.parse(timeStr.split(':')[1].split(' ')[0]),
+ );
final isPM = timeStr.toLowerCase().contains('pm');
final hour24 = isPM && time.hour < 12 ? time.hour + 12 : time.hour;
@@ -284,9 +366,13 @@ class BookParcelController extends GetxController {
}
Future fetchGoogleRouteWithWaypoints() async {
- final origin = '${senderLocation.value!.latitude},${senderLocation.value!.longitude}';
- final destination = '${receiverLocation.value!.latitude},${receiverLocation.value!.longitude}';
- final url = Uri.parse('https://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$destination&mode=driving&key=${Constant.mapAPIKey}');
+ final origin =
+ '${senderLocation.value!.latitude},${senderLocation.value!.longitude}';
+ final destination =
+ '${receiverLocation.value!.latitude},${receiverLocation.value!.longitude}';
+ final url = Uri.parse(
+ 'https://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$destination&mode=driving&key=${Constant.mapAPIKey}',
+ );
try {
final response = await http.get(url);
@@ -315,8 +401,12 @@ class BookParcelController extends GetxController {
}
Future fetchRouteWithWaypoints(List points) async {
- final coordinates = points.map((p) => '${p.longitude},${p.latitude}').join(';');
- final url = Uri.parse('https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson');
+ final coordinates = points
+ .map((p) => '${p.longitude},${p.latitude}')
+ .join(';');
+ final url = Uri.parse(
+ 'https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson',
+ );
try {
final response = await http.get(url);
diff --git a/lib/controllers/cab_booking_controller.dart b/lib/controllers/cab_booking_controller.dart
index ce05319..ccd500c 100644
--- a/lib/controllers/cab_booking_controller.dart
+++ b/lib/controllers/cab_booking_controller.dart
@@ -46,7 +46,7 @@ import 'package:flutter_map/flutter_map.dart' as flutterMap;
import 'package:flutter_paypal/flutter_paypal.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:latlong2/latlong.dart' as latlong;
@@ -60,10 +60,13 @@ class CabBookingController extends GetxController {
late GoogleMapController mapController;
final flutterMap.MapController mapOsmController = flutterMap.MapController();
- final Rx sourceTextEditController = TextEditingController().obs;
- final Rx destinationTextEditController = TextEditingController().obs;
+ final Rx sourceTextEditController =
+ TextEditingController().obs;
+ final Rx destinationTextEditController =
+ TextEditingController().obs;
- final Rx couponCodeTextEditController = TextEditingController().obs;
+ final Rx couponCodeTextEditController =
+ TextEditingController().obs;
final Rx currentLocation = Location().obs;
@@ -133,64 +136,99 @@ class CabBookingController extends GetxController {
await getPaymentSettings();
- FireStoreUtils.fireStore.collection(CollectionName.users).doc(FireStoreUtils.getCurrentUid()).snapshots().listen((userSnapshot) async {
- if (!userSnapshot.exists) return;
+ FireStoreUtils.fireStore
+ .collection(CollectionName.users)
+ .doc(FireStoreUtils.getCurrentUid())
+ .snapshots()
+ .listen((userSnapshot) async {
+ if (!userSnapshot.exists) return;
- userModel.value = UserModel.fromJson(userSnapshot.data()!);
+ userModel.value = UserModel.fromJson(userSnapshot.data()!);
- if (userModel.value.inProgressOrderID != null && userModel.value.inProgressOrderID!.isNotEmpty) {
- String? validRideId;
+ if (userModel.value.inProgressOrderID != null &&
+ userModel.value.inProgressOrderID!.isNotEmpty) {
+ String? validRideId;
- for (String id in userModel.value.inProgressOrderID!) {
- final rideDoc = await FireStoreUtils.fireStore.collection(CollectionName.rides).doc(id).get();
+ for (String id in userModel.value.inProgressOrderID!) {
+ final rideDoc =
+ await FireStoreUtils.fireStore
+ .collection(CollectionName.rides)
+ .doc(id)
+ .get();
- if (rideDoc.exists && (rideDoc.data()?['rideType'] ?? '').toString().toLowerCase() == "ride") {
- validRideId = userModel.value.inProgressOrderID!.first!;
- break;
- }
- }
-
- FireStoreUtils.fireStore.collection(CollectionName.rides).doc(validRideId).snapshots().listen((rideSnapshot) async {
- if (!rideSnapshot.exists) return;
-
- final rideData = rideSnapshot.data()!;
- currentOrder.value = CabOrderModel.fromJson(rideData);
- final status = currentOrder.value.status;
-
- if (status == Constant.driverAccepted || status == Constant.orderInTransit) {
- FireStoreUtils.fireStore.collection(CollectionName.users).doc(currentOrder.value.driverId).snapshots().listen((event) async {
- if (event.exists && event.data() != null) {
- UserModel driverModel0 = UserModel.fromJson(event.data()!);
- driverModel.value = driverModel0;
- await updateDriverRoute(driverModel0);
+ if (rideDoc.exists &&
+ (rideDoc.data()?['rideType'] ?? '')
+ .toString()
+ .toLowerCase() ==
+ "ride") {
+ validRideId = userModel.value.inProgressOrderID!.first!;
+ break;
}
- });
- }
+ }
- print("Current Ride Status: $status");
- if (status == Constant.orderPlaced || status == Constant.driverPending || status == Constant.driverRejected || (status == Constant.orderAccepted && currentOrder.value.driverId == null)) {
- bottomSheetType.value = 'waitingForDriver';
- } else if (status == Constant.driverAccepted || status == Constant.orderInTransit) {
- bottomSheetType.value = 'driverDetails';
- sourceTextEditController.value.text = currentOrder.value.sourceLocationName ?? '';
- destinationTextEditController.value.text = currentOrder.value.destinationLocationName ?? '';
- selectedPaymentMethod.value = currentOrder.value.paymentMethod ?? '';
- calculateTotalAmountAfterAccept();
- } else if (status == Constant.orderCompleted) {
- userModel.value.inProgressOrderID!.remove(validRideId);
- await FireStoreUtils.updateUser(userModel.value);
+ FireStoreUtils.fireStore
+ .collection(CollectionName.rides)
+ .doc(validRideId)
+ .snapshots()
+ .listen((rideSnapshot) async {
+ if (!rideSnapshot.exists) return;
+
+ final rideData = rideSnapshot.data()!;
+ currentOrder.value = CabOrderModel.fromJson(rideData);
+ final status = currentOrder.value.status;
+
+ if (status == Constant.driverAccepted ||
+ status == Constant.orderInTransit) {
+ FireStoreUtils.fireStore
+ .collection(CollectionName.users)
+ .doc(currentOrder.value.driverId)
+ .snapshots()
+ .listen((event) async {
+ if (event.exists && event.data() != null) {
+ UserModel driverModel0 = UserModel.fromJson(
+ event.data()!,
+ );
+ driverModel.value = driverModel0;
+ await updateDriverRoute(driverModel0);
+ }
+ });
+ }
+
+ print("Current Ride Status: $status");
+ if (status == Constant.orderPlaced ||
+ status == Constant.driverPending ||
+ status == Constant.driverRejected ||
+ (status == Constant.orderAccepted &&
+ currentOrder.value.driverId == null)) {
+ bottomSheetType.value = 'waitingForDriver';
+ } else if (status == Constant.driverAccepted ||
+ status == Constant.orderInTransit) {
+ bottomSheetType.value = 'driverDetails';
+ sourceTextEditController.value.text =
+ currentOrder.value.sourceLocationName ?? '';
+ destinationTextEditController.value.text =
+ currentOrder.value.destinationLocationName ?? '';
+ selectedPaymentMethod.value =
+ currentOrder.value.paymentMethod ?? '';
+ calculateTotalAmountAfterAccept();
+ } else if (status == Constant.orderCompleted) {
+ userModel.value.inProgressOrderID!.remove(validRideId);
+ await FireStoreUtils.updateUser(userModel.value);
+ bottomSheetType.value = 'location';
+ Get.back();
+ }
+ });
+ } else {
bottomSheetType.value = 'location';
- Get.back();
+ if (Constant.currentLocation != null) {
+ setDepartureMarker(
+ Constant.currentLocation!.latitude,
+ Constant.currentLocation!.longitude,
+ );
+ searchPlaceNameOSM();
+ }
}
});
- } else {
- bottomSheetType.value = 'location';
- if (Constant.currentLocation != null) {
- setDepartureMarker(Constant.currentLocation!.latitude, Constant.currentLocation!.longitude);
- searchPlaceNameOSM();
- }
- }
- });
final coupons = await FireStoreUtils.getCabCoupon();
cabCouponList.value = coupons;
@@ -217,18 +255,30 @@ class CabBookingController extends GetxController {
if (order.status == Constant.driverAccepted) {
// DRIVER → PICKUP
- await fetchRouteWithWaypoints([latlong.LatLng(driverLat, driverLng), latlong.LatLng(pickupLat, pickupLng)]);
+ await fetchRouteWithWaypoints([
+ latlong.LatLng(driverLat, driverLng),
+ latlong.LatLng(pickupLat, pickupLng),
+ ]);
} else if (order.status == Constant.orderInTransit) {
// PICKUP → DESTINATION
- await fetchRouteWithWaypoints([latlong.LatLng(driverLat, driverLng), latlong.LatLng(destLat, destLng)]);
+ await fetchRouteWithWaypoints([
+ latlong.LatLng(driverLat, driverLng),
+ latlong.LatLng(destLat, destLng),
+ ]);
}
updateRouteMarkers(driverModel);
} else {
/// For Google Maps
if (order.status == Constant.driverAccepted) {
- await fetchGoogleRouteBetween(LatLng(driverLat, driverLng), LatLng(pickupLat, pickupLng));
+ await fetchGoogleRouteBetween(
+ LatLng(driverLat, driverLng),
+ LatLng(pickupLat, pickupLng),
+ );
} else if (order.status == Constant.orderInTransit) {
- await fetchGoogleRouteBetween(LatLng(driverLat, driverLng), LatLng(destLat, destLng));
+ await fetchGoogleRouteBetween(
+ LatLng(driverLat, driverLng),
+ LatLng(destLat, destLng),
+ );
}
updateRouteMarkers(driverModel);
}
@@ -252,12 +302,24 @@ class CabBookingController extends GetxController {
markers.clear();
osmMarker.clear();
- final departureBytes = await Constant().getBytesFromAsset('assets/images/location_black3x.png', 50);
- final destinationBytes = await Constant().getBytesFromAsset('assets/images/location_orange3x.png', 50);
+ final departureBytes = await Constant().getBytesFromAsset(
+ 'assets/images/location_black3x.png',
+ 50,
+ );
+ final destinationBytes = await Constant().getBytesFromAsset(
+ 'assets/images/location_orange3x.png',
+ 50,
+ );
final driverBytesRaw =
(Constant.sectionConstantModel?.markerIcon?.isNotEmpty ?? false)
- ? await Constant().getBytesFromUrl(Constant.sectionConstantModel!.markerIcon!, width: 120)
- : await Constant().getBytesFromAsset('assets/images/ic_cab.png', 50);
+ ? await Constant().getBytesFromUrl(
+ Constant.sectionConstantModel!.markerIcon!,
+ width: 120,
+ )
+ : await Constant().getBytesFromAsset(
+ 'assets/images/ic_cab.png',
+ 50,
+ );
departureIcon = BitmapDescriptor.fromBytes(departureBytes);
destinationIcon = BitmapDescriptor.fromBytes(destinationBytes);
@@ -266,7 +328,15 @@ class CabBookingController extends GetxController {
if (Constant.selectedMapType == 'osm') {
if (order.status == Constant.driverAccepted) {
osmMarker.addAll([
- flutterMap.Marker(point: latlong.LatLng(pickupLat, pickupLng), width: 40, height: 40, child: Image.asset('assets/images/location_black3x.png', width: 40)),
+ flutterMap.Marker(
+ point: latlong.LatLng(pickupLat, pickupLng),
+ width: 40,
+ height: 40,
+ child: Image.asset(
+ 'assets/images/location_black3x.png',
+ width: 40,
+ ),
+ ),
flutterMap.Marker(
point: latlong.LatLng(driverLat, driverLng),
width: 45,
@@ -277,13 +347,26 @@ class CabBookingController extends GetxController {
height: 50,
imageUrl: Constant.sectionConstantModel!.markerIcon.toString(),
placeholder: (context, url) => Constant.loader(),
- errorWidget: (context, url, error) => SizedBox(width: 30, height: 30, child: CircularProgressIndicator(strokeWidth: 2)),
+ errorWidget:
+ (context, url, error) => SizedBox(
+ width: 30,
+ height: 30,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
),
),
]);
} else if (order.status == Constant.orderInTransit) {
osmMarker.addAll([
- flutterMap.Marker(point: latlong.LatLng(destLat, destLng), width: 40, height: 40, child: Image.asset('assets/images/location_orange3x.png', width: 40)),
+ flutterMap.Marker(
+ point: latlong.LatLng(destLat, destLng),
+ width: 40,
+ height: 40,
+ child: Image.asset(
+ 'assets/images/location_orange3x.png',
+ width: 40,
+ ),
+ ),
flutterMap.Marker(
point: latlong.LatLng(driverLat, driverLng),
width: 45,
@@ -294,7 +377,12 @@ class CabBookingController extends GetxController {
height: 50,
imageUrl: Constant.sectionConstantModel!.markerIcon.toString(),
placeholder: (context, url) => Constant.loader(),
- errorWidget: (context, url, error) => SizedBox(width: 30, height: 30, child: CircularProgressIndicator(strokeWidth: 2)),
+ errorWidget:
+ (context, url, error) => SizedBox(
+ width: 30,
+ height: 30,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
),
),
]);
@@ -306,9 +394,18 @@ class CabBookingController extends GetxController {
markerId: const MarkerId("pickup"),
position: LatLng(pickupLat, pickupLng),
infoWindow: InfoWindow(title: "Pickup Location".tr()),
- icon: departureIcon ?? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
+ icon:
+ departureIcon ??
+ BitmapDescriptor.defaultMarkerWithHue(
+ BitmapDescriptor.hueGreen,
+ ),
+ ),
+ Marker(
+ markerId: const MarkerId("driver"),
+ position: LatLng(driverLat, driverLng),
+ infoWindow: InfoWindow(title: "Driver at Pickup".tr()),
+ icon: taxiIcon ?? BitmapDescriptor.defaultMarker,
),
- Marker(markerId: const MarkerId("driver"), position: LatLng(driverLat, driverLng), infoWindow: InfoWindow(title: "Driver at Pickup".tr()), icon: taxiIcon ?? BitmapDescriptor.defaultMarker),
]);
} else if (order.status == Constant.orderInTransit) {
markers.addAll([
@@ -316,9 +413,18 @@ class CabBookingController extends GetxController {
markerId: const MarkerId("destination"),
position: LatLng(destLat, destLng),
infoWindow: InfoWindow(title: "Destination Location".tr()),
- icon: destinationIcon ?? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
+ icon:
+ destinationIcon ??
+ BitmapDescriptor.defaultMarkerWithHue(
+ BitmapDescriptor.hueRed,
+ ),
+ ),
+ Marker(
+ markerId: const MarkerId("driver"),
+ position: LatLng(driverLat, driverLng),
+ infoWindow: InfoWindow(title: "Driver Location".tr()),
+ icon: taxiIcon ?? BitmapDescriptor.defaultMarker,
),
- Marker(markerId: const MarkerId("driver"), position: LatLng(driverLat, driverLng), infoWindow: InfoWindow(title: "Driver Location".tr()), icon: taxiIcon ?? BitmapDescriptor.defaultMarker),
]);
}
}
@@ -329,7 +435,10 @@ class CabBookingController extends GetxController {
}
}
- Future fetchGoogleRouteBetween(LatLng originPoint, LatLng destPoint) async {
+ Future fetchGoogleRouteBetween(
+ LatLng originPoint,
+ LatLng destPoint,
+ ) async {
final origin = '${originPoint.latitude},${originPoint.longitude}';
final destination = '${destPoint.latitude},${destPoint.longitude}';
final url = Uri.parse(
@@ -346,7 +455,8 @@ class CabBookingController extends GetxController {
final route = data['routes'][0];
final encodedPolyline = route['overview_polyline']['points'];
final decodedPoints = PolylinePoints.decodePolyline(encodedPolyline);
- final coordinates = decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
+ final coordinates =
+ decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
addPolyLine(coordinates);
@@ -373,7 +483,12 @@ class CabBookingController extends GetxController {
if (currentOrder.value.taxSetting != null) {
for (var element in currentOrder.value.taxSetting!) {
- taxAmount.value = (taxAmount.value + Constant.calculateTax(amount: (subTotal.value - discount.value).toString(), taxModel: element));
+ taxAmount.value =
+ (taxAmount.value +
+ Constant.calculateTax(
+ amount: (subTotal.value - discount.value).toString(),
+ taxModel: element,
+ ));
}
}
@@ -389,11 +504,19 @@ class CabBookingController extends GetxController {
subTotal.value = getAmount(selectedVehicleType.value);
if (selectedCouponModel.value.id != null) {
- discount.value = Constant.calculateDiscount(amount: subTotal.value.toString(), offerModel: selectedCouponModel.value);
+ discount.value = Constant.calculateDiscount(
+ amount: subTotal.value.toString(),
+ offerModel: selectedCouponModel.value,
+ );
}
for (var element in Constant.taxList) {
- taxAmount.value = (taxAmount.value + Constant.calculateTax(amount: (subTotal.value - discount.value).toString(), taxModel: element));
+ taxAmount.value =
+ (taxAmount.value +
+ Constant.calculateTax(
+ amount: (subTotal.value - discount.value).toString(),
+ taxModel: element,
+ ));
}
totalAmount.value = (subTotal.value - discount.value) + taxAmount.value;
@@ -430,9 +553,14 @@ class CabBookingController extends GetxController {
serviceType: Constant.parcelServiceType,
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-${totalAmount.value.toString()}", userId: FireStoreUtils.getCurrentUid());
+ await FireStoreUtils.updateUserWallet(
+ amount: "-${totalAmount.value.toString()}",
+ userId: FireStoreUtils.getCurrentUid(),
+ );
}
});
}
@@ -446,13 +574,25 @@ class CabBookingController extends GetxController {
Future placeOrder() async {
DestinationLocation sourceLocation = DestinationLocation(
- latitude: Constant.selectedMapType == 'osm' ? departureLatLongOsm.value.latitude : departureLatLong.value.latitude,
- longitude: Constant.selectedMapType == 'osm' ? departureLatLongOsm.value.longitude : departureLatLong.value.longitude,
+ latitude:
+ Constant.selectedMapType == 'osm'
+ ? departureLatLongOsm.value.latitude
+ : departureLatLong.value.latitude,
+ longitude:
+ Constant.selectedMapType == 'osm'
+ ? departureLatLongOsm.value.longitude
+ : departureLatLong.value.longitude,
);
DestinationLocation destinationLocation = DestinationLocation(
- latitude: Constant.selectedMapType == 'osm' ? destinationLatLongOsm.value.latitude : destinationLatLong.value.latitude,
- longitude: Constant.selectedMapType == 'osm' ? destinationLatLongOsm.value.longitude : destinationLatLong.value.longitude,
+ latitude:
+ Constant.selectedMapType == 'osm'
+ ? destinationLatLongOsm.value.latitude
+ : destinationLatLong.value.latitude,
+ longitude:
+ Constant.selectedMapType == 'osm'
+ ? destinationLatLongOsm.value.longitude
+ : destinationLatLong.value.longitude,
);
CabOrderModel orderModel = CabOrderModel();
@@ -463,7 +603,8 @@ class CabBookingController extends GetxController {
orderModel.vehicleType = selectedVehicleType.value;
orderModel.authorID = FireStoreUtils.getCurrentUid();
orderModel.sourceLocationName = sourceTextEditController.value.text;
- orderModel.destinationLocationName = destinationTextEditController.value.text;
+ orderModel.destinationLocationName =
+ destinationTextEditController.value.text;
orderModel.sourceLocation = sourceLocation;
orderModel.destinationLocation = destinationLocation;
@@ -475,11 +616,14 @@ class CabBookingController extends GetxController {
orderModel.taxSetting = Constant.taxList;
orderModel.adminCommissionType =
- Constant.sectionConstantModel!.adminCommision != null && Constant.sectionConstantModel!.adminCommision!.isEnabled == true
- ? Constant.sectionConstantModel!.adminCommision!.commissionType.toString()
+ Constant.sectionConstantModel!.adminCommision != null &&
+ Constant.sectionConstantModel!.adminCommision!.isEnabled == true
+ ? Constant.sectionConstantModel!.adminCommision!.commissionType
+ .toString()
: null;
orderModel.adminCommission =
- Constant.sectionConstantModel!.adminCommision != null && Constant.sectionConstantModel!.adminCommision!.isEnabled == true
+ Constant.sectionConstantModel!.adminCommision != null &&
+ Constant.sectionConstantModel!.adminCommision!.isEnabled == true
? Constant.sectionConstantModel!.adminCommision!.amount.toString()
: null;
orderModel.couponCode = couponCodeTextEditController.value.text;
@@ -492,7 +636,9 @@ class CabBookingController extends GetxController {
orderModel.roundTrip = false;
orderModel.sectionId = Constant.sectionConstantModel!.id;
orderModel.createdAt = Timestamp.now();
- orderModel.otpCode = (maths.Random().nextInt(9000) + 1000).toString(); // Generate a 4-digit OTP
+ orderModel.otpCode =
+ (maths.Random().nextInt(9000) + 1000)
+ .toString(); // Generate a 4-digit OTP
orderModel.status = Constant.orderPlaced;
orderModel.scheduleDateTime = Timestamp.now();
log("Order Model : ${orderModel.toJson()}");
@@ -507,8 +653,10 @@ class CabBookingController extends GetxController {
double getAmount(VehicleType vehicleType) {
final double currentDistance = distance.value;
- if (currentDistance <= (vehicleType.minimum_delivery_charges_within_km ?? 0)) {
- return double.tryParse(vehicleType.minimum_delivery_charges.toString()) ?? 0.0;
+ if (currentDistance <=
+ (vehicleType.minimum_delivery_charges_within_km ?? 0)) {
+ return double.tryParse(vehicleType.minimum_delivery_charges.toString()) ??
+ 0.0;
} else {
return (vehicleType.delivery_charges_per_km ?? 0.0) * currentDistance;
}
@@ -533,28 +681,50 @@ class CabBookingController extends GetxController {
void setStopMarker(double lat, double lng, int index) {
if (Constant.selectedMapType == 'osm') {
// Add new stop marker without clearing
- osmMarker.add(flutterMap.Marker(point: latlong.LatLng(lat, lng), width: 40, height: 40, child: stopIconOsm!));
+ osmMarker.add(
+ flutterMap.Marker(
+ point: latlong.LatLng(lat, lng),
+ width: 40,
+ height: 40,
+ child: stopIconOsm!,
+ ),
+ );
getDirections(isStopMarker: true);
} else {
final markerId = MarkerId('Stop $index');
markers.removeWhere((marker) => marker.markerId == markerId);
- markers.add(Marker(markerId: markerId, infoWindow: InfoWindow(title: '${'Stop'.tr()} ${String.fromCharCode(index + 65)}'), position: LatLng(lat, lng), icon: stopIcon!));
+ markers.add(
+ Marker(
+ markerId: markerId,
+ infoWindow: InfoWindow(
+ title: '${'Stop'.tr()} ${String.fromCharCode(index + 65)}',
+ ),
+ position: LatLng(lat, lng),
+ icon: stopIcon!,
+ ),
+ );
getDirections();
}
}
void _setOsmMarker(double lat, double lng, {required bool isDeparture}) {
- final marker = flutterMap.Marker(point: latlong.LatLng(lat, lng), width: 40, height: 40, child: isDeparture ? departureIconOsm! : destinationIconOsm!);
+ final marker = flutterMap.Marker(
+ point: latlong.LatLng(lat, lng),
+ width: 40,
+ height: 40,
+ child: isDeparture ? departureIconOsm! : destinationIconOsm!,
+ );
if (isDeparture) {
departureLatLongOsm.value = latlong.LatLng(lat, lng);
} else {
destinationLatLongOsm.value = latlong.LatLng(lat, lng);
}
osmMarker.add(marker);
- if (departureLatLongOsm.value.latitude != 0 && destinationLatLongOsm.value.latitude != 0) {
+ if (departureLatLongOsm.value.latitude != 0 &&
+ destinationLatLongOsm.value.latitude != 0) {
getDirections();
animateToSource(lat, lng);
}
@@ -576,14 +746,26 @@ class CabBookingController extends GetxController {
markers.removeWhere((marker) => marker.markerId == markerId);
// Add new marker
- markers.add(Marker(markerId: markerId, position: pos, icon: icon, infoWindow: InfoWindow(title: title)));
+ markers.add(
+ Marker(
+ markerId: markerId,
+ position: pos,
+ icon: icon,
+ infoWindow: InfoWindow(title: title),
+ ),
+ );
mapController.animateCamera(CameraUpdate.newLatLngZoom(pos, 14));
- if (departureLatLong.value.latitude != 0 && destinationLatLong.value.latitude != 0) {
+ if (departureLatLong.value.latitude != 0 &&
+ destinationLatLong.value.latitude != 0) {
getDirections();
} else {
- mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: LatLng(lat, lng), zoom: 14)));
+ mapController.animateCamera(
+ CameraUpdate.newCameraPosition(
+ CameraPosition(target: LatLng(lat, lng), zoom: 14),
+ ),
+ );
}
}
@@ -592,25 +774,43 @@ class CabBookingController extends GetxController {
final wayPoints = [];
// Only add valid source
- if (departureLatLongOsm.value.latitude != 0.0 && departureLatLongOsm.value.longitude != 0.0) {
+ if (departureLatLongOsm.value.latitude != 0.0 &&
+ departureLatLongOsm.value.longitude != 0.0) {
wayPoints.add(departureLatLongOsm.value);
}
// Only add valid destination
- if (destinationLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.longitude != 0.0) {
+ if (destinationLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.longitude != 0.0) {
wayPoints.add(destinationLatLongOsm.value);
}
if (!isStopMarker) osmMarker.clear();
// Add source marker
- if (departureLatLongOsm.value.latitude != 0.0 && departureLatLongOsm.value.longitude != 0.0) {
- osmMarker.add(flutterMap.Marker(point: departureLatLongOsm.value, width: 40, height: 40, child: departureIconOsm!));
+ if (departureLatLongOsm.value.latitude != 0.0 &&
+ departureLatLongOsm.value.longitude != 0.0) {
+ osmMarker.add(
+ flutterMap.Marker(
+ point: departureLatLongOsm.value,
+ width: 40,
+ height: 40,
+ child: departureIconOsm!,
+ ),
+ );
}
// Add destination marker
- if (destinationLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.longitude != 0.0) {
- osmMarker.add(flutterMap.Marker(point: destinationLatLongOsm.value, width: 40, height: 40, child: destinationIconOsm!));
+ if (destinationLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.longitude != 0.0) {
+ osmMarker.add(
+ flutterMap.Marker(
+ point: destinationLatLongOsm.value,
+ width: 40,
+ height: 40,
+ child: destinationIconOsm!,
+ ),
+ );
}
if (wayPoints.length >= 2) {
@@ -623,10 +823,14 @@ class CabBookingController extends GetxController {
}
Future fetchGoogleRouteWithWaypoints() async {
- if (departureLatLong.value.latitude == 0.0 || destinationLatLong.value.latitude == 0.0) return;
+ if (departureLatLong.value.latitude == 0.0 ||
+ destinationLatLong.value.latitude == 0.0)
+ return;
- final origin = '${departureLatLong.value.latitude},${departureLatLong.value.longitude}';
- final destination = '${destinationLatLong.value.latitude},${destinationLatLong.value.longitude}';
+ final origin =
+ '${departureLatLong.value.latitude},${departureLatLong.value.longitude}';
+ final destination =
+ '${destinationLatLong.value.latitude},${destinationLatLong.value.longitude}';
final url = Uri.parse(
'https://maps.googleapis.com/maps/api/directions/json'
@@ -645,7 +849,8 @@ class CabBookingController extends GetxController {
// Polyline
final encodedPolyline = route['overview_polyline']['points'];
final decodedPoints = PolylinePoints.decodePolyline(encodedPolyline);
- final coordinates = decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
+ final coordinates =
+ decodedPoints.map((e) => LatLng(e.latitude, e.longitude)).toList();
addPolyLine(coordinates);
@@ -677,19 +882,26 @@ class CabBookingController extends GetxController {
}
Future fetchRouteWithWaypoints(List points) async {
- final coordinates = points.map((p) => '${p.longitude},${p.latitude}').join(';');
- final url = Uri.parse('https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson');
+ final coordinates = points
+ .map((p) => '${p.longitude},${p.latitude}')
+ .join(';');
+ final url = Uri.parse(
+ 'https://router.project-osrm.org/route/v1/driving/$coordinates?overview=full&geometries=geojson',
+ );
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final decoded = json.decode(response.body);
- final geometry = decoded['routes'][0]['geometry']['coordinates'] as List;
+ final geometry =
+ decoded['routes'][0]['geometry']['coordinates'] as List;
final dist = decoded['routes'][0]['distance'];
final dur = decoded['routes'][0]['duration'];
routePoints.clear();
- routePoints.addAll(geometry.map((coord) => latlong.LatLng(coord[1], coord[0])));
+ routePoints.addAll(
+ geometry.map((coord) => latlong.LatLng(coord[1], coord[0])),
+ );
if (Constant.distanceType.toLowerCase() == "KM".toLowerCase()) {
distance.value = dist / 1000.00;
@@ -714,7 +926,10 @@ class CabBookingController extends GetxController {
void zoomToPolylineOSM() {
if (routePoints.isEmpty) return;
// LatLngBounds requires at least two points
- final bounds = flutterMap.LatLngBounds(routePoints.first, routePoints.first);
+ final bounds = flutterMap.LatLngBounds(
+ routePoints.first,
+ routePoints.first,
+ );
for (final point in routePoints) {
bounds.extend(point);
}
@@ -726,8 +941,10 @@ class CabBookingController extends GetxController {
double getBoundsZoomLevel(flutterMap.LatLngBounds bounds) {
// Simple heuristic: zoom out for larger bounds
- final latDiff = (bounds.northEast.latitude - bounds.southWest.latitude).abs();
- final lngDiff = (bounds.northEast.longitude - bounds.southWest.longitude).abs();
+ final latDiff =
+ (bounds.northEast.latitude - bounds.southWest.latitude).abs();
+ final lngDiff =
+ (bounds.northEast.longitude - bounds.southWest.longitude).abs();
double maxDiff = math.max(latDiff, lngDiff);
if (maxDiff < 0.005) return 18.0;
if (maxDiff < 0.01) return 16.0;
@@ -739,7 +956,13 @@ class CabBookingController extends GetxController {
void addPolyLine(List points) {
final id = const PolylineId("poly");
- final polyline = Polyline(polylineId: id, color: AppThemeData.primary300, points: points, width: 6, geodesic: true);
+ final polyline = Polyline(
+ polylineId: id,
+ color: AppThemeData.primary300,
+ points: points,
+ width: 6,
+ geodesic: true,
+ );
polyLines[id] = polyline;
if (points.length >= 2) {
@@ -748,7 +971,10 @@ class CabBookingController extends GetxController {
}
}
- Future updateCameraLocationToFitPolyline(List points, GoogleMapController? mapController) async {
+ Future updateCameraLocationToFitPolyline(
+ List points,
+ GoogleMapController? mapController,
+ ) async {
if (mapController == null || points.isEmpty) return;
double minLat = points.first.latitude, maxLat = points.first.latitude;
double minLng = points.first.longitude, maxLng = points.first.longitude;
@@ -758,16 +984,24 @@ class CabBookingController extends GetxController {
if (p.longitude < minLng) minLng = p.longitude;
if (p.longitude > maxLng) maxLng = p.longitude;
}
- final bounds = LatLngBounds(southwest: LatLng(minLat, minLng), northeast: LatLng(maxLat, maxLng));
+ final bounds = LatLngBounds(
+ southwest: LatLng(minLat, minLng),
+ northeast: LatLng(maxLat, maxLng),
+ );
final cameraUpdate = CameraUpdate.newLatLngBounds(bounds, 50);
await checkCameraLocation(cameraUpdate, mapController);
}
Future animateToSource(double lat, double long) async {
- final hasBothCoords = departureLatLongOsm.value.latitude != 0.0 && destinationLatLongOsm.value.latitude != 0.0;
+ final hasBothCoords =
+ departureLatLongOsm.value.latitude != 0.0 &&
+ destinationLatLongOsm.value.latitude != 0.0;
if (hasBothCoords) {
- await calculateZoomLevel(source: departureLatLongOsm.value, destination: destinationLatLongOsm.value);
+ await calculateZoomLevel(
+ source: departureLatLongOsm.value,
+ destination: destinationLatLongOsm.value,
+ );
} else {
mapOsmController.move(latlong.LatLng(lat, long), 10);
}
@@ -775,15 +1009,25 @@ class CabBookingController extends GetxController {
RxMap polyLines = {}.obs;
- Future calculateZoomLevel({required latlong.LatLng source, required latlong.LatLng destination, double paddingFraction = 0.001}) async {
+ Future calculateZoomLevel({
+ required latlong.LatLng source,
+ required latlong.LatLng destination,
+ double paddingFraction = 0.001,
+ }) async {
final bounds = flutterMap.LatLngBounds.fromPoints([source, destination]);
final screenSize = Size(Get.width, Get.height * 0.5);
const double worldDimension = 256.0;
const double maxZoom = 10.0;
- double latToRad(double lat) => math.log((1 + math.sin(lat * math.pi / 180)) / (1 - math.sin(lat * math.pi / 180))) / 2;
+ double latToRad(double lat) =>
+ math.log(
+ (1 + math.sin(lat * math.pi / 180)) /
+ (1 - math.sin(lat * math.pi / 180)),
+ ) /
+ 2;
- double computeZoom(double screenPx, double worldPx, double fraction) => math.log(screenPx / worldPx / fraction) / math.ln2;
+ double computeZoom(double screenPx, double worldPx, double fraction) =>
+ math.log(screenPx / worldPx / fraction) / math.ln2;
final north = bounds.northEast.latitude;
final south = bounds.southWest.latitude;
@@ -801,27 +1045,48 @@ class CabBookingController extends GetxController {
final latFraction = (latToRad(north) - latToRad(south)) / math.pi;
final lngFraction = ((east - west + 360) % 360) / 360;
- final latZoom = computeZoom(screenSize.height, worldDimension, latFraction + paddingFraction);
- final lngZoom = computeZoom(screenSize.width, worldDimension, lngFraction + paddingFraction);
+ final latZoom = computeZoom(
+ screenSize.height,
+ worldDimension,
+ latFraction + paddingFraction,
+ );
+ final lngZoom = computeZoom(
+ screenSize.width,
+ worldDimension,
+ lngFraction + paddingFraction,
+ );
final zoomLevel = math.min(latZoom, lngZoom).clamp(0.0, maxZoom);
mapOsmController.move(center, zoomLevel);
}
}
- Future updateCameraLocation(LatLng source, LatLng destination, GoogleMapController? mapController) async {
+ Future updateCameraLocation(
+ LatLng source,
+ LatLng destination,
+ GoogleMapController? mapController,
+ ) async {
if (mapController == null) return;
final bounds = LatLngBounds(
- southwest: LatLng(math.min(source.latitude, destination.latitude), math.min(source.longitude, destination.longitude)),
- northeast: LatLng(math.max(source.latitude, destination.latitude), math.max(source.longitude, destination.longitude)),
+ southwest: LatLng(
+ math.min(source.latitude, destination.latitude),
+ math.min(source.longitude, destination.longitude),
+ ),
+ northeast: LatLng(
+ math.max(source.latitude, destination.latitude),
+ math.max(source.longitude, destination.longitude),
+ ),
);
final cameraUpdate = CameraUpdate.newLatLngBounds(bounds, 90);
await checkCameraLocation(cameraUpdate, mapController);
}
- Future checkCameraLocation(CameraUpdate cameraUpdate, GoogleMapController mapController) async {
+ Future checkCameraLocation(
+ CameraUpdate cameraUpdate,
+ GoogleMapController mapController,
+ ) async {
await mapController.animateCamera(cameraUpdate);
final l1 = await mapController.getVisibleRegion();
final l2 = await mapController.getVisibleRegion();
@@ -834,16 +1099,44 @@ class CabBookingController extends GetxController {
Future setIcons() async {
try {
if (Constant.selectedMapType == 'osm') {
- departureIconOsm = Image.asset("assets/icons/pickup.png", width: 30, height: 30);
- destinationIconOsm = Image.asset("assets/icons/dropoff.png", width: 30, height: 30);
- taxiIconOsm = Image.asset("assets/icons/ic_taxi.png", width: 30, height: 30);
- stopIconOsm = Image.asset("assets/icons/location.png", width: 26, height: 26);
+ departureIconOsm = Image.asset(
+ "assets/icons/pickup.png",
+ width: 30,
+ height: 30,
+ );
+ destinationIconOsm = Image.asset(
+ "assets/icons/dropoff.png",
+ width: 30,
+ height: 30,
+ );
+ taxiIconOsm = Image.asset(
+ "assets/icons/ic_taxi.png",
+ width: 30,
+ height: 30,
+ );
+ stopIconOsm = Image.asset(
+ "assets/icons/location.png",
+ width: 26,
+ height: 26,
+ );
} else {
const config = ImageConfiguration(size: Size(48, 48));
- departureIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/pickup.png");
- destinationIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/dropoff.png");
- taxiIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/ic_taxi.png");
- stopIcon = await BitmapDescriptor.fromAssetImage(config, "assets/icons/location.png");
+ departureIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/pickup.png",
+ );
+ destinationIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/dropoff.png",
+ );
+ taxiIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/ic_taxi.png",
+ );
+ stopIcon = await BitmapDescriptor.fromAssetImage(
+ config,
+ "assets/icons/location.png",
+ );
}
} catch (e) {
print('Error loading icons: $e');
@@ -851,8 +1144,12 @@ class CabBookingController extends GetxController {
}
void clearMapDataIfLocationsRemoved() {
- final isSourceEmpty = departureLatLongOsm.value.latitude == 0.0 && departureLatLongOsm.value.longitude == 0.0;
- final isDestinationEmpty = destinationLatLongOsm.value.latitude == 0.0 && destinationLatLongOsm.value.longitude == 0.0;
+ final isSourceEmpty =
+ departureLatLongOsm.value.latitude == 0.0 &&
+ departureLatLongOsm.value.longitude == 0.0;
+ final isDestinationEmpty =
+ destinationLatLongOsm.value.latitude == 0.0 &&
+ destinationLatLongOsm.value.longitude == 0.0;
if (isSourceEmpty || isDestinationEmpty) {
// Clear polylines
@@ -881,7 +1178,9 @@ class CabBookingController extends GetxController {
// Remove marker
if (Constant.selectedMapType == 'osm') {
- osmMarker.removeWhere((marker) => marker.point == departureLatLongOsm.value);
+ osmMarker.removeWhere(
+ (marker) => marker.point == departureLatLongOsm.value,
+ );
} else {
markers.removeWhere((marker) => marker.markerId.value == 'Departure');
}
@@ -897,7 +1196,9 @@ class CabBookingController extends GetxController {
destinationTextEditController.value.clear();
if (Constant.selectedMapType == 'osm') {
- osmMarker.removeWhere((marker) => marker.point == destinationLatLongOsm.value);
+ osmMarker.removeWhere(
+ (marker) => marker.point == destinationLatLongOsm.value,
+ );
} else {
markers.removeWhere((marker) => marker.markerId.value == 'Destination');
}
@@ -907,9 +1208,16 @@ class CabBookingController extends GetxController {
}
Future searchPlaceNameOSM() async {
- final url = Uri.parse('https://nominatim.openstreetmap.org/reverse?lat=${departureLatLongOsm.value.latitude}&lon=${departureLatLongOsm.value.longitude}&format=json');
+ final url = Uri.parse(
+ 'https://nominatim.openstreetmap.org/reverse?lat=${departureLatLongOsm.value.latitude}&lon=${departureLatLongOsm.value.longitude}&format=json',
+ );
- final response = await http.get(url, headers: {'User-Agent': 'FlutterMapApp/1.0 (menil.siddhiinfosoft@gmail.com)'});
+ final response = await http.get(
+ url,
+ headers: {
+ 'User-Agent': 'FlutterMapApp/1.0 (menil.siddhiinfosoft@gmail.com)',
+ },
+ );
if (response.statusCode == 200) {
log("response.body :: ${response.body}");
@@ -922,7 +1230,9 @@ class CabBookingController extends GetxController {
final lat = departureLatLong.value.latitude;
final lng = departureLatLong.value.longitude;
- final url = Uri.parse('https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=${Constant.mapAPIKey}');
+ final url = Uri.parse(
+ 'https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=${Constant.mapAPIKey}',
+ );
final response = await http.get(url);
@@ -965,19 +1275,45 @@ class CabBookingController extends GetxController {
Future getPaymentSettings() async {
await FireStoreUtils.getPaymentSettingsData().then((value) {
- stripeModel.value = StripeModel.fromJson(jsonDecode(Preferences.getString(Preferences.stripeSettings)));
- payPalModel.value = PayPalModel.fromJson(jsonDecode(Preferences.getString(Preferences.paypalSettings)));
- payStackModel.value = PayStackModel.fromJson(jsonDecode(Preferences.getString(Preferences.payStack)));
- mercadoPagoModel.value = MercadoPagoModel.fromJson(jsonDecode(Preferences.getString(Preferences.mercadoPago)));
- flutterWaveModel.value = FlutterWaveModel.fromJson(jsonDecode(Preferences.getString(Preferences.flutterWave)));
- paytmModel.value = PaytmModel.fromJson(jsonDecode(Preferences.getString(Preferences.paytmSettings)));
- payFastModel.value = PayFastModel.fromJson(jsonDecode(Preferences.getString(Preferences.payFastSettings)));
- razorPayModel.value = RazorPayModel.fromJson(jsonDecode(Preferences.getString(Preferences.razorpaySettings)));
- midTransModel.value = MidTrans.fromJson(jsonDecode(Preferences.getString(Preferences.midTransSettings)));
- orangeMoneyModel.value = OrangeMoney.fromJson(jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)));
- xenditModel.value = Xendit.fromJson(jsonDecode(Preferences.getString(Preferences.xenditSettings)));
- walletSettingModel.value = WalletSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.walletSettings)));
- cashOnDeliverySettingModel.value = CodSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.codSettings)));
+ stripeModel.value = StripeModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.stripeSettings)),
+ );
+ payPalModel.value = PayPalModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paypalSettings)),
+ );
+ payStackModel.value = PayStackModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payStack)),
+ );
+ mercadoPagoModel.value = MercadoPagoModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.mercadoPago)),
+ );
+ flutterWaveModel.value = FlutterWaveModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.flutterWave)),
+ );
+ paytmModel.value = PaytmModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paytmSettings)),
+ );
+ payFastModel.value = PayFastModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payFastSettings)),
+ );
+ razorPayModel.value = RazorPayModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.razorpaySettings)),
+ );
+ midTransModel.value = MidTrans.fromJson(
+ jsonDecode(Preferences.getString(Preferences.midTransSettings)),
+ );
+ orangeMoneyModel.value = OrangeMoney.fromJson(
+ jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)),
+ );
+ xenditModel.value = Xendit.fromJson(
+ jsonDecode(Preferences.getString(Preferences.xenditSettings)),
+ );
+ walletSettingModel.value = WalletSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.walletSettings)),
+ );
+ cashOnDeliverySettingModel.value = CodSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.codSettings)),
+ );
if (walletSettingModel.value.isEnabled == true) {
selectedPaymentMethod.value = PaymentGateway.wallet.name;
@@ -1019,20 +1355,32 @@ class CabBookingController extends GetxController {
Future stripeMakePayment({required String amount}) async {
log(double.parse(amount).toStringAsFixed(0));
try {
- Map? paymentIntentData = await createStripeIntent(amount: amount);
+ Map? paymentIntentData = await createStripeIntent(
+ amount: amount,
+ );
log("stripe Responce====>$paymentIntentData");
if (paymentIntentData!.containsKey("error")) {
Get.back();
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
} else {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentData['client_secret'],
allowsDelayedPaymentMethods: false,
- googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'US', testEnv: true, currencyCode: "USD"),
+ googlePay: const PaymentSheetGooglePay(
+ merchantCountryCode: 'US',
+ testEnv: true,
+ currencyCode: "USD",
+ ),
customFlow: true,
style: ThemeMode.system,
- appearance: PaymentSheetAppearance(colors: PaymentSheetAppearanceColors(primary: AppThemeData.primary300)),
+ appearance: PaymentSheetAppearance(
+ colors: PaymentSheetAppearanceColors(
+ primary: AppThemeData.primary300,
+ ),
+ ),
merchantDisplayName: 'GoRide',
),
);
@@ -1078,7 +1426,10 @@ class CabBookingController extends GetxController {
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
body: body,
- headers: {'Authorization': 'Bearer $stripeSecret', 'Content-Type': 'application/x-www-form-urlencoded'},
+ headers: {
+ 'Authorization': 'Bearer $stripeSecret',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
);
return jsonDecode(response.body);
@@ -1088,8 +1439,14 @@ class CabBookingController extends GetxController {
}
//mercadoo
- Future mercadoPagoMakePayment({required BuildContext context, required String amount}) async {
- final headers = {'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}', 'Content-Type': 'application/json'};
+ Future mercadoPagoMakePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
+ final headers = {
+ 'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"items": [
@@ -1102,12 +1459,20 @@ class CabBookingController extends GetxController {
},
],
"payer": {"email": userModel.value.email},
- "back_urls": {"failure": "${Constant.globalUrl}payment/failure", "pending": "${Constant.globalUrl}payment/pending", "success": "${Constant.globalUrl}payment/success"},
+ "back_urls": {
+ "failure": "${Constant.globalUrl}payment/failure",
+ "pending": "${Constant.globalUrl}payment/pending",
+ "success": "${Constant.globalUrl}payment/success",
+ },
"auto_return": "approved",
// Automatically return after payment is approved
});
- final response = await http.post(Uri.parse("https://api.mercadopago.com/checkout/preferences"), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse("https://api.mercadopago.com/checkout/preferences"),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
final data = jsonDecode(response.body);
@@ -1165,9 +1530,12 @@ class CabBookingController extends GetxController {
///PayStack Payment Method
Future payStackPayment(String totalAmount) async {
- await PayStackURLGen.payStackURLGen(amount: (double.parse(totalAmount) * 100).toString(), currency: "ZAR", secretKey: payStackModel.value.secretKey.toString(), userModel: userModel.value).then((
- value,
- ) async {
+ await PayStackURLGen.payStackURLGen(
+ amount: (double.parse(totalAmount) * 100).toString(),
+ currency: "ZAR",
+ secretKey: payStackModel.value.secretKey.toString(),
+ userModel: userModel.value,
+ ).then((value) async {
if (value != null) {
PayStackUrlModel payStackModel0 = value;
Get.to(
@@ -1187,15 +1555,23 @@ class CabBookingController extends GetxController {
}
});
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
}
});
}
//flutter wave Payment Method
- Future flutterWaveInitiatePayment({required BuildContext context, required String amount}) async {
+ Future flutterWaveInitiatePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
final url = Uri.parse('https://api.flutterwave.com/v3/payments');
- final headers = {'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}', 'Content-Type': 'application/json'};
+ final headers = {
+ 'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"tx_ref": _ref,
@@ -1208,14 +1584,19 @@ class CabBookingController extends GetxController {
"phonenumber": userModel.value.phoneNumber, // Add a real phone number
"name": userModel.value.fullName(), // Add a real customer name
},
- "customizations": {"title": "Payment for Services", "description": "Payment for XYZ services"},
+ "customizations": {
+ "title": "Payment for Services",
+ "description": "Payment for XYZ services",
+ },
});
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
- Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((value) {
+ Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((
+ value,
+ ) {
if (value) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1244,8 +1625,14 @@ class CabBookingController extends GetxController {
// payFast
void payFastPayment({required BuildContext context, required String amount}) {
- PayStackURLGen.getPayHTML(payFastSettingData: payFastModel.value, amount: amount.toString(), userModel: userModel.value).then((String? value) async {
- bool isDone = await Get.to(PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value));
+ PayStackURLGen.getPayHTML(
+ payFastSettingData: payFastModel.value,
+ amount: amount.toString(),
+ userModel: userModel.value,
+ ).then((String? value) async {
+ bool isDone = await Get.to(
+ PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value),
+ );
if (isDone) {
Get.back();
ShowToastDialog.showToast("Payment successfully".tr());
@@ -1284,7 +1671,14 @@ class CabBookingController extends GetxController {
// });
}
- Future startTransaction(context, {required String txnTokenBy, required orderId, required double amount, required callBackURL, required isStaging}) async {
+ Future startTransaction(
+ context, {
+ required String txnTokenBy,
+ required orderId,
+ required double amount,
+ required callBackURL,
+ required isStaging,
+ }) async {
// try {
// var response = AllInOneSdk.startTransaction(
// paytmModel.value.paytmMID.toString(),
@@ -1320,24 +1714,38 @@ class CabBookingController extends GetxController {
// }
}
- Future verifyCheckSum({required String checkSum, required double amount, required orderId}) async {
+ Future verifyCheckSum({
+ required String checkSum,
+ required double amount,
+ required orderId,
+ }) async {
String getChecksum = "${Constant.globalUrl}payments/validatechecksum";
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(), "checksum_value": checkSum},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ "checksum_value": checkSum,
+ },
);
final data = jsonDecode(response.body);
return data['status'];
}
- Future initiatePayment({required double amount, required orderId}) async {
+ Future initiatePayment({
+ required double amount,
+ required orderId,
+ }) async {
String initiateURL = "${Constant.globalUrl}payments/initiatepaytmpayment";
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
final response = await http.post(
Uri.parse(initiateURL),
@@ -1355,9 +1763,12 @@ class CabBookingController extends GetxController {
);
log(response.body);
final data = jsonDecode(response.body);
- if (data["body"]["txnToken"] == null || data["body"]["txnToken"].toString().isEmpty) {
+ if (data["body"]["txnToken"] == null ||
+ data["body"]["txnToken"].toString().isEmpty) {
Get.back();
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
}
return GetPaymentTxtTokenModel.fromJson(data);
}
@@ -1375,7 +1786,10 @@ class CabBookingController extends GetxController {
'description': 'wallet Topup',
'retry': {'enabled': true, 'max_count': 1},
'send_sms_hash': true,
- 'prefill': {'contact': userModel.value.phoneNumber, 'email': userModel.value.email},
+ 'prefill': {
+ 'contact': userModel.value.phoneNumber,
+ 'email': userModel.value.email,
+ },
'external': {
'wallets': ['paytm'],
},
@@ -1410,7 +1824,10 @@ class CabBookingController extends GetxController {
}
//Midtrans payment
- Future midtransMakePayment({required String amount, required BuildContext context}) async {
+ Future midtransMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
await createPaymentLink(amount: amount).then((url) {
ShowToastDialog.closeLoader();
if (url != '') {
@@ -1428,15 +1845,30 @@ class CabBookingController extends GetxController {
Future createPaymentLink({required var amount}) async {
var ordersId = const Uuid().v1();
- final url = Uri.parse(midTransModel.value.isSandbox! ? 'https://api.sandbox.midtrans.com/v1/payment-links' : 'https://api.midtrans.com/v1/payment-links');
+ final url = Uri.parse(
+ midTransModel.value.isSandbox!
+ ? 'https://api.sandbox.midtrans.com/v1/payment-links'
+ : 'https://api.midtrans.com/v1/payment-links',
+ );
final response = await http.post(
url,
- headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': generateBasicAuthHeader(midTransModel.value.serverKey!)},
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ 'Authorization': generateBasicAuthHeader(
+ midTransModel.value.serverKey!,
+ ),
+ },
body: jsonEncode({
- 'transaction_details': {'order_id': ordersId, 'gross_amount': double.parse(amount.toString()).toInt()},
+ 'transaction_details': {
+ 'order_id': ordersId,
+ 'gross_amount': double.parse(amount.toString()).toInt(),
+ },
'usage_limit': 2,
- "callbacks": {"finish": "https://www.google.com?merchant_order_id=$ordersId"},
+ "callbacks": {
+ "finish": "https://www.google.com?merchant_order_id=$ordersId",
+ },
}),
);
@@ -1444,7 +1876,9 @@ class CabBookingController extends GetxController {
final responseData = jsonDecode(response.body);
return responseData['payment_url'];
} else {
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -1461,13 +1895,30 @@ class CabBookingController extends GetxController {
static String orderId = '';
static String amount = '';
- Future orangeMakePayment({required String amount, required BuildContext context}) async {
+ Future orangeMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
reset();
var id = const Uuid().v4();
- var paymentURL = await fetchToken(context: context, orderId: id, amount: amount, currency: 'USD');
+ var paymentURL = await fetchToken(
+ context: context,
+ orderId: id,
+ amount: amount,
+ currency: 'USD',
+ );
ShowToastDialog.closeLoader();
if (paymentURL.toString() != '') {
- Get.to(() => OrangeMoneyScreen(initialURl: paymentURL, accessToken: accessToken, amount: amount, orangePay: orangeMoneyModel.value, orderId: orderId, payToken: payToken))!.then((value) {
+ Get.to(
+ () => OrangeMoneyScreen(
+ initialURl: paymentURL,
+ accessToken: accessToken,
+ amount: amount,
+ orangePay: orangeMoneyModel.value,
+ orderId: orderId,
+ payToken: payToken,
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1479,13 +1930,22 @@ class CabBookingController extends GetxController {
}
}
- Future fetchToken({required String orderId, required String currency, required BuildContext context, required String amount}) async {
+ Future fetchToken({
+ required String orderId,
+ required String currency,
+ required BuildContext context,
+ required String amount,
+ }) async {
String apiUrl = 'https://api.orange.com/oauth/v3/token';
Map requestBody = {'grant_type': 'client_credentials'};
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': "Basic ${orangeMoneyModel.value.auth!}", 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': "Basic ${orangeMoneyModel.value.auth!}",
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Accept': 'application/json',
+ },
body: requestBody,
);
@@ -1496,17 +1956,32 @@ class CabBookingController extends GetxController {
accessToken = responseData['access_token'];
// ignore: use_build_context_synchronously
- return await webpayment(context: context, amountData: amount, currency: currency, orderIdData: orderId);
+ return await webpayment(
+ context: context,
+ amountData: amount,
+ currency: currency,
+ orderIdData: orderId,
+ );
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
- Future webpayment({required String orderIdData, required BuildContext context, required String currency, required String amountData}) async {
+ Future webpayment({
+ required String orderIdData,
+ required BuildContext context,
+ required String currency,
+ required String amountData,
+ }) async {
orderId = orderIdData;
amount = amountData;
- String apiUrl = orangeMoneyModel.value.isSandbox! == true ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment' : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
+ String apiUrl =
+ orangeMoneyModel.value.isSandbox! == true
+ ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment'
+ : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
Map requestBody = {
"merchant_key": orangeMoneyModel.value.merchantKey ?? '',
"currency": orangeMoneyModel.value.isSandbox == true ? "OUV" : currency,
@@ -1521,7 +1996,11 @@ class CabBookingController extends GetxController {
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': 'Bearer $accessToken',
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ },
body: json.encode(requestBody),
);
@@ -1535,7 +2014,9 @@ class CabBookingController extends GetxController {
return '';
}
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -1552,7 +2033,13 @@ class CabBookingController extends GetxController {
await createXenditInvoice(amount: amount).then((model) {
ShowToastDialog.closeLoader();
if (model.id != null) {
- Get.to(() => XenditScreen(initialURl: model.invoiceUrl ?? '', transId: model.id ?? '', apiKey: xenditModel.value.apiKey!.toString()))!.then((value) {
+ Get.to(
+ () => XenditScreen(
+ initialURl: model.invoiceUrl ?? '',
+ transId: model.id ?? '',
+ apiKey: xenditModel.value.apiKey!.toString(),
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
completeOrder();
@@ -1569,7 +2056,9 @@ class CabBookingController extends GetxController {
const url = 'https://api.xendit.co/v2/invoices';
var headers = {
'Content-Type': 'application/json',
- 'Authorization': generateBasicAuthHeader(xenditModel.value.apiKey!.toString()),
+ 'Authorization': generateBasicAuthHeader(
+ xenditModel.value.apiKey!.toString(),
+ ),
// 'Cookie': '__cf_bm=yERkrx3xDITyFGiou0bbKY1bi7xEwovHNwxV1vCNbVc-1724155511-1.0.1.1-jekyYQmPCwY6vIJ524K0V6_CEw6O.dAwOmQnHtwmaXO_MfTrdnmZMka0KZvjukQgXu5B.K_6FJm47SGOPeWviQ',
};
@@ -1582,7 +2071,11 @@ class CabBookingController extends GetxController {
});
try {
- final response = await http.post(Uri.parse(url), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse(url),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
XenditModel model = XenditModel.fromJson(jsonDecode(response.body));
diff --git a/lib/controllers/cab_coupon_code_controller.dart b/lib/controllers/cab_coupon_code_controller.dart
index 8d57707..2da0007 100644
--- a/lib/controllers/cab_coupon_code_controller.dart
+++ b/lib/controllers/cab_coupon_code_controller.dart
@@ -1,6 +1,6 @@
import 'package:customer/models/coupon_model.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class CabCouponCodeController extends GetxController {
// Add your methods and properties here
@@ -12,10 +12,10 @@ class CabCouponCodeController extends GetxController {
super.onInit();
}
-
- void getData(){
+ void getData() {
getCouponCode();
}
+
RxBool isLoading = true.obs;
RxList cabCouponList = [].obs;
diff --git a/lib/controllers/cab_dashboard_controller.dart b/lib/controllers/cab_dashboard_controller.dart
index 2bd4e9b..24e33cf 100644
--- a/lib/controllers/cab_dashboard_controller.dart
+++ b/lib/controllers/cab_dashboard_controller.dart
@@ -3,7 +3,7 @@ import 'package:customer/screen_ui/cab_service_screens/cab_home_screen.dart';
import 'package:customer/screen_ui/multi_vendor_service/profile_screen/profile_screen.dart';
import 'package:customer/screen_ui/multi_vendor_service/wallet_screen/wallet_screen.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import '../screen_ui/cab_service_screens/my_cab_booking_screen.dart';
class CabDashboardController extends GetxController {
@@ -15,15 +15,26 @@ class CabDashboardController extends GetxController {
void onInit() {
getTaxList();
if (Constant.walletSetting == false) {
- pageList.value = [CabHomeScreen(), const MyCabBookingScreen(), const ProfileScreen()];
+ pageList.value = [
+ CabHomeScreen(),
+ const MyCabBookingScreen(),
+ const ProfileScreen(),
+ ];
} else {
- pageList.value = [CabHomeScreen(), const MyCabBookingScreen(), const WalletScreen(), const ProfileScreen()];
+ pageList.value = [
+ CabHomeScreen(),
+ const MyCabBookingScreen(),
+ const WalletScreen(),
+ const ProfileScreen(),
+ ];
}
super.onInit();
}
Future getTaxList() async {
- await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((value) {
+ await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((
+ value,
+ ) {
if (value != null) {
Constant.taxList = value;
}
diff --git a/lib/controllers/cab_home_controller.dart b/lib/controllers/cab_home_controller.dart
index ba4361c..8ece16f 100644
--- a/lib/controllers/cab_home_controller.dart
+++ b/lib/controllers/cab_home_controller.dart
@@ -1,6 +1,6 @@
import 'package:customer/models/banner_model.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class CabHomeController extends GetxController {
RxBool isLoading = true.obs;
diff --git a/lib/controllers/cab_order_details_controller.dart b/lib/controllers/cab_order_details_controller.dart
index 0106e98..e2f5e3b 100644
--- a/lib/controllers/cab_order_details_controller.dart
+++ b/lib/controllers/cab_order_details_controller.dart
@@ -2,7 +2,7 @@ import 'dart:convert';
import 'package:customer/constant/constant.dart';
import 'package:customer/models/rating_model.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:http/http.dart' as http;
import 'package:google_maps_flutter/google_maps_flutter.dart' as gmap;
import 'package:latlong2/latlong.dart' as osm;
@@ -56,14 +56,18 @@ class CabOrderDetailsController extends GetxController {
Future fetchDriverDetails() async {
if (cabOrder.value.driverId != null) {
- await FireStoreUtils.getUserProfile(cabOrder.value.driverId ?? '').then((value) {
+ await FireStoreUtils.getUserProfile(cabOrder.value.driverId ?? '').then((
+ value,
+ ) {
if (value != null) {
driverUser.value = value;
}
});
print(driverUser.value.toJson());
- await FireStoreUtils.getReviewsbyID(cabOrder.value.id.toString()).then((value) {
+ await FireStoreUtils.getReviewsbyID(cabOrder.value.id.toString()).then((
+ value,
+ ) {
if (value != null) {
ratingModel.value = value;
}
@@ -79,7 +83,12 @@ class CabOrderDetailsController extends GetxController {
if (cabOrder.value.taxSetting != null) {
for (var element in cabOrder.value.taxSetting!) {
- taxAmount.value = (taxAmount.value + Constant.calculateTax(amount: (subTotal.value - discount.value).toString(), taxModel: element));
+ taxAmount.value =
+ (taxAmount.value +
+ Constant.calculateTax(
+ amount: (subTotal.value - discount.value).toString(),
+ taxModel: element,
+ ));
}
}
@@ -94,8 +103,20 @@ class CabOrderDetailsController extends GetxController {
final destLng = cabOrder.value.destinationLocation!.longitude;
googleMarkers.value = {
- gmap.Marker(markerId: const gmap.MarkerId('source'), position: gmap.LatLng(sourceLat!, sourceLng!), icon: gmap.BitmapDescriptor.defaultMarkerWithHue(gmap.BitmapDescriptor.hueGreen)),
- gmap.Marker(markerId: const gmap.MarkerId('destination'), position: gmap.LatLng(destLat!, destLng!), icon: gmap.BitmapDescriptor.defaultMarkerWithHue(gmap.BitmapDescriptor.hueRed)),
+ gmap.Marker(
+ markerId: const gmap.MarkerId('source'),
+ position: gmap.LatLng(sourceLat!, sourceLng!),
+ icon: gmap.BitmapDescriptor.defaultMarkerWithHue(
+ gmap.BitmapDescriptor.hueGreen,
+ ),
+ ),
+ gmap.Marker(
+ markerId: const gmap.MarkerId('destination'),
+ position: gmap.LatLng(destLat!, destLng!),
+ icon: gmap.BitmapDescriptor.defaultMarkerWithHue(
+ gmap.BitmapDescriptor.hueRed,
+ ),
+ ),
};
}
@@ -104,7 +125,8 @@ class CabOrderDetailsController extends GetxController {
final src = cabOrder.value.sourceLocation;
final dest = cabOrder.value.destinationLocation;
- final url = "https://maps.googleapis.com/maps/api/directions/json?origin=${src!.latitude},${src.longitude}&destination=${dest!.latitude},${dest.longitude}&key=$googleApiKey";
+ final url =
+ "https://maps.googleapis.com/maps/api/directions/json?origin=${src!.latitude},${src.longitude}&destination=${dest!.latitude},${dest.longitude}&key=$googleApiKey";
final response = await http.get(Uri.parse(url));
final data = jsonDecode(response.body);
@@ -113,9 +135,19 @@ class CabOrderDetailsController extends GetxController {
final points = data["routes"][0]["overview_polyline"]["points"];
final polylinePoints = PolylinePoints.decodePolyline(points);
- final polylineCoords = polylinePoints.map((p) => gmap.LatLng(p.latitude, p.longitude)).toList();
+ final polylineCoords =
+ polylinePoints
+ .map((p) => gmap.LatLng(p.latitude, p.longitude))
+ .toList();
- googlePolylines.value = {gmap.Polyline(polylineId: const gmap.PolylineId("google_route"), color: AppThemeData.onDemandDark100, width: 5, points: polylineCoords)};
+ googlePolylines.value = {
+ gmap.Polyline(
+ polylineId: const gmap.PolylineId("google_route"),
+ color: AppThemeData.onDemandDark100,
+ width: 5,
+ points: polylineCoords,
+ ),
+ };
}
}
@@ -124,15 +156,20 @@ class CabOrderDetailsController extends GetxController {
final src = cabOrder.value.sourceLocation;
final dest = cabOrder.value.destinationLocation;
- final url = "http://router.project-osrm.org/route/v1/driving/${src!.longitude},${src.latitude};${dest!.longitude},${dest.latitude}?overview=full&geometries=geojson";
+ final url =
+ "http://router.project-osrm.org/route/v1/driving/${src!.longitude},${src.latitude};${dest!.longitude},${dest.latitude}?overview=full&geometries=geojson";
final response = await http.get(Uri.parse(url));
final data = jsonDecode(response.body);
if (data["routes"].isNotEmpty) {
- final coords = data["routes"][0]["geometry"]["coordinates"] as List;
+ final coords =
+ data["routes"][0]["geometry"]["coordinates"] as List;
- osmPolyline.value = coords.map((c) => osm.LatLng(c[1].toDouble(), c[0].toDouble())).toList();
+ osmPolyline.value =
+ coords
+ .map((c) => osm.LatLng(c[1].toDouble(), c[0].toDouble()))
+ .toList();
}
}
}
diff --git a/lib/controllers/cab_rental_dashboard_controllers.dart b/lib/controllers/cab_rental_dashboard_controllers.dart
index add5017..1e0eda6 100644
--- a/lib/controllers/cab_rental_dashboard_controllers.dart
+++ b/lib/controllers/cab_rental_dashboard_controllers.dart
@@ -3,8 +3,7 @@ import 'package:customer/screen_ui/multi_vendor_service/profile_screen/profile_s
import 'package:customer/screen_ui/multi_vendor_service/wallet_screen/wallet_screen.dart';
import 'package:customer/screen_ui/rental_service/rental_home_screen.dart';
import 'package:customer/service/fire_store_utils.dart';
-import 'package:get/get.dart';
-
+import 'package:get/get.dart' hide Trans;
import '../screen_ui/rental_service/my_rental_booking_screen.dart';
class CabRentalDashboardControllers extends GetxController {
@@ -17,15 +16,26 @@ class CabRentalDashboardControllers extends GetxController {
// TODO: implement onInit
getTaxList();
if (Constant.walletSetting == false) {
- pageList.value = [RentalHomeScreen(), MyRentalBookingScreen(), const ProfileScreen()];
+ pageList.value = [
+ RentalHomeScreen(),
+ MyRentalBookingScreen(),
+ const ProfileScreen(),
+ ];
} else {
- pageList.value = [RentalHomeScreen(), MyRentalBookingScreen(), const WalletScreen(), const ProfileScreen()];
+ pageList.value = [
+ RentalHomeScreen(),
+ MyRentalBookingScreen(),
+ const WalletScreen(),
+ const ProfileScreen(),
+ ];
}
super.onInit();
}
Future getTaxList() async {
- await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((value) {
+ await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((
+ value,
+ ) {
if (value != null) {
Constant.taxList = value;
}
diff --git a/lib/controllers/cab_review_controller.dart b/lib/controllers/cab_review_controller.dart
index bbd1b20..e5218bb 100644
--- a/lib/controllers/cab_review_controller.dart
+++ b/lib/controllers/cab_review_controller.dart
@@ -2,7 +2,7 @@ import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:customer/models/cab_order_model.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import '../constant/collection_name.dart';
import '../models/rating_model.dart';
import '../models/user_model.dart';
@@ -44,12 +44,17 @@ class CabReviewController extends GetxController {
}
});
- await FireStoreUtils.getUserProfile(order.value?.driverId ?? '').then((value) {
+ await FireStoreUtils.getUserProfile(order.value?.driverId ?? '').then((
+ value,
+ ) {
if (value != null) {
driverUser.value = value;
- final int userReviewsCount = int.tryParse(driverUser.value!.reviewsCount?.toString() ?? "0") ?? 0;
- final int userReviewsSum = int.tryParse(driverUser.value!.reviewsSum?.toString() ?? "0") ?? 0;
+ final int userReviewsCount =
+ int.tryParse(driverUser.value!.reviewsCount?.toString() ?? "0") ??
+ 0;
+ final int userReviewsSum =
+ int.tryParse(driverUser.value!.reviewsSum?.toString() ?? "0") ?? 0;
if (ratingModel.value != null) {
final int oldRating = ratingModel.value?.rating?.toInt() ?? 0;
@@ -74,7 +79,9 @@ class CabReviewController extends GetxController {
ShowToastDialog.showLoader("Submit in...".tr());
- final user = await FireStoreUtils.getUserProfile(order.value?.driverId ?? '');
+ final user = await FireStoreUtils.getUserProfile(
+ order.value?.driverId ?? '',
+ );
if (user != null) {
user.reviewsCount = (futureCount.value + 1).toString();
@@ -91,7 +98,8 @@ class CabReviewController extends GetxController {
driverId: ratingModel.value!.driverId,
customerId: ratingModel.value!.customerId,
vendorId: ratingModel.value?.vendorId,
- uname: "${Constant.userModel?.firstName ?? ''} ${Constant.userModel?.lastName ?? ''}",
+ uname:
+ "${Constant.userModel?.firstName ?? ''} ${Constant.userModel?.lastName ?? ''}",
profile: Constant.userModel?.profilePictureURL,
createdAt: Timestamp.now(),
);
@@ -102,7 +110,8 @@ class CabReviewController extends GetxController {
}
} else {
/// New review
- final docRef = FireStoreUtils.fireStore.collection(CollectionName.itemsReview).doc();
+ final docRef =
+ FireStoreUtils.fireStore.collection(CollectionName.itemsReview).doc();
final newRating = RatingModel(
id: docRef.id,
comment: comment.value.text,
@@ -111,7 +120,8 @@ class CabReviewController extends GetxController {
orderId: order.value?.id,
driverId: order.value?.driverId.toString(),
customerId: Constant.userModel?.id,
- uname: "${Constant.userModel?.firstName ?? ''} ${Constant.userModel?.lastName ?? ''}",
+ uname:
+ "${Constant.userModel?.firstName ?? ''} ${Constant.userModel?.lastName ?? ''}",
profile: Constant.userModel?.profilePictureURL,
createdAt: Timestamp.now(),
);
diff --git a/lib/controllers/cart_controller.dart b/lib/controllers/cart_controller.dart
index 8998fa7..5dc45ff 100644
--- a/lib/controllers/cart_controller.dart
+++ b/lib/controllers/cart_controller.dart
@@ -17,7 +17,7 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_paypal/flutter_paypal.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
@@ -108,7 +108,9 @@ class CartController extends GetxController {
cartItem.addAll(event);
if (cartItem.isNotEmpty) {
- await FireStoreUtils.getVendorById(cartItem.first.vendorID.toString()).then((value) {
+ await FireStoreUtils.getVendorById(
+ cartItem.first.vendorID.toString(),
+ ).then((value) {
if (value != null) {
vendorModel.value = value;
}
@@ -116,9 +118,14 @@ class CartController extends GetxController {
}
calculatePrice();
});
- selectedFoodType.value = Preferences.getString(Preferences.foodDeliveryType, defaultValue: "Delivery");
+ selectedFoodType.value = Preferences.getString(
+ Preferences.foodDeliveryType,
+ defaultValue: "Delivery",
+ );
- await FireStoreUtils.getUserProfile(FireStoreUtils.getCurrentUid()).then((value) {
+ await FireStoreUtils.getUserProfile(FireStoreUtils.getCurrentUid()).then((
+ value,
+ ) {
if (value != null) {
userModel.value = value;
}
@@ -127,16 +134,22 @@ class CartController extends GetxController {
await FireStoreUtils.getDeliveryCharge().then((value) {
if (value != null) {
deliveryChargeModel.value = value;
- print("===> Delivery Charge Model: ${deliveryChargeModel.value.toJson()}");
+ print(
+ "===> Delivery Charge Model: ${deliveryChargeModel.value.toJson()}",
+ );
calculatePrice();
}
});
- await FireStoreUtils.getAllVendorPublicCoupons(vendorModel.value.id.toString()).then((value) {
+ await FireStoreUtils.getAllVendorPublicCoupons(
+ vendorModel.value.id.toString(),
+ ).then((value) {
couponList.value = value;
});
- await FireStoreUtils.getAllVendorCoupons(vendorModel.value.id.toString()).then((value) {
+ await FireStoreUtils.getAllVendorCoupons(
+ vendorModel.value.id.toString(),
+ ).then((value) {
allCouponList.value = value;
});
}
@@ -150,8 +163,11 @@ class CartController extends GetxController {
totalAmount.value = 0.0;
if (cartItem.isNotEmpty) {
- if (Constant.sectionConstantModel!.serviceTypeFlag == "ecommerce-service") {
- deliveryCharges.value = double.parse(Constant.sectionConstantModel!.delivery_charge ?? "0");
+ if (Constant.sectionConstantModel!.serviceTypeFlag ==
+ "ecommerce-service") {
+ deliveryCharges.value = double.parse(
+ Constant.sectionConstantModel!.delivery_charge ?? "0",
+ );
} else {
if (selectedFoodType.value == "Delivery") {
totalDistance.value = double.parse(
@@ -162,26 +178,50 @@ class CartController extends GetxController {
lng2: vendorModel.value.longitude.toString(),
),
);
- if (vendorModel.value.isSelfDelivery == true && Constant.isSelfDeliveryFeature == true) {
+ if (vendorModel.value.isSelfDelivery == true &&
+ Constant.isSelfDeliveryFeature == true) {
deliveryCharges.value = 0.0;
} else if (deliveryChargeModel.value.vendorCanModify == false) {
- if (totalDistance.value > deliveryChargeModel.value.minimumDeliveryChargesWithinKm!) {
- deliveryCharges.value = totalDistance.value * deliveryChargeModel.value.deliveryChargesPerKm!;
+ if (totalDistance.value >
+ deliveryChargeModel.value.minimumDeliveryChargesWithinKm!) {
+ deliveryCharges.value =
+ totalDistance.value *
+ deliveryChargeModel.value.deliveryChargesPerKm!;
} else {
- deliveryCharges.value = (deliveryChargeModel.value.minimumDeliveryCharges)!.toDouble();
+ deliveryCharges.value =
+ (deliveryChargeModel.value.minimumDeliveryCharges)!
+ .toDouble();
}
} else {
if (vendorModel.value.deliveryCharge != null) {
- if (totalDistance.value > vendorModel.value.deliveryCharge!.minimumDeliveryChargesWithinKm!) {
- deliveryCharges.value = (totalDistance.value * vendorModel.value.deliveryCharge!.deliveryChargesPerKm!).toDouble();
+ if (totalDistance.value >
+ vendorModel
+ .value
+ .deliveryCharge!
+ .minimumDeliveryChargesWithinKm!) {
+ deliveryCharges.value =
+ (totalDistance.value *
+ vendorModel
+ .value
+ .deliveryCharge!
+ .deliveryChargesPerKm!)
+ .toDouble();
} else {
- deliveryCharges.value = vendorModel.value.deliveryCharge!.minimumDeliveryCharges!.toDouble();
+ deliveryCharges.value =
+ vendorModel.value.deliveryCharge!.minimumDeliveryCharges!
+ .toDouble();
}
} else {
- if (totalDistance.value > deliveryChargeModel.value.minimumDeliveryChargesWithinKm!) {
- deliveryCharges.value = (totalDistance.value * deliveryChargeModel.value.deliveryChargesPerKm!).toDouble();
+ if (totalDistance.value >
+ deliveryChargeModel.value.minimumDeliveryChargesWithinKm!) {
+ deliveryCharges.value =
+ (totalDistance.value *
+ deliveryChargeModel.value.deliveryChargesPerKm!)
+ .toDouble();
} else {
- deliveryCharges.value = deliveryChargeModel.value.minimumDeliveryCharges!.toDouble();
+ deliveryCharges.value =
+ deliveryChargeModel.value.minimumDeliveryCharges!
+ .toDouble();
}
}
}
@@ -195,21 +235,29 @@ class CartController extends GetxController {
if (double.parse(element.discountPrice.toString()) <= 0) {
subTotal.value =
subTotal.value +
- double.parse(element.price.toString()) * double.parse(element.quantity.toString()) +
- (double.parse(element.extrasPrice.toString()) * double.parse(element.quantity.toString()));
+ double.parse(element.price.toString()) *
+ double.parse(element.quantity.toString()) +
+ (double.parse(element.extrasPrice.toString()) *
+ double.parse(element.quantity.toString()));
} else {
subTotal.value =
subTotal.value +
- double.parse(element.discountPrice.toString()) * double.parse(element.quantity.toString()) +
- (double.parse(element.extrasPrice.toString()) * double.parse(element.quantity.toString()));
+ double.parse(element.discountPrice.toString()) *
+ double.parse(element.quantity.toString()) +
+ (double.parse(element.extrasPrice.toString()) *
+ double.parse(element.quantity.toString()));
}
}
if (selectedCouponModel.value.id != null) {
- couponAmount.value = Constant.calculateDiscount(amount: subTotal.value.toString(), offerModel: selectedCouponModel.value);
+ couponAmount.value = Constant.calculateDiscount(
+ amount: subTotal.value.toString(),
+ offerModel: selectedCouponModel.value,
+ );
}
- if (vendorModel.value.specialDiscountEnable == true && Constant.specialDiscountOffer == true) {
+ if (vendorModel.value.specialDiscountEnable == true &&
+ Constant.specialDiscountOffer == true) {
final now = DateTime.now();
var day = DateFormat('EEEE', 'en_US').format(now);
var date = DateFormat('dd-MM-yyyy').format(now);
@@ -218,13 +266,20 @@ class CartController extends GetxController {
if (element.timeslot!.isNotEmpty) {
for (var element in element.timeslot!) {
if (element.discountType == "delivery") {
- var start = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.from}");
- var end = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.to}");
+ var start = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.from}");
+ var end = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.to}");
if (isCurrentDateInRange(start, end)) {
- specialDiscount.value = double.parse(element.discount.toString());
+ specialDiscount.value = double.parse(
+ element.discount.toString(),
+ );
specialType.value = element.type.toString();
if (element.type == "percentage") {
- specialDiscountAmount.value = subTotal * specialDiscount.value / 100;
+ specialDiscountAmount.value =
+ subTotal * specialDiscount.value / 100;
} else {
specialDiscountAmount.value = specialDiscount.value;
}
@@ -240,10 +295,23 @@ class CartController extends GetxController {
}
for (var element in Constant.taxList) {
- taxAmount.value = taxAmount.value + Constant.calculateTax(amount: (subTotal.value - couponAmount.value - specialDiscountAmount.value).toString(), taxModel: element);
+ taxAmount.value =
+ taxAmount.value +
+ Constant.calculateTax(
+ amount:
+ (subTotal.value -
+ couponAmount.value -
+ specialDiscountAmount.value)
+ .toString(),
+ taxModel: element,
+ );
}
- totalAmount.value = (subTotal.value - couponAmount.value - specialDiscountAmount.value) + taxAmount.value + deliveryCharges.value + deliveryTips.value;
+ totalAmount.value =
+ (subTotal.value - couponAmount.value - specialDiscountAmount.value) +
+ taxAmount.value +
+ deliveryCharges.value +
+ deliveryTips.value;
getCashback();
}
@@ -264,17 +332,31 @@ class CartController extends GetxController {
if (startDate == null || endDate == null) continue;
- final withinDateRange = startDate.toDate().isBefore(now) && endDate.toDate().isAfter(now);
- final meetsMinAmount = orderTotal >= (cashback.minimumPurchaseAmount ?? 0);
+ final withinDateRange =
+ startDate.toDate().isBefore(now) && endDate.toDate().isAfter(now);
+ final meetsMinAmount =
+ orderTotal >= (cashback.minimumPurchaseAmount ?? 0);
final allPayment = cashback.allPayment ?? false;
- final paymentMatch = allPayment || (cashback.paymentMethods ?? []).contains(paymentMethod);
+ final paymentMatch =
+ allPayment ||
+ (cashback.paymentMethods ?? []).contains(paymentMethod);
final allCustomer = cashback.allCustomer ?? false;
- final customerMatch = allCustomer || (cashback.customerIds ?? []).contains(FireStoreUtils.getCurrentUid());
+ final customerMatch =
+ allCustomer ||
+ (cashback.customerIds ?? []).contains(
+ FireStoreUtils.getCurrentUid(),
+ );
- final redeemData = await FireStoreUtils.getRedeemedCashbacks(cashback.id ?? '');
+ final redeemData = await FireStoreUtils.getRedeemedCashbacks(
+ cashback.id ?? '',
+ );
final underLimit = redeemData.length < (cashback.redeemLimit ?? 0);
- if (withinDateRange && meetsMinAmount && paymentMatch && customerMatch && underLimit) {
+ if (withinDateRange &&
+ meetsMinAmount &&
+ paymentMatch &&
+ customerMatch &&
+ underLimit) {
eligibleCashbacks.add(cashback);
}
}
@@ -312,7 +394,11 @@ class CartController extends GetxController {
}
}
- Future addToCart({required CartProductModel cartProductModel, required bool isIncrement, required int quantity}) async {
+ Future addToCart({
+ required CartProductModel cartProductModel,
+ required bool isIncrement,
+ required int quantity,
+ }) async {
if (isIncrement) {
cartProvider.addToCart(Get.context!, cartProductModel, quantity);
} else {
@@ -325,10 +411,13 @@ class CartController extends GetxController {
Future placeOrder() async {
if (selectedPaymentMethod.value == PaymentGateway.wallet.name) {
- if (double.parse(userModel.value.walletAmount.toString()) >= totalAmount.value) {
+ if (double.parse(userModel.value.walletAmount.toString()) >=
+ totalAmount.value) {
setOrder();
} else {
- ShowToastDialog.showToast("You don't have sufficient wallet balance to place order".tr());
+ ShowToastDialog.showToast(
+ "You don't have sufficient wallet balance to place order".tr(),
+ );
}
} else {
setOrder();
@@ -338,11 +427,19 @@ class CartController extends GetxController {
Future setOrder() async {
ShowToastDialog.showLoader("Please wait...".tr());
- if ((Constant.isSubscriptionModelApplied == true || Constant.sectionConstantModel?.adminCommision?.isEnabled == true) && vendorModel.value.subscriptionPlan != null) {
- await FireStoreUtils.getVendorById(vendorModel.value.id!).then((vender) async {
- if (vender?.subscriptionTotalOrders == '0' || vender?.subscriptionTotalOrders == null) {
+ if ((Constant.isSubscriptionModelApplied == true ||
+ Constant.sectionConstantModel?.adminCommision?.isEnabled == true) &&
+ vendorModel.value.subscriptionPlan != null) {
+ await FireStoreUtils.getVendorById(vendorModel.value.id!).then((
+ vender,
+ ) async {
+ if (vender?.subscriptionTotalOrders == '0' ||
+ vender?.subscriptionTotalOrders == null) {
ShowToastDialog.closeLoader();
- ShowToastDialog.showToast("This vendor has reached their maximum order capacity. Please select a different vendor or try again later.".tr());
+ ShowToastDialog.showToast(
+ "This vendor has reached their maximum order capacity. Please select a different vendor or try again later."
+ .tr(),
+ );
return;
}
});
@@ -356,7 +453,11 @@ class CartController extends GetxController {
tempProduc.add(tempCart);
}
- Map specialDiscountMap = {'special_discount': specialDiscountAmount.value, 'special_discount_label': specialDiscount.value, 'specialType': specialType.value};
+ Map specialDiscountMap = {
+ 'special_discount': specialDiscountAmount.value,
+ 'special_discount_label': specialDiscount.value,
+ 'specialType': specialType.value,
+ };
OrderModel orderModel = OrderModel();
orderModel.id = Constant.getUuid();
@@ -391,8 +492,12 @@ class CartController extends GetxController {
orderModel.notes = reMarkController.value.text;
orderModel.takeAway = selectedFoodType.value == "Delivery" ? false : true;
orderModel.createdAt = Timestamp.now();
- orderModel.scheduleTime = deliveryType.value == "schedule" ? Timestamp.fromDate(scheduleDateTime.value) : null;
- orderModel.cashback = bestCashback.value.id == null ? null : bestCashback.value;
+ orderModel.scheduleTime =
+ deliveryType.value == "schedule"
+ ? Timestamp.fromDate(scheduleDateTime.value)
+ : null;
+ orderModel.cashback =
+ bestCashback.value.id == null ? null : bestCashback.value;
if (selectedPaymentMethod.value == PaymentGateway.wallet.name) {
WalletTransactionModel transactionModel = WalletTransactionModel(
id: Constant.getUuid(),
@@ -407,33 +512,57 @@ class CartController extends GetxController {
paymentStatus: "success".tr(),
);
- await FireStoreUtils.setWalletTransaction(transactionModel).then((value) async {
+ await FireStoreUtils.setWalletTransaction(transactionModel).then((
+ value,
+ ) async {
if (value == true) {
- await FireStoreUtils.updateUserWallet(amount: "-${totalAmount.value.toString()}", userId: FireStoreUtils.getCurrentUid()).then((value) {});
+ await FireStoreUtils.updateUserWallet(
+ amount: "-${totalAmount.value.toString()}",
+ userId: FireStoreUtils.getCurrentUid(),
+ ).then((value) {});
}
});
}
for (int i = 0; i < tempProduc.length; i++) {
- await FireStoreUtils.getProductById(tempProduc[i].id!.split('~').first).then((value) async {
+ await FireStoreUtils.getProductById(
+ tempProduc[i].id!.split('~').first,
+ ).then((value) async {
ProductModel? productModel = value;
if (tempProduc[i].variantInfo != null) {
if (productModel!.itemAttribute != null) {
- for (int j = 0; j < productModel.itemAttribute!.variants!.length; j++) {
- if (productModel.itemAttribute!.variants![j].variantId == tempProduc[i].id!.split('~').last) {
- if (productModel.itemAttribute!.variants![j].variantQuantity != "-1") {
- productModel.itemAttribute!.variants![j].variantQuantity = (int.parse(productModel.itemAttribute!.variants![j].variantQuantity.toString()) - tempProduc[i].quantity!).toString();
+ for (
+ int j = 0;
+ j < productModel.itemAttribute!.variants!.length;
+ j++
+ ) {
+ if (productModel.itemAttribute!.variants![j].variantId ==
+ tempProduc[i].id!.split('~').last) {
+ if (productModel.itemAttribute!.variants![j].variantQuantity !=
+ "-1") {
+ productModel.itemAttribute!.variants![j].variantQuantity =
+ (int.parse(
+ productModel
+ .itemAttribute!
+ .variants![j]
+ .variantQuantity
+ .toString(),
+ ) -
+ tempProduc[i].quantity!)
+ .toString();
}
}
}
} else {
if (productModel.quantity != -1) {
- productModel.quantity = (productModel.quantity! - tempProduc[i].quantity!);
+ productModel.quantity =
+ (productModel.quantity! - tempProduc[i].quantity!);
}
}
} else {
if (productModel!.quantity != -1) {
- productModel.quantity = (productModel.quantity! - tempProduc[i].quantity!);
+ productModel.quantity =
+ (productModel.quantity! - tempProduc[i].quantity!);
}
}
@@ -451,18 +580,31 @@ class CartController extends GetxController {
await FireStoreUtils.setCashbackRedeemModel(cashbackRedeemModel);
}
await FireStoreUtils.setOrder(orderModel).then((value) async {
- await FireStoreUtils.getUserProfile(orderModel.vendor!.author.toString()).then((value) async {
+ await FireStoreUtils.getUserProfile(
+ orderModel.vendor!.author.toString(),
+ ).then((value) async {
if (value != null) {
if (orderModel.scheduleTime != null) {
- await SendNotification.sendFcmMessage(Constant.scheduleOrder, value.fcmToken ?? '', {});
+ await SendNotification.sendFcmMessage(
+ Constant.scheduleOrder,
+ value.fcmToken ?? '',
+ {},
+ );
} else {
- await SendNotification.sendFcmMessage(Constant.newOrderPlaced, value.fcmToken ?? '', {});
+ await SendNotification.sendFcmMessage(
+ Constant.newOrderPlaced,
+ value.fcmToken ?? '',
+ {},
+ );
}
}
});
await Constant.sendOrderEmail(orderModel: orderModel);
ShowToastDialog.closeLoader();
- Get.off(const OrderPlacingScreen(), arguments: {"orderModel": orderModel});
+ Get.off(
+ const OrderPlacingScreen(),
+ arguments: {"orderModel": orderModel},
+ );
});
}
@@ -483,19 +625,45 @@ class CartController extends GetxController {
Future getPaymentSettings() async {
await FireStoreUtils.getPaymentSettingsData().then((value) {
- stripeModel.value = StripeModel.fromJson(jsonDecode(Preferences.getString(Preferences.stripeSettings)));
- payPalModel.value = PayPalModel.fromJson(jsonDecode(Preferences.getString(Preferences.paypalSettings)));
- payStackModel.value = PayStackModel.fromJson(jsonDecode(Preferences.getString(Preferences.payStack)));
- mercadoPagoModel.value = MercadoPagoModel.fromJson(jsonDecode(Preferences.getString(Preferences.mercadoPago)));
- flutterWaveModel.value = FlutterWaveModel.fromJson(jsonDecode(Preferences.getString(Preferences.flutterWave)));
- paytmModel.value = PaytmModel.fromJson(jsonDecode(Preferences.getString(Preferences.paytmSettings)));
- payFastModel.value = PayFastModel.fromJson(jsonDecode(Preferences.getString(Preferences.payFastSettings)));
- razorPayModel.value = RazorPayModel.fromJson(jsonDecode(Preferences.getString(Preferences.razorpaySettings)));
- midTransModel.value = MidTrans.fromJson(jsonDecode(Preferences.getString(Preferences.midTransSettings)));
- orangeMoneyModel.value = OrangeMoney.fromJson(jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)));
- xenditModel.value = Xendit.fromJson(jsonDecode(Preferences.getString(Preferences.xenditSettings)));
- walletSettingModel.value = WalletSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.walletSettings)));
- cashOnDeliverySettingModel.value = CodSettingModel.fromJson(jsonDecode(Preferences.getString(Preferences.codSettings)));
+ stripeModel.value = StripeModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.stripeSettings)),
+ );
+ payPalModel.value = PayPalModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paypalSettings)),
+ );
+ payStackModel.value = PayStackModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payStack)),
+ );
+ mercadoPagoModel.value = MercadoPagoModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.mercadoPago)),
+ );
+ flutterWaveModel.value = FlutterWaveModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.flutterWave)),
+ );
+ paytmModel.value = PaytmModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.paytmSettings)),
+ );
+ payFastModel.value = PayFastModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.payFastSettings)),
+ );
+ razorPayModel.value = RazorPayModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.razorpaySettings)),
+ );
+ midTransModel.value = MidTrans.fromJson(
+ jsonDecode(Preferences.getString(Preferences.midTransSettings)),
+ );
+ orangeMoneyModel.value = OrangeMoney.fromJson(
+ jsonDecode(Preferences.getString(Preferences.orangeMoneySettings)),
+ );
+ xenditModel.value = Xendit.fromJson(
+ jsonDecode(Preferences.getString(Preferences.xenditSettings)),
+ );
+ walletSettingModel.value = WalletSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.walletSettings)),
+ );
+ cashOnDeliverySettingModel.value = CodSettingModel.fromJson(
+ jsonDecode(Preferences.getString(Preferences.codSettings)),
+ );
if (walletSettingModel.value.isEnabled == true) {
selectedPaymentMethod.value = PaymentGateway.wallet.name;
@@ -537,20 +705,32 @@ class CartController extends GetxController {
Future stripeMakePayment({required String amount}) async {
log(double.parse(amount).toStringAsFixed(0));
try {
- Map? paymentIntentData = await createStripeIntent(amount: amount);
+ Map? paymentIntentData = await createStripeIntent(
+ amount: amount,
+ );
log("stripe Responce====>$paymentIntentData");
if (paymentIntentData!.containsKey("error")) {
Get.back();
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
} else {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentData['client_secret'],
allowsDelayedPaymentMethods: false,
- googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'US', testEnv: true, currencyCode: "USD"),
+ googlePay: const PaymentSheetGooglePay(
+ merchantCountryCode: 'US',
+ testEnv: true,
+ currencyCode: "USD",
+ ),
customFlow: true,
style: ThemeMode.system,
- appearance: PaymentSheetAppearance(colors: PaymentSheetAppearanceColors(primary: AppThemeData.primary300)),
+ appearance: PaymentSheetAppearance(
+ colors: PaymentSheetAppearanceColors(
+ primary: AppThemeData.primary300,
+ ),
+ ),
merchantDisplayName: 'GoRide',
),
);
@@ -596,7 +776,10 @@ class CartController extends GetxController {
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
body: body,
- headers: {'Authorization': 'Bearer $stripeSecret', 'Content-Type': 'application/x-www-form-urlencoded'},
+ headers: {
+ 'Authorization': 'Bearer $stripeSecret',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
);
return jsonDecode(response.body);
@@ -606,8 +789,14 @@ class CartController extends GetxController {
}
//mercadoo
- Future mercadoPagoMakePayment({required BuildContext context, required String amount}) async {
- final headers = {'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}', 'Content-Type': 'application/json'};
+ Future mercadoPagoMakePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
+ final headers = {
+ 'Authorization': 'Bearer ${mercadoPagoModel.value.accessToken}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"items": [
@@ -620,12 +809,20 @@ class CartController extends GetxController {
},
],
"payer": {"email": userModel.value.email},
- "back_urls": {"failure": "${Constant.globalUrl}payment/failure", "pending": "${Constant.globalUrl}payment/pending", "success": "${Constant.globalUrl}payment/success"},
+ "back_urls": {
+ "failure": "${Constant.globalUrl}payment/failure",
+ "pending": "${Constant.globalUrl}payment/pending",
+ "success": "${Constant.globalUrl}payment/success",
+ },
"auto_return": "approved",
// Automatically return after payment is approved
});
- final response = await http.post(Uri.parse("https://api.mercadopago.com/checkout/preferences"), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse("https://api.mercadopago.com/checkout/preferences"),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
final data = jsonDecode(response.body);
@@ -683,9 +880,12 @@ class CartController extends GetxController {
///PayStack Payment Method
Future payStackPayment(String totalAmount) async {
- await PayStackURLGen.payStackURLGen(amount: (double.parse(totalAmount) * 100).toString(), currency: "ZAR", secretKey: payStackModel.value.secretKey.toString(), userModel: userModel.value).then((
- value,
- ) async {
+ await PayStackURLGen.payStackURLGen(
+ amount: (double.parse(totalAmount) * 100).toString(),
+ currency: "ZAR",
+ secretKey: payStackModel.value.secretKey.toString(),
+ userModel: userModel.value,
+ ).then((value) async {
if (value != null) {
PayStackUrlModel payStackModel0 = value;
Get.to(
@@ -705,15 +905,23 @@ class CartController extends GetxController {
}
});
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
}
});
}
//flutter wave Payment Method
- Future flutterWaveInitiatePayment({required BuildContext context, required String amount}) async {
+ Future flutterWaveInitiatePayment({
+ required BuildContext context,
+ required String amount,
+ }) async {
final url = Uri.parse('https://api.flutterwave.com/v3/payments');
- final headers = {'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}', 'Content-Type': 'application/json'};
+ final headers = {
+ 'Authorization': 'Bearer ${flutterWaveModel.value.secretKey}',
+ 'Content-Type': 'application/json',
+ };
final body = jsonEncode({
"tx_ref": _ref,
@@ -726,14 +934,19 @@ class CartController extends GetxController {
"phonenumber": userModel.value.phoneNumber, // Add a real phone number
"name": userModel.value.fullName(), // Add a real customer name
},
- "customizations": {"title": "Payment for Services", "description": "Payment for XYZ services"},
+ "customizations": {
+ "title": "Payment for Services",
+ "description": "Payment for XYZ services",
+ },
});
final response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
- Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((value) {
+ Get.to(MercadoPagoScreen(initialURl: data['data']['link']))!.then((
+ value,
+ ) {
if (value) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -762,8 +975,14 @@ class CartController extends GetxController {
// payFast
void payFastPayment({required BuildContext context, required String amount}) {
- PayStackURLGen.getPayHTML(payFastSettingData: payFastModel.value, amount: amount.toString(), userModel: userModel.value).then((String? value) async {
- bool isDone = await Get.to(PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value));
+ PayStackURLGen.getPayHTML(
+ payFastSettingData: payFastModel.value,
+ amount: amount.toString(),
+ userModel: userModel.value,
+ ).then((String? value) async {
+ bool isDone = await Get.to(
+ PayFastScreen(htmlData: value!, payFastSettingData: payFastModel.value),
+ );
if (isDone) {
Get.back();
ShowToastDialog.showToast("Payment successfully".tr());
@@ -783,26 +1002,50 @@ class CartController extends GetxController {
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString()},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ },
);
final data = jsonDecode(response.body);
- await verifyCheckSum(checkSum: data["code"], amount: amount, orderId: orderId).then((value) {
+ await verifyCheckSum(
+ checkSum: data["code"],
+ amount: amount,
+ orderId: orderId,
+ ).then((value) {
initiatePayment(amount: amount, orderId: orderId).then((value) {
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
GetPaymentTxtTokenModel result = value;
- startTransaction(context, txnTokenBy: result.body.txnToken ?? '', orderId: orderId, amount: amount, callBackURL: callback, isStaging: paytmModel.value.isSandboxEnabled);
+ startTransaction(
+ context,
+ txnTokenBy: result.body.txnToken ?? '',
+ orderId: orderId,
+ amount: amount,
+ callBackURL: callback,
+ isStaging: paytmModel.value.isSandboxEnabled,
+ );
});
});
}
- Future startTransaction(context, {required String txnTokenBy, required orderId, required double amount, required callBackURL, required isStaging}) async {
+ Future startTransaction(
+ context, {
+ required String txnTokenBy,
+ required orderId,
+ required double amount,
+ required callBackURL,
+ required isStaging,
+ }) async {
// try {
// var response = AllInOneSdk.startTransaction(
// paytmModel.value.paytmMID.toString(),
@@ -838,24 +1081,38 @@ class CartController extends GetxController {
// }
}
- Future verifyCheckSum({required String checkSum, required double amount, required orderId}) async {
+ Future verifyCheckSum({
+ required String checkSum,
+ required double amount,
+ required orderId,
+ }) async {
String getChecksum = "${Constant.globalUrl}payments/validatechecksum";
final response = await http.post(
Uri.parse(getChecksum),
headers: {},
- body: {"mid": paytmModel.value.paytmMID.toString(), "order_id": orderId, "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(), "checksum_value": checkSum},
+ body: {
+ "mid": paytmModel.value.paytmMID.toString(),
+ "order_id": orderId,
+ "key_secret": paytmModel.value.pAYTMMERCHANTKEY.toString(),
+ "checksum_value": checkSum,
+ },
);
final data = jsonDecode(response.body);
return data['status'];
}
- Future initiatePayment({required double amount, required orderId}) async {
+ Future initiatePayment({
+ required double amount,
+ required orderId,
+ }) async {
String initiateURL = "${Constant.globalUrl}payments/initiatepaytmpayment";
String callback = "";
if (paytmModel.value.isSandboxEnabled == true) {
- callback = "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
} else {
- callback = "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
+ callback =
+ "${callback}https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=$orderId";
}
final response = await http.post(
Uri.parse(initiateURL),
@@ -873,9 +1130,12 @@ class CartController extends GetxController {
);
log(response.body);
final data = jsonDecode(response.body);
- if (data["body"]["txnToken"] == null || data["body"]["txnToken"].toString().isEmpty) {
+ if (data["body"]["txnToken"] == null ||
+ data["body"]["txnToken"].toString().isEmpty) {
Get.back();
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
}
return GetPaymentTxtTokenModel.fromJson(data);
}
@@ -893,7 +1153,10 @@ class CartController extends GetxController {
'description': 'wallet Topup',
'retry': {'enabled': true, 'max_count': 1},
'send_sms_hash': true,
- 'prefill': {'contact': userModel.value.phoneNumber, 'email': userModel.value.email},
+ 'prefill': {
+ 'contact': userModel.value.phoneNumber,
+ 'email': userModel.value.email,
+ },
'external': {
'wallets': ['paytm'],
},
@@ -927,7 +1190,10 @@ class CartController extends GetxController {
}
//Midtrans payment
- Future midtransMakePayment({required String amount, required BuildContext context}) async {
+ Future midtransMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
await createPaymentLink(amount: amount).then((url) {
ShowToastDialog.closeLoader();
if (url != '') {
@@ -945,15 +1211,30 @@ class CartController extends GetxController {
Future createPaymentLink({required var amount}) async {
var ordersId = const Uuid().v1();
- final url = Uri.parse(midTransModel.value.isSandbox! ? 'https://api.sandbox.midtrans.com/v1/payment-links' : 'https://api.midtrans.com/v1/payment-links');
+ final url = Uri.parse(
+ midTransModel.value.isSandbox!
+ ? 'https://api.sandbox.midtrans.com/v1/payment-links'
+ : 'https://api.midtrans.com/v1/payment-links',
+ );
final response = await http.post(
url,
- headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': generateBasicAuthHeader(midTransModel.value.serverKey!)},
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ 'Authorization': generateBasicAuthHeader(
+ midTransModel.value.serverKey!,
+ ),
+ },
body: jsonEncode({
- 'transaction_details': {'order_id': ordersId, 'gross_amount': double.parse(amount.toString()).toInt()},
+ 'transaction_details': {
+ 'order_id': ordersId,
+ 'gross_amount': double.parse(amount.toString()).toInt(),
+ },
'usage_limit': 2,
- "callbacks": {"finish": "https://www.google.com?merchant_order_id=$ordersId"},
+ "callbacks": {
+ "finish": "https://www.google.com?merchant_order_id=$ordersId",
+ },
}),
);
@@ -961,7 +1242,9 @@ class CartController extends GetxController {
final responseData = jsonDecode(response.body);
return responseData['payment_url'];
} else {
- ShowToastDialog.showToast("something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -978,13 +1261,30 @@ class CartController extends GetxController {
static String orderId = '';
static String amount = '';
- Future orangeMakePayment({required String amount, required BuildContext context}) async {
+ Future orangeMakePayment({
+ required String amount,
+ required BuildContext context,
+ }) async {
reset();
var id = const Uuid().v4();
- var paymentURL = await fetchToken(context: context, orderId: id, amount: amount, currency: 'USD');
+ var paymentURL = await fetchToken(
+ context: context,
+ orderId: id,
+ amount: amount,
+ currency: 'USD',
+ );
ShowToastDialog.closeLoader();
if (paymentURL.toString() != '') {
- Get.to(() => OrangeMoneyScreen(initialURl: paymentURL, accessToken: accessToken, amount: amount, orangePay: orangeMoneyModel.value, orderId: orderId, payToken: payToken))!.then((value) {
+ Get.to(
+ () => OrangeMoneyScreen(
+ initialURl: paymentURL,
+ accessToken: accessToken,
+ amount: amount,
+ orangePay: orangeMoneyModel.value,
+ orderId: orderId,
+ payToken: payToken,
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -996,13 +1296,22 @@ class CartController extends GetxController {
}
}
- Future fetchToken({required String orderId, required String currency, required BuildContext context, required String amount}) async {
+ Future fetchToken({
+ required String orderId,
+ required String currency,
+ required BuildContext context,
+ required String amount,
+ }) async {
String apiUrl = 'https://api.orange.com/oauth/v3/token';
Map requestBody = {'grant_type': 'client_credentials'};
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': "Basic ${orangeMoneyModel.value.auth!}", 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': "Basic ${orangeMoneyModel.value.auth!}",
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Accept': 'application/json',
+ },
body: requestBody,
);
@@ -1013,17 +1322,32 @@ class CartController extends GetxController {
accessToken = responseData['access_token'];
// ignore: use_build_context_synchronously
- return await webpayment(context: context, amountData: amount, currency: currency, orderIdData: orderId);
+ return await webpayment(
+ context: context,
+ amountData: amount,
+ currency: currency,
+ orderIdData: orderId,
+ );
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
- Future webpayment({required String orderIdData, required BuildContext context, required String currency, required String amountData}) async {
+ Future webpayment({
+ required String orderIdData,
+ required BuildContext context,
+ required String currency,
+ required String amountData,
+ }) async {
orderId = orderIdData;
amount = amountData;
- String apiUrl = orangeMoneyModel.value.isSandbox! == true ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment' : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
+ String apiUrl =
+ orangeMoneyModel.value.isSandbox! == true
+ ? 'https://api.orange.com/orange-money-webpay/dev/v1/webpayment'
+ : 'https://api.orange.com/orange-money-webpay/cm/v1/webpayment';
Map requestBody = {
"merchant_key": orangeMoneyModel.value.merchantKey ?? '',
"currency": orangeMoneyModel.value.isSandbox == true ? "OUV" : currency,
@@ -1038,7 +1362,11 @@ class CartController extends GetxController {
var response = await http.post(
Uri.parse(apiUrl),
- headers: {'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', 'Accept': 'application/json'},
+ headers: {
+ 'Authorization': 'Bearer $accessToken',
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ },
body: json.encode(requestBody),
);
@@ -1052,7 +1380,9 @@ class CartController extends GetxController {
return '';
}
} else {
- ShowToastDialog.showToast("Something went wrong, please contact admin.".tr());
+ ShowToastDialog.showToast(
+ "Something went wrong, please contact admin.".tr(),
+ );
return '';
}
}
@@ -1069,7 +1399,13 @@ class CartController extends GetxController {
await createXenditInvoice(amount: amount).then((model) {
ShowToastDialog.closeLoader();
if (model.id != null) {
- Get.to(() => XenditScreen(initialURl: model.invoiceUrl ?? '', transId: model.id ?? '', apiKey: xenditModel.value.apiKey!.toString()))!.then((value) {
+ Get.to(
+ () => XenditScreen(
+ initialURl: model.invoiceUrl ?? '',
+ transId: model.id ?? '',
+ apiKey: xenditModel.value.apiKey!.toString(),
+ ),
+ )!.then((value) {
if (value == true) {
ShowToastDialog.showToast("Payment Successful!!".tr());
placeOrder();
@@ -1086,7 +1422,9 @@ class CartController extends GetxController {
const url = 'https://api.xendit.co/v2/invoices';
var headers = {
'Content-Type': 'application/json',
- 'Authorization': generateBasicAuthHeader(xenditModel.value.apiKey!.toString()),
+ 'Authorization': generateBasicAuthHeader(
+ xenditModel.value.apiKey!.toString(),
+ ),
// 'Cookie': '__cf_bm=yERkrx3xDITyFGiou0bbKY1bi7xEwovHNwxV1vCNbVc-1724155511-1.0.1.1-jekyYQmPCwY6vIJ524K0V6_CEw6O.dAwOmQnHtwmaXO_MfTrdnmZMka0KZvjukQgXu5B.K_6FJm47SGOPeWviQ',
};
@@ -1099,7 +1437,11 @@ class CartController extends GetxController {
});
try {
- final response = await http.post(Uri.parse(url), headers: headers, body: body);
+ final response = await http.post(
+ Uri.parse(url),
+ headers: headers,
+ body: body,
+ );
if (response.statusCode == 200 || response.statusCode == 201) {
XenditModel model = XenditModel.fromJson(jsonDecode(response.body));
diff --git a/lib/controllers/cashback_controller.dart b/lib/controllers/cashback_controller.dart
index 43aa518..786fa55 100644
--- a/lib/controllers/cashback_controller.dart
+++ b/lib/controllers/cashback_controller.dart
@@ -1,5 +1,5 @@
import '../models/cashback_model.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import '../service/fire_store_utils.dart';
class CashbackController extends GetxController {
diff --git a/lib/controllers/category_restaurant_controller.dart b/lib/controllers/category_restaurant_controller.dart
index bd8e41a..a80b92b 100644
--- a/lib/controllers/category_restaurant_controller.dart
+++ b/lib/controllers/category_restaurant_controller.dart
@@ -3,7 +3,7 @@ import 'package:customer/models/vendor_model.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../models/vendor_category_model.dart';
import '../service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class CategoryRestaurantController extends GetxController {
RxBool isLoading = true.obs;
@@ -33,9 +33,10 @@ class CategoryRestaurantController extends GetxController {
}
Future getRestaurant() async {
- FireStoreUtils.getAllNearestRestaurantByCategoryId(categoryId: vendorCategoryModel.value.id.toString(), isDining: dineIn.value).listen((
- event,
- ) async {
+ FireStoreUtils.getAllNearestRestaurantByCategoryId(
+ categoryId: vendorCategoryModel.value.id.toString(),
+ isDining: dineIn.value,
+ ).listen((event) async {
allNearestRestaurant.clear();
allNearestRestaurant.addAll(event);
});
@@ -46,7 +47,10 @@ class CategoryRestaurantController extends GetxController {
if (value != null) {
for (int i = 0; i < value.length; i++) {
if (Constant.isPointInPolygon(
- LatLng(Constant.selectedLocation.location!.latitude ?? 0.0, Constant.selectedLocation.location!.longitude ?? 0.0),
+ LatLng(
+ Constant.selectedLocation.location!.latitude ?? 0.0,
+ Constant.selectedLocation.location!.longitude ?? 0.0,
+ ),
value[i].area!,
)) {
Constant.selectedZone = value[i];
diff --git a/lib/controllers/change_language_controller.dart b/lib/controllers/change_language_controller.dart
index aad7891..82be122 100644
--- a/lib/controllers/change_language_controller.dart
+++ b/lib/controllers/change_language_controller.dart
@@ -2,8 +2,7 @@ import 'package:customer/constant/constant.dart';
import 'package:customer/models/language_model.dart';
import '../service/fire_store_utils.dart';
import 'package:customer/utils/preferences.dart';
-import 'package:get/get.dart';
-
+import 'package:get/get.dart' hide Trans;
import '../constant/collection_name.dart';
class ChangeLanguageController extends GetxController {
@@ -20,24 +19,30 @@ class ChangeLanguageController extends GetxController {
}
Future getLanguage() async {
- await FireStoreUtils.fireStore.collection(CollectionName.settings).doc("languages").get().then((event) {
- if (event.exists) {
- List languageListTemp = event.data()!["list"];
- for (var element in languageListTemp) {
- LanguageModel languageModel = LanguageModel.fromJson(element);
- languageList.add(languageModel);
- }
+ await FireStoreUtils.fireStore
+ .collection(CollectionName.settings)
+ .doc("languages")
+ .get()
+ .then((event) {
+ if (event.exists) {
+ List languageListTemp = event.data()!["list"];
+ for (var element in languageListTemp) {
+ LanguageModel languageModel = LanguageModel.fromJson(element);
+ languageList.add(languageModel);
+ }
- if (Preferences.getString(Preferences.languageCodeKey).toString().isNotEmpty) {
- LanguageModel pref = Constant.getLanguage();
- for (var element in languageList) {
- if (element.slug == pref.slug) {
- selectedLanguage.value = element;
+ if (Preferences.getString(
+ Preferences.languageCodeKey,
+ ).toString().isNotEmpty) {
+ LanguageModel pref = Constant.getLanguage();
+ for (var element in languageList) {
+ if (element.slug == pref.slug) {
+ selectedLanguage.value = element;
+ }
+ }
}
}
- }
- }
- });
+ });
isLoading.value = false;
}
diff --git a/lib/controllers/chat_controller.dart b/lib/controllers/chat_controller.dart
index bce8cf5..c0e2925 100644
--- a/lib/controllers/chat_controller.dart
+++ b/lib/controllers/chat_controller.dart
@@ -7,7 +7,7 @@ import '../models/conversation_model.dart';
import '../models/inbox_model.dart';
import '../service/fire_store_utils.dart';
import 'package:flutter/material.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:uuid/uuid.dart';
import '../service/send_notification.dart';
@@ -21,7 +21,11 @@ class ChatController extends GetxController {
void onInit() {
// TODO: implement onInit
if (scrollController.hasClients) {
- Timer(const Duration(milliseconds: 500), () => scrollController.jumpTo(scrollController.position.maxScrollExtent));
+ Timer(
+ const Duration(milliseconds: 500),
+ () =>
+ scrollController.jumpTo(scrollController.position.maxScrollExtent),
+ );
}
getArgument();
super.onInit();
@@ -47,14 +51,20 @@ class ChatController extends GetxController {
customerProfileImage.value = argumentData['customerProfileImage'] ?? "";
restaurantId.value = argumentData['restaurantId'];
restaurantName.value = argumentData['restaurantName'];
- restaurantProfileImage.value = argumentData['restaurantProfileImage'] ?? "";
+ restaurantProfileImage.value =
+ argumentData['restaurantProfileImage'] ?? "";
token.value = argumentData['token'] ?? "";
chatType.value = argumentData['chatType'];
}
isLoading.value = false;
}
- Future sendMessage(String message, Url? url, String videoThumbnail, String messageType) async {
+ Future sendMessage(
+ String message,
+ Url? url,
+ String videoThumbnail,
+ String messageType,
+ ) async {
InboxModel inboxModel = InboxModel(
lastSenderId: customerId.value,
customerId: customerId.value,
@@ -113,18 +123,23 @@ class ChatController extends GetxController {
}
//await SendNotification.sendChatFcmMessage(customerName.value, conversationModel.message.toString(), token.value, {});
- await SendNotification.sendChatFcmMessage(customerName.value, conversationModel.message.toString(), token.value, {
- "type": "chat",
- "chatType": chatType.value,
- "orderId": orderId.value,
- "customerId": customerId.value,
- "customerName": customerName.value,
- "customerProfileImage": customerProfileImage.value,
- "restaurantId": restaurantId.value,
- "restaurantName": restaurantName.value,
- "restaurantProfileImage": restaurantProfileImage.value,
- "token": token.value,
- });
+ await SendNotification.sendChatFcmMessage(
+ customerName.value,
+ conversationModel.message.toString(),
+ token.value,
+ {
+ "type": "chat",
+ "chatType": chatType.value,
+ "orderId": orderId.value,
+ "customerId": customerId.value,
+ "customerName": customerName.value,
+ "customerProfileImage": customerProfileImage.value,
+ "restaurantId": restaurantId.value,
+ "restaurantName": restaurantName.value,
+ "restaurantProfileImage": restaurantProfileImage.value,
+ "token": token.value,
+ },
+ );
}
final ImagePicker imagePicker = ImagePicker();
diff --git a/lib/controllers/complain_controller.dart b/lib/controllers/complain_controller.dart
index a76d011..45367eb 100644
--- a/lib/controllers/complain_controller.dart
+++ b/lib/controllers/complain_controller.dart
@@ -1,6 +1,6 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import '../models/cab_order_model.dart';
import '../service/fire_store_utils.dart';
import '../themes/show_toast_dialog.dart';
@@ -30,7 +30,9 @@ class ComplainController extends GetxController {
Future getComplain() async {
isLoading.value = true;
try {
- final data = await FireStoreUtils.getRideComplainData(order.value.id ?? '');
+ final data = await FireStoreUtils.getRideComplainData(
+ order.value.id ?? '',
+ );
if (data != null) {
title.value.text = data['title'] ?? '';
comment.value.text = data['description'] ?? '';
@@ -59,7 +61,9 @@ class ComplainController extends GetxController {
try {
// Check if complaint already exists
- bool exists = await FireStoreUtils.isRideComplainAdded(order.value.id ?? '');
+ bool exists = await FireStoreUtils.isRideComplainAdded(
+ order.value.id ?? '',
+ );
if (!exists) {
await FireStoreUtils.setRideComplain(
@@ -67,13 +71,19 @@ class ComplainController extends GetxController {
title: title.value.text.trim(),
description: comment.value.text.trim(),
customerID: order.value.authorID ?? '',
- customerName: "${order.value.author?.firstName ?? ''} ${order.value.author?.lastName ?? ''}".trim(),
+ customerName:
+ "${order.value.author?.firstName ?? ''} ${order.value.author?.lastName ?? ''}"
+ .trim(),
driverID: order.value.driverId ?? '',
- driverName: "${order.value.driver?.firstName ?? ''} ${order.value.driver?.lastName ?? ''}".trim(),
+ driverName:
+ "${order.value.driver?.firstName ?? ''} ${order.value.driver?.lastName ?? ''}"
+ .trim(),
);
ShowToastDialog.closeLoader();
- ShowToastDialog.showToast("Your complaint has been submitted to admin".tr());
+ ShowToastDialog.showToast(
+ "Your complaint has been submitted to admin".tr(),
+ );
Get.back();
} else {
ShowToastDialog.closeLoader();
diff --git a/lib/controllers/dash_board_controller.dart b/lib/controllers/dash_board_controller.dart
index ae6445f..405df62 100644
--- a/lib/controllers/dash_board_controller.dart
+++ b/lib/controllers/dash_board_controller.dart
@@ -6,7 +6,7 @@ import '../screen_ui/multi_vendor_service/order_list_screen/order_screen.dart';
import '../screen_ui/multi_vendor_service/profile_screen/profile_screen.dart';
import '../screen_ui/multi_vendor_service/wallet_screen/wallet_screen.dart';
import '../service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DashBoardController extends GetxController {
RxInt selectedIndex = 0.obs;
@@ -19,22 +19,46 @@ class DashBoardController extends GetxController {
getTaxList();
if (Constant.sectionConstantModel!.theme == "theme_2") {
if (Constant.walletSetting == false) {
- pageList.value = [const HomeScreen(), const FavouriteScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeScreen(),
+ const FavouriteScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
} else {
- pageList.value = [const HomeScreen(), const FavouriteScreen(), const WalletScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeScreen(),
+ const FavouriteScreen(),
+ const WalletScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
}
} else {
if (Constant.walletSetting == false) {
- pageList.value = [const HomeScreenTwo(), const FavouriteScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeScreenTwo(),
+ const FavouriteScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
} else {
- pageList.value = [const HomeScreenTwo(), const FavouriteScreen(), const WalletScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeScreenTwo(),
+ const FavouriteScreen(),
+ const WalletScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
}
}
super.onInit();
}
Future getTaxList() async {
- await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((value) {
+ await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((
+ value,
+ ) {
if (value != null) {
Constant.taxList = value;
}
diff --git a/lib/controllers/dash_board_ecommarce_controller.dart b/lib/controllers/dash_board_ecommarce_controller.dart
index 02bb9ce..647f120 100644
--- a/lib/controllers/dash_board_ecommarce_controller.dart
+++ b/lib/controllers/dash_board_ecommarce_controller.dart
@@ -5,7 +5,7 @@ import '../screen_ui/multi_vendor_service/order_list_screen/order_screen.dart';
import '../screen_ui/multi_vendor_service/profile_screen/profile_screen.dart';
import '../screen_ui/multi_vendor_service/wallet_screen/wallet_screen.dart';
import '../service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DashBoardEcommerceController extends GetxController {
RxInt selectedIndex = 0.obs;
@@ -17,15 +17,28 @@ class DashBoardEcommerceController extends GetxController {
// TODO: implement onInit
getTaxList();
if (Constant.walletSetting == false) {
- pageList.value = [const HomeECommerceScreen(), const FavouriteScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeECommerceScreen(),
+ const FavouriteScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
} else {
- pageList.value = [const HomeECommerceScreen(), const FavouriteScreen(), const WalletScreen(), const OrderScreen(), const ProfileScreen()];
+ pageList.value = [
+ const HomeECommerceScreen(),
+ const FavouriteScreen(),
+ const WalletScreen(),
+ const OrderScreen(),
+ const ProfileScreen(),
+ ];
}
super.onInit();
}
Future getTaxList() async {
- await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((value) {
+ await FireStoreUtils.getTaxList(Constant.sectionConstantModel!.id).then((
+ value,
+ ) {
if (value != null) {
Constant.taxList = value;
}
diff --git a/lib/controllers/dine_in_booking_controller.dart b/lib/controllers/dine_in_booking_controller.dart
index e273284..4f31c69 100644
--- a/lib/controllers/dine_in_booking_controller.dart
+++ b/lib/controllers/dine_in_booking_controller.dart
@@ -1,6 +1,6 @@
import '../models/dine_in_booking_model.dart';
import '../service/fire_store_utils.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DineInBookingController extends GetxController {
RxBool isLoading = true.obs;
@@ -18,16 +18,12 @@ class DineInBookingController extends GetxController {
}
Future getDineInBooking() async {
- await FireStoreUtils.getDineInBooking(true).then(
- (value) {
- featureList.value = value;
- },
- );
- await FireStoreUtils.getDineInBooking(false).then(
- (value) {
- historyList.value = value;
- },
- );
+ await FireStoreUtils.getDineInBooking(true).then((value) {
+ featureList.value = value;
+ });
+ await FireStoreUtils.getDineInBooking(false).then((value) {
+ historyList.value = value;
+ });
isLoading.value = false;
}
diff --git a/lib/controllers/dine_in_booking_details_controller.dart b/lib/controllers/dine_in_booking_details_controller.dart
index 994420c..9332e76 100644
--- a/lib/controllers/dine_in_booking_details_controller.dart
+++ b/lib/controllers/dine_in_booking_details_controller.dart
@@ -1,5 +1,5 @@
import 'package:customer/models/dine_in_booking_model.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DineInBookingDetailsController extends GetxController {
RxBool isLoading = true.obs;
diff --git a/lib/controllers/dine_in_controller.dart b/lib/controllers/dine_in_controller.dart
index b582900..57c6524 100644
--- a/lib/controllers/dine_in_controller.dart
+++ b/lib/controllers/dine_in_controller.dart
@@ -7,7 +7,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../models/banner_model.dart';
import '../service/fire_store_utils.dart';
import 'package:flutter/material.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DineInController extends GetxController {
RxBool isLoading = true.obs;
@@ -28,7 +28,8 @@ class DineInController extends GetxController {
RxList popularRestaurantList = [].obs;
RxList bannerBottomModel = [].obs;
- Rx pageBottomController = PageController(viewportFraction: 0.877).obs;
+ Rx pageBottomController =
+ PageController(viewportFraction: 0.877).obs;
RxInt currentBottomPage = 0.obs;
RxList favouriteList = [].obs;
@@ -37,7 +38,9 @@ class DineInController extends GetxController {
isLoading.value = true;
await getZone();
- FireStoreUtils.getAllNearestRestaurant(isDining: true).listen((event) async {
+ FireStoreUtils.getAllNearestRestaurant(isDining: true).listen((
+ event,
+ ) async {
newArrivalRestaurantList.clear();
allNearestRestaurant.clear();
popularRestaurantList.clear();
@@ -47,12 +50,21 @@ class DineInController extends GetxController {
popularRestaurantList.addAll(event);
popularRestaurantList.sort(
- (a, b) => Constant.calculateReview(reviewCount: b.reviewsCount.toString(), reviewSum: b.reviewsSum.toString())
- .compareTo(Constant.calculateReview(reviewCount: a.reviewsCount.toString(), reviewSum: a.reviewsSum.toString())),
+ (a, b) => Constant.calculateReview(
+ reviewCount: b.reviewsCount.toString(),
+ reviewSum: b.reviewsSum.toString(),
+ ).compareTo(
+ Constant.calculateReview(
+ reviewCount: a.reviewsCount.toString(),
+ reviewSum: a.reviewsSum.toString(),
+ ),
+ ),
);
newArrivalRestaurantList.sort(
- (a, b) => (b.createdAt ?? Timestamp.now()).toDate().compareTo((a.createdAt ?? Timestamp.now()).toDate()),
+ (a, b) => (b.createdAt ?? Timestamp.now()).toDate().compareTo(
+ (a.createdAt ?? Timestamp.now()).toDate(),
+ ),
);
});
@@ -61,23 +73,17 @@ class DineInController extends GetxController {
}
Future getCategory() async {
- await FireStoreUtils.getHomeVendorCategory().then(
- (value) {
- vendorCategoryModel.value = value;
- },
- );
+ await FireStoreUtils.getHomeVendorCategory().then((value) {
+ vendorCategoryModel.value = value;
+ });
- await FireStoreUtils.getHomeBottomBanner().then(
- (value) {
- bannerBottomModel.value = value;
- },
- );
+ await FireStoreUtils.getHomeBottomBanner().then((value) {
+ bannerBottomModel.value = value;
+ });
if (Constant.userModel != null) {
- await FireStoreUtils.getFavouriteRestaurant().then(
- (value) {
- favouriteList.value = value;
- },
- );
+ await FireStoreUtils.getFavouriteRestaurant().then((value) {
+ favouriteList.value = value;
+ });
}
}
@@ -85,7 +91,13 @@ class DineInController extends GetxController {
await FireStoreUtils.getZone().then((value) {
if (value != null) {
for (int i = 0; i < value.length; i++) {
- if (Constant.isPointInPolygon(LatLng(Constant.selectedLocation.location!.latitude ?? 0.0, Constant.selectedLocation.location!.longitude ?? 0.0), value[i].area!)) {
+ if (Constant.isPointInPolygon(
+ LatLng(
+ Constant.selectedLocation.location!.latitude ?? 0.0,
+ Constant.selectedLocation.location!.longitude ?? 0.0,
+ ),
+ value[i].area!,
+ )) {
Constant.selectedZone = value[i];
Constant.isZoneAvailable = true;
break;
@@ -96,5 +108,4 @@ class DineInController extends GetxController {
}
});
}
-
}
diff --git a/lib/controllers/dine_in_restaurant_details_controller.dart b/lib/controllers/dine_in_restaurant_details_controller.dart
index 8d2105c..5436203 100644
--- a/lib/controllers/dine_in_restaurant_details_controller.dart
+++ b/lib/controllers/dine_in_restaurant_details_controller.dart
@@ -8,16 +8,18 @@ import 'package:easy_localization/easy_localization.dart';
import '../screen_ui/multi_vendor_service/dine_in_booking/dine_in_booking_screen.dart';
import '../service/fire_store_utils.dart';
import 'package:flutter/material.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:intl/intl.dart';
import '../service/send_notification.dart';
import '../themes/show_toast_dialog.dart';
class DineInRestaurantDetailsController extends GetxController {
- Rx searchEditingController = TextEditingController().obs;
+ Rx searchEditingController =
+ TextEditingController().obs;
- Rx additionRequestController = TextEditingController().obs;
+ Rx additionRequestController =
+ TextEditingController().obs;
RxBool isLoading = true.obs;
RxBool firstVisit = false.obs;
@@ -42,6 +44,7 @@ class DineInRestaurantDetailsController extends GetxController {
return key;
}
}
+
RxString selectedOccasion = "".obs;
RxList dateList = [].obs;
@@ -65,30 +68,53 @@ class DineInRestaurantDetailsController extends GetxController {
ShowToastDialog.showLoader("Please wait...".tr());
DateTime dt = selectedDate.value.toDate();
- String hour = DateFormat("kk:mm").format(DateFormat('hh:mm a').parse((Intl.getCurrentLocale() == "en_US") ? selectedTimeSlot.value : selectedTimeSlot.value.toLowerCase()));
- dt = DateTime(dt.year, dt.month, dt.day, int.parse(hour.split(":")[0]), int.parse(hour.split(":")[1]), dt.second, dt.millisecond, dt.microsecond);
+ String hour = DateFormat("kk:mm").format(
+ DateFormat('hh:mm a').parse(
+ (Intl.getCurrentLocale() == "en_US")
+ ? selectedTimeSlot.value
+ : selectedTimeSlot.value.toLowerCase(),
+ ),
+ );
+ dt = DateTime(
+ dt.year,
+ dt.month,
+ dt.day,
+ int.parse(hour.split(":")[0]),
+ int.parse(hour.split(":")[1]),
+ dt.second,
+ dt.millisecond,
+ dt.microsecond,
+ );
selectedDate.value = Timestamp.fromDate(dt);
DineInBookingModel dineInBookingModel = DineInBookingModel(
- id: Constant.getUuid(),
- author: Constant.userModel,
- authorID: FireStoreUtils.getCurrentUid(),
- createdAt: Timestamp.now(),
- date: selectedDate.value,
- status: Constant.orderPlaced,
- vendor: vendorModel.value,
- specialRequest: additionRequestController.value.text.isEmpty ? "" : additionRequestController.value.text,
- vendorID: vendorModel.value.id,
- guestEmail: Constant.userModel!.email,
- guestFirstName: Constant.userModel!.firstName,
- guestLastName: Constant.userModel!.lastName,
- guestPhone: Constant.userModel!.phoneNumber,
- occasion: selectedOccasion.value,
- discount: selectedTimeDiscount.value,
- discountType: selectedTimeDiscountType.value,
- totalGuest: noOfQuantity.value.toString(),
- firstVisit: firstVisit.value);
+ id: Constant.getUuid(),
+ author: Constant.userModel,
+ authorID: FireStoreUtils.getCurrentUid(),
+ createdAt: Timestamp.now(),
+ date: selectedDate.value,
+ status: Constant.orderPlaced,
+ vendor: vendorModel.value,
+ specialRequest:
+ additionRequestController.value.text.isEmpty
+ ? ""
+ : additionRequestController.value.text,
+ vendorID: vendorModel.value.id,
+ guestEmail: Constant.userModel!.email,
+ guestFirstName: Constant.userModel!.firstName,
+ guestLastName: Constant.userModel!.lastName,
+ guestPhone: Constant.userModel!.phoneNumber,
+ occasion: selectedOccasion.value,
+ discount: selectedTimeDiscount.value,
+ discountType: selectedTimeDiscountType.value,
+ totalGuest: noOfQuantity.value.toString(),
+ firstVisit: firstVisit.value,
+ );
await FireStoreUtils.setBookedOrder(dineInBookingModel);
- await SendNotification.sendFcmMessage(Constant.dineInPlaced, vendorModel.value.fcmToken.toString(), {});
+ await SendNotification.sendFcmMessage(
+ Constant.dineInPlaced,
+ vendorModel.value.fcmToken.toString(),
+ {},
+ );
ShowToastDialog.closeLoader();
Get.back();
Get.to(const DineInBookingScreen());
@@ -99,27 +125,46 @@ class DineInRestaurantDetailsController extends GetxController {
for (int i = 0; i < 7; i++) {
final now = DateTime.now().add(Duration(days: i));
var day = DateFormat('EEEE').format(now);
- if (vendorModel.value.specialDiscount?.isNotEmpty == true && vendorModel.value.specialDiscountEnable == true) {
+ if (vendorModel.value.specialDiscount?.isNotEmpty == true &&
+ vendorModel.value.specialDiscountEnable == true) {
for (var element in vendorModel.value.specialDiscount!) {
if (day == element.day.toString()) {
if (element.timeslot!.isNotEmpty) {
- SpecialDiscountTimeslot employeeWithMaxSalary =
- element.timeslot!.reduce((item1, item2) => double.parse(item1.discount.toString()) > double.parse(item2.discount.toString()) ? item1 : item2);
+ SpecialDiscountTimeslot employeeWithMaxSalary = element.timeslot!
+ .reduce(
+ (item1, item2) =>
+ double.parse(item1.discount.toString()) >
+ double.parse(item2.discount.toString())
+ ? item1
+ : item2,
+ );
if (employeeWithMaxSalary.discountType == "dinein") {
- DateModel model = DateModel(date: Timestamp.fromDate(now), discountPer: employeeWithMaxSalary.discount.toString());
+ DateModel model = DateModel(
+ date: Timestamp.fromDate(now),
+ discountPer: employeeWithMaxSalary.discount.toString(),
+ );
dateList.add(model);
} else {
- DateModel model = DateModel(date: Timestamp.fromDate(now), discountPer: "0");
+ DateModel model = DateModel(
+ date: Timestamp.fromDate(now),
+ discountPer: "0",
+ );
dateList.add(model);
}
} else {
- DateModel model = DateModel(date: Timestamp.fromDate(now), discountPer: "0");
+ DateModel model = DateModel(
+ date: Timestamp.fromDate(now),
+ discountPer: "0",
+ );
dateList.add(model);
}
}
}
} else {
- DateModel model = DateModel(date: Timestamp.fromDate(now), discountPer: "0");
+ DateModel model = DateModel(
+ date: Timestamp.fromDate(now),
+ discountPer: "0",
+ );
dateList.add(model);
}
}
@@ -127,70 +172,116 @@ class DineInRestaurantDetailsController extends GetxController {
timeSet(selectedDate.value);
if (timeSlotList.isNotEmpty) {
- selectedTimeSlot.value = DateFormat('hh:mm a').format(timeSlotList[0].time!);
+ selectedTimeSlot.value = DateFormat(
+ 'hh:mm a',
+ ).format(timeSlotList[0].time!);
}
}
void timeSet(Timestamp selectedDate) {
timeSlotList.clear();
- for (DateTime time = Constant.stringToDate(vendorModel.value.openDineTime.toString());
- time.isBefore(Constant.stringToDate(vendorModel.value.closeDineTime.toString()));
- time = time.add(const Duration(minutes: 30))) {
+ for (
+ DateTime time = Constant.stringToDate(
+ vendorModel.value.openDineTime.toString(),
+ );
+ time.isBefore(
+ Constant.stringToDate(vendorModel.value.closeDineTime.toString()),
+ );
+ time = time.add(const Duration(minutes: 30))
+ ) {
final now = DateTime.parse(selectedDate.toDate().toString());
var day = DateFormat('EEEE').format(now);
var date = DateFormat('dd-MM-yyyy').format(now);
- if (vendorModel.value.specialDiscount?.isNotEmpty == true && vendorModel.value.specialDiscountEnable == true) {
+ if (vendorModel.value.specialDiscount?.isNotEmpty == true &&
+ vendorModel.value.specialDiscountEnable == true) {
for (var element in vendorModel.value.specialDiscount!) {
if (day == element.day.toString()) {
if (element.timeslot!.isNotEmpty) {
for (var element in element.timeslot!) {
if (element.discountType == "dinein") {
- var start = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.from}");
- var end = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.to}");
- var selected = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${DateFormat.Hm().format(time)}");
+ var start = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.from}");
+ var end = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.to}");
+ var selected = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${DateFormat.Hm().format(time)}");
if (isCurrentDateInRangeDineIn(start, end, selected)) {
- var contains = timeSlotList.where((element) => element.time == time);
+ var contains = timeSlotList.where(
+ (element) => element.time == time,
+ );
if (contains.isNotEmpty) {
- var index = timeSlotList.indexWhere((element) => element.time == time);
+ var index = timeSlotList.indexWhere(
+ (element) => element.time == time,
+ );
if (timeSlotList[index].discountPer == "0") {
timeSlotList.removeAt(index);
- TimeModel model = TimeModel(time: time, discountPer: element.discount, discountType: element.type);
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: element.discount,
+ discountType: element.type,
+ );
timeSlotList.insert(index == 0 ? 0 : index, model);
}
} else {
- TimeModel model = TimeModel(time: time, discountPer: element.discount, discountType: element.type);
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: element.discount,
+ discountType: element.type,
+ );
timeSlotList.add(model);
}
} else {
- var contains = timeSlotList.where((element) => element.time == time);
+ var contains = timeSlotList.where(
+ (element) => element.time == time,
+ );
if (contains.isEmpty) {
- TimeModel model = TimeModel(time: time, discountPer: "0", discountType: "amount");
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: "0",
+ discountType: "amount",
+ );
timeSlotList.add(model);
}
}
} else {
- TimeModel model = TimeModel(time: time, discountPer: "0", discountType: "amount");
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: "0",
+ discountType: "amount",
+ );
timeSlotList.add(model);
}
}
} else {
- TimeModel model = TimeModel(time: time, discountPer: "0", discountType: "amount");
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: "0",
+ discountType: "amount",
+ );
timeSlotList.add(model);
}
}
}
} else {
- TimeModel model = TimeModel(time: time, discountPer: "0", discountType: "amount");
+ TimeModel model = TimeModel(
+ time: time,
+ discountPer: "0",
+ discountType: "amount",
+ );
timeSlotList.add(model);
}
}
}
void animateSlider() {
- if (vendorModel.value.photos != null && vendorModel.value.photos!.isNotEmpty) {
+ if (vendorModel.value.photos != null &&
+ vendorModel.value.photos!.isNotEmpty) {
Timer.periodic(const Duration(seconds: 2), (Timer timer) {
if (currentPage < vendorModel.value.photos!.length) {
currentPage++;
@@ -226,18 +317,16 @@ class DineInRestaurantDetailsController extends GetxController {
Future getFavouriteList() async {
if (Constant.userModel != null) {
- await FireStoreUtils.getFavouriteRestaurant().then(
- (value) {
- favouriteList.value = value;
- },
- );
+ await FireStoreUtils.getFavouriteRestaurant().then((value) {
+ favouriteList.value = value;
+ });
}
- await FireStoreUtils.getVendorCuisines(vendorModel.value.id.toString()).then(
- (value) {
- tags.value = value;
- },
- );
+ await FireStoreUtils.getVendorCuisines(
+ vendorModel.value.id.toString(),
+ ).then((value) {
+ tags.value = value;
+ });
update();
}
@@ -251,8 +340,12 @@ class DineInRestaurantDetailsController extends GetxController {
if (day == element.day.toString()) {
if (element.timeslot!.isNotEmpty) {
for (var element in element.timeslot!) {
- var start = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.from}");
- var end = DateFormat("dd-MM-yyyy HH:mm").parse("$date ${element.to}");
+ var start = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.from}");
+ var end = DateFormat(
+ "dd-MM-yyyy HH:mm",
+ ).parse("$date ${element.to}");
if (isCurrentDateInRange(start, end)) {
isOpen.value = true;
}
@@ -262,8 +355,14 @@ class DineInRestaurantDetailsController extends GetxController {
}
}
- bool isCurrentDateInRangeDineIn(DateTime startDate, DateTime endDate, DateTime selected) {
- return selected.isAtSameMomentAs(startDate) || selected.isAtSameMomentAs(endDate) || selected.isAfter(startDate) && selected.isBefore(endDate);
+ bool isCurrentDateInRangeDineIn(
+ DateTime startDate,
+ DateTime endDate,
+ DateTime selected,
+ ) {
+ return selected.isAtSameMomentAs(startDate) ||
+ selected.isAtSameMomentAs(endDate) ||
+ selected.isAfter(startDate) && selected.isBefore(endDate);
}
bool isCurrentDateInRange(DateTime startDate, DateTime endDate) {
@@ -284,5 +383,9 @@ class TimeModel {
String? discountPer;
String? discountType;
- TimeModel({required this.time, required this.discountPer, required this.discountType});
+ TimeModel({
+ required this.time,
+ required this.discountPer,
+ required this.discountType,
+ });
}
diff --git a/lib/controllers/discount_restaurant_list_controller.dart b/lib/controllers/discount_restaurant_list_controller.dart
index 4b01083..bc5b12e 100644
--- a/lib/controllers/discount_restaurant_list_controller.dart
+++ b/lib/controllers/discount_restaurant_list_controller.dart
@@ -1,6 +1,6 @@
import 'package:customer/models/coupon_model.dart';
import 'package:customer/models/vendor_model.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
class DiscountRestaurantListController extends GetxController {
RxBool isLoading = true.obs;
diff --git a/lib/controllers/edit_profile_controller.dart b/lib/controllers/edit_profile_controller.dart
index 47537b4..6fc4203 100644
--- a/lib/controllers/edit_profile_controller.dart
+++ b/lib/controllers/edit_profile_controller.dart
@@ -5,7 +5,7 @@ import 'package:easy_localization/easy_localization.dart';
import '../service/fire_store_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:get/get.dart';
+import 'package:get/get.dart' hide Trans;
import 'package:image_picker/image_picker.dart';
import '../themes/show_toast_dialog.dart';
@@ -18,7 +18,8 @@ class EditProfileController extends GetxController {
Rx lastNameController = TextEditingController().obs;
Rx