25-10-2/1
This commit is contained in:
@@ -246,7 +246,7 @@ class HomeCaptainController extends GetxController {
|
||||
// isLoading = true;
|
||||
update();
|
||||
|
||||
var res = await CRUD().get(
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getDriverPaymentPoints,
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()},
|
||||
);
|
||||
@@ -268,7 +268,7 @@ class HomeCaptainController extends GetxController {
|
||||
void onInit() async {
|
||||
// await locationBackController.requestLocationPermission();
|
||||
Get.put(FirebaseMessagesController());
|
||||
addToken();
|
||||
// addToken();
|
||||
await getlocation();
|
||||
onButtonSelected();
|
||||
getDriverRate();
|
||||
@@ -327,39 +327,23 @@ class HomeCaptainController extends GetxController {
|
||||
|
||||
addToken() async {
|
||||
String? fingerPrint = await storage.read(key: BoxName.fingerPrint);
|
||||
CRUD().post(link: AppLink.addTokensDriver, payload: {
|
||||
final payload = {
|
||||
'token': (box.read(BoxName.tokenDriver)),
|
||||
'captain_id': (box.read(BoxName.driverID)).toString(),
|
||||
'fingerPrint': (fingerPrint).toString()
|
||||
});
|
||||
};
|
||||
Log.print('payload: ${payload}');
|
||||
CRUD().post(link: AppLink.addTokensDriver, payload: payload);
|
||||
|
||||
// CRUD().post(
|
||||
// link: "${AppLink.seferAlexandriaServer}/ride/firebase/addDriver.php",
|
||||
// payload: {
|
||||
// 'token': box.read(BoxName.tokenDriver),
|
||||
// 'captain_id': box.read(BoxName.driverID).toString(),
|
||||
// 'fingerPrint': (fingerPrint).toString()
|
||||
// });
|
||||
// CRUD().post(
|
||||
// link: "${AppLink.seferGizaServer}/ride/firebase/addDriver.php",
|
||||
// payload: {
|
||||
// 'token': box.read(BoxName.tokenDriver),
|
||||
// 'captain_id': box.read(BoxName.driverID).toString(),
|
||||
// 'fingerPrint': (fingerPrint).toString()
|
||||
// });
|
||||
await CRUD().postWallet(
|
||||
await CRUD().post(
|
||||
link: "${AppLink.seferPaymentServer}/ride/firebase/addDriver.php",
|
||||
payload: {
|
||||
'token': box.read(BoxName.tokenDriver),
|
||||
'captain_id': box.read(BoxName.driverID).toString(),
|
||||
'fingerPrint': (fingerPrint).toString()
|
||||
});
|
||||
payload: payload);
|
||||
// MapDriverController().driverCallPassenger();
|
||||
// box.write(BoxName.statusDriverLocation, 'off');
|
||||
}
|
||||
|
||||
getPaymentToday() async {
|
||||
var res = await CRUD().get(
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getDriverPaymentToday,
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()});
|
||||
if (res != 'failure') {
|
||||
@@ -423,7 +407,7 @@ class HomeCaptainController extends GetxController {
|
||||
}
|
||||
|
||||
getAllPayment() async {
|
||||
var res = await CRUD().get(
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getAllPaymentFromRide,
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()});
|
||||
if (res == 'failure') {
|
||||
@@ -447,10 +431,15 @@ class HomeCaptainController extends GetxController {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getTotalDriverDurationToday,
|
||||
payload: {'driver_id': box.read(BoxName.driverID).toString()});
|
||||
|
||||
data = jsonDecode(res);
|
||||
totalDurationToday = data['message'][0]['total_duration'];
|
||||
update();
|
||||
if (res == 'failure') {
|
||||
totalDurationToday = '0';
|
||||
update();
|
||||
return;
|
||||
} else {
|
||||
data = jsonDecode(res);
|
||||
totalDurationToday = data['message'][0]['total_duration'];
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -664,14 +664,22 @@ class MapDriverController extends GetxController {
|
||||
return d['message'];
|
||||
}
|
||||
|
||||
// ... other controller code ...
|
||||
|
||||
/// Refactored function to finish a ride with consolidated API calls.
|
||||
void finishRideFromDriver1() async {
|
||||
// Show a loading indicator to the user
|
||||
Get.dialog(Center(child: CircularProgressIndicator()),
|
||||
barrierDismissible: false);
|
||||
|
||||
isRideFinished = true;
|
||||
isRideStarted = false;
|
||||
isPriceWindow = false;
|
||||
box.write(BoxName.rideStatus, 'Finished');
|
||||
Log.print('rideStatus from map 664 : ${box.read(BoxName.rideStatus)}');
|
||||
Log.print(
|
||||
'rideStatus from map (refactored) : ${box.read(BoxName.rideStatus)}');
|
||||
|
||||
// Calculate totalCost more concisely
|
||||
// --- 1. Calculate Total Cost (Logic remains the same) ---
|
||||
if (price < 16000) {
|
||||
totalCost = (carType == 'Comfort' ||
|
||||
carType == 'Mishwar Vip' ||
|
||||
@@ -690,224 +698,100 @@ class MapDriverController extends GetxController {
|
||||
paymentAmount = totalCost;
|
||||
box.write(BoxName.statusDriverLocation, 'off');
|
||||
|
||||
// Prepare data for API calls
|
||||
// --- 2. Prepare Payloads for Consolidated API Calls ---
|
||||
final nowString = DateTime.now().toString();
|
||||
final basePayload = {
|
||||
'id': (rideId),
|
||||
|
||||
final rideUpdatePayload = {
|
||||
'rideId': rideId.toString(),
|
||||
'rideTimeFinish': nowString,
|
||||
'status': 'Finished',
|
||||
'price': totalCost,
|
||||
};
|
||||
final driverOrderPayload = {
|
||||
'order_id': (rideId.toString()),
|
||||
'status': 'Finished'
|
||||
|
||||
final String paymentAuthToken =
|
||||
await generateTokenDriver(paymentAmount.toString());
|
||||
|
||||
final paymentProcessingPayload = {
|
||||
'rideId': rideId.toString(),
|
||||
'driverId': box.read(BoxName.driverID).toString(),
|
||||
'passengerId': passengerId.toString(),
|
||||
'paymentAmount': paymentAmount,
|
||||
'paymentMethod': paymentMethod,
|
||||
'walletChecked': walletChecked.toString(),
|
||||
'passengerWalletBurc': passengerWalletBurc.toString(),
|
||||
'authToken': paymentAuthToken,
|
||||
};
|
||||
|
||||
// List to hold all asynchronous operations
|
||||
List<Future<dynamic>> futures = [];
|
||||
// --- 3. Execute API Calls in Parallel ---
|
||||
try {
|
||||
List<Future<dynamic>> apiCalls = [];
|
||||
|
||||
// API calls that can run in parallel
|
||||
futures.add(CRUD().post(
|
||||
link: "${AppLink.seferCairoServer}/ride/rides/update.php",
|
||||
payload: basePayload,
|
||||
));
|
||||
futures.add(CRUD().post(
|
||||
link: "${AppLink.seferCairoServer}/ride/driver_order/update.php",
|
||||
payload: driverOrderPayload,
|
||||
));
|
||||
apiCalls.add(CRUD().post(
|
||||
link: "${AppLink.seferCairoServer}/ride/rides//finish_ride_updates.php",
|
||||
payload: rideUpdatePayload,
|
||||
));
|
||||
|
||||
// Wallet transactions (can potentially be parallelized if independent)
|
||||
if (walletChecked == 'true') {
|
||||
paymentToken = await generateTokenPassenger(
|
||||
((-1) * double.parse(paymentAmount)).toString());
|
||||
futures
|
||||
.add(CRUD().postWallet(link: AppLink.addPassengersWallet, payload: {
|
||||
'passenger_id': (passengerId),
|
||||
'balance': ((-1) * double.parse(paymentAmount)).toString(),
|
||||
'token': paymentToken,
|
||||
}));
|
||||
apiCalls.add(CRUD().postWallet(
|
||||
link:
|
||||
"${AppLink.seferPaymentServer}/ride/payment/process_ride_payments.php",
|
||||
payload: paymentProcessingPayload,
|
||||
));
|
||||
|
||||
final results = await Future.wait(apiCalls);
|
||||
|
||||
// --- 4. *** CRITICAL STEP: Verify BOTH results were successful *** ---
|
||||
// Assuming CRUD().post returns a Map<String, dynamic> like {'success': true, 'message': '...'}
|
||||
final rideUpdateResult = results[0];
|
||||
final paymentResult = results[1];
|
||||
|
||||
if (rideUpdateResult['status'] == 'success' &&
|
||||
paymentResult['status'] == 'success') {
|
||||
// --- SUCCESS: Both API calls succeeded, now proceed ---
|
||||
|
||||
Get.back(); // Dismiss the loading indicator
|
||||
|
||||
Get.put(DriverBehaviorController())
|
||||
.sendSummaryToServer(driverId, rideId);
|
||||
|
||||
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
|
||||
"Driver Finish Trip".tr,
|
||||
'${'you will pay to Driver'.tr} $paymentAmount \$',
|
||||
tokenPassenger,
|
||||
[
|
||||
box.read(BoxName.driverID),
|
||||
rideId,
|
||||
box.read(BoxName.tokenDriver),
|
||||
paymentAmount.toString()
|
||||
],
|
||||
'ding.wav');
|
||||
|
||||
Get.to(() => RatePassenger(), arguments: {
|
||||
'passengerId': passengerId,
|
||||
'rideId': rideId,
|
||||
'price': paymentAmount.toString(),
|
||||
'walletChecked': walletChecked
|
||||
});
|
||||
} else {
|
||||
// --- FAILURE: One or both API calls failed ---
|
||||
// The transaction on the server side would have been rolled back.
|
||||
// We throw an exception to be caught by the catch block, which will revert the UI state.
|
||||
throw Exception(
|
||||
'One of the server operations failed. Ride Update: ${rideUpdateResult['message']} | Payment: ${paymentResult['message']}');
|
||||
}
|
||||
} catch (e) {
|
||||
// --- CATCH ALL ERRORS (Network, Server Failure, etc.) ---
|
||||
Get.back(); // Dismiss the loading indicator
|
||||
|
||||
Log.print("Error finishing ride: $e");
|
||||
Get.snackbar("Error", "Could not finish the ride. Please try again.");
|
||||
|
||||
// Revert state because the operation failed
|
||||
isRideFinished = false;
|
||||
isRideStarted = true;
|
||||
isPriceWindow = true;
|
||||
box.write(BoxName.rideStatus, 'InProgress'); // Revert status
|
||||
}
|
||||
|
||||
paymentToken = await generateTokenDriver(paymentAmount.toString());
|
||||
futures.add(CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'rideId': (rideId),
|
||||
'amount': paymentAmount,
|
||||
'payment_method':
|
||||
walletChecked == 'true' ? "${paymentMethod}Ride" : paymentMethod,
|
||||
'passengerID': (passengerId),
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
}));
|
||||
|
||||
if (double.parse(passengerWalletBurc) < 0) {
|
||||
final paymentToken1 = await generateTokenPassenger(
|
||||
((-1) * double.parse(passengerWalletBurc)).toString());
|
||||
futures
|
||||
.add(CRUD().postWallet(link: AppLink.addPassengersWallet, payload: {
|
||||
'passenger_id': (passengerId),
|
||||
'token': paymentToken1,
|
||||
'balance': ((-1) * double.parse(passengerWalletBurc)).toString()
|
||||
}));
|
||||
}
|
||||
|
||||
double pointsSubtraction = double.parse(paymentAmount) * (-1) * 0.1;
|
||||
final paymentToken2 =
|
||||
await generateTokenDriver((pointsSubtraction).toStringAsFixed(0));
|
||||
futures
|
||||
.add(CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'paymentID': 'rideId${(rideId)}',
|
||||
'amount': (pointsSubtraction).toStringAsFixed(0),
|
||||
'paymentMethod': paymentMethod,
|
||||
'token': paymentToken2,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
}));
|
||||
|
||||
// Wait for all independent API calls to complete
|
||||
await Future.wait(futures);
|
||||
Get.put(DriverBehaviorController()).sendSummaryToServer(driverId, rideId);
|
||||
|
||||
// Send notification (this likely depends on previous steps)
|
||||
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
|
||||
"Driver Finish Trip".tr,
|
||||
'${'you will pay to Driver'.tr} $paymentAmount \$',
|
||||
tokenPassenger,
|
||||
[
|
||||
box.read(BoxName.driverID),
|
||||
rideId,
|
||||
box.read(BoxName.tokenDriver),
|
||||
paymentAmount.toString()
|
||||
],
|
||||
'ding.wav');
|
||||
|
||||
// Navigate to the next screen (likely depends on previous steps being done)
|
||||
Get.to(() => RatePassenger(), arguments: {
|
||||
'passengerId': passengerId,
|
||||
'rideId': rideId,
|
||||
'price': paymentAmount.toString(),
|
||||
'walletChecked': walletChecked
|
||||
});
|
||||
}
|
||||
// void finishRideFromDriver1() async {
|
||||
// // if (carType != 'Comfort' || carType != 'Free Ride') {
|
||||
|
||||
// isRideFinished = true;
|
||||
// isRideStarted = false;
|
||||
// isPriceWindow = false;
|
||||
// box.write(BoxName.rideStatus, 'Finished');
|
||||
// // Get.find<HomeCaptainController>().changeToAppliedRide('Finished');
|
||||
// // Get.find<HomeCaptainController>().update();
|
||||
// totalCost = price < 20
|
||||
// ? carType != 'Comfort' && carType != 'Mishwar Vip' && carType != 'Lady'
|
||||
// ? '20'
|
||||
// : '30'
|
||||
// : price < double.parse(totalPricePassenger)
|
||||
// ? totalPricePassenger
|
||||
// : carType != 'Comfort' &&
|
||||
// carType != 'Mishwar Vip' &&
|
||||
// carType != 'Lady'
|
||||
// ? totalPricePassenger
|
||||
// : price.toStringAsFixed(2);
|
||||
// paymentAmount = totalCost;
|
||||
// box.write(BoxName.statusDriverLocation, 'off');
|
||||
// // changeRideToBeginToPassenger();
|
||||
// await CRUD().post(
|
||||
// link: "${AppLink.seferCairoServer}/ride/rides/update.php",
|
||||
// payload: {
|
||||
// 'id': rideId,
|
||||
// 'rideTimeFinish': DateTime.now().toString(),
|
||||
// 'status': 'Finished',
|
||||
// 'price': totalCost,
|
||||
// });
|
||||
// CRUD().post(
|
||||
// link: "${AppLink.seferCairoServer}/ride/driver_order/update.php",
|
||||
// payload: {
|
||||
// // 'driver_id': box.read(BoxName.driverID).toString(),
|
||||
// 'order_id': rideId.toString(),
|
||||
// 'status': 'Finished'
|
||||
// });
|
||||
// if (AppLink.endPoint != AppLink.seferCairoServer) {
|
||||
// CRUD().post(
|
||||
// link: "${AppLink.endPoint}/ride/rides/update.php",
|
||||
// payload: {
|
||||
// 'id': rideId,
|
||||
// 'rideTimeFinish': DateTime.now().toString(),
|
||||
// 'status': 'Finished',
|
||||
// 'price': totalCost,
|
||||
// },
|
||||
// );
|
||||
// CRUD().post(
|
||||
// link: "${AppLink.endPoint}/ride/driver_order/update.php",
|
||||
// payload: {
|
||||
// // 'driver_id': box.read(BoxName.driverID).toString(),
|
||||
// 'order_id': rideId.toString(),
|
||||
// 'status': 'Finished'
|
||||
// });
|
||||
// }
|
||||
// if (walletChecked == 'true') {
|
||||
// paymentToken = await generateTokenPassenger(
|
||||
// ((-1) * double.parse(paymentAmount)).toString());
|
||||
// await CRUD().post(link: AppLink.addPassengersWallet, payload: {
|
||||
// 'passenger_id': passengerId,
|
||||
// 'balance': ((-1) * double.parse(paymentAmount)).toString(),
|
||||
// 'token': paymentToken,
|
||||
// });
|
||||
// }
|
||||
// paymentToken = await generateTokenDriver(paymentAmount.toString());
|
||||
// await CRUD().post(link: AppLink.addDrivePayment, payload: {
|
||||
// 'rideId': rideId,
|
||||
// 'amount': paymentAmount,
|
||||
// 'payment_method':
|
||||
// walletChecked == 'true' ? "${paymentMethod}Ride" : paymentMethod,
|
||||
// 'passengerID': passengerId,
|
||||
// 'token': paymentToken,
|
||||
// 'driverID': box.read(BoxName.driverID).toString(),
|
||||
// });
|
||||
// if (double.parse(passengerWalletBurc) < 0) {
|
||||
// // for zero passenger
|
||||
// var paymentToken1 = await generateTokenPassenger(
|
||||
// ((-1) * double.parse(passengerWalletBurc)).toString());
|
||||
// await CRUD().post(link: AppLink.addPassengersWallet, payload: {
|
||||
// 'passenger_id': passengerId,
|
||||
// 'token': paymentToken1,
|
||||
// 'balance': ((-1) * double.parse(passengerWalletBurc)).toString()
|
||||
// });
|
||||
// }
|
||||
|
||||
// double pointsSubtraction = 0;
|
||||
// pointsSubtraction =
|
||||
// double.parse(paymentAmount) * (-1) * .08; //for 300 from 3000
|
||||
// var paymentToken2 =
|
||||
// await generateTokenDriver((pointsSubtraction).toStringAsFixed(0));
|
||||
// var res = await CRUD().post(link: AppLink.addDriversWalletPoints, payload: {
|
||||
// 'paymentID': 'rideId$rideId',
|
||||
// 'amount': (pointsSubtraction).toStringAsFixed(0),
|
||||
// 'paymentMethod': paymentMethod,
|
||||
// 'token': paymentToken2,
|
||||
// 'driverID': box.read(BoxName.driverID).toString(),
|
||||
// });
|
||||
// Future.delayed(const Duration(milliseconds: 300));
|
||||
// Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
|
||||
// "Driver Finish Trip".tr,
|
||||
// '${'you will pay to Driver'.tr} $paymentAmount \$',
|
||||
// tokenPassenger,
|
||||
// [
|
||||
// box.read(BoxName.driverID),
|
||||
// rideId,
|
||||
// box.read(BoxName.tokenDriver),
|
||||
// // carType == 'Comfort' || carType == 'Mishwar Vip'
|
||||
// // ? price.toStringAsFixed(2)
|
||||
// // : totalPassenger
|
||||
// paymentAmount.toString()
|
||||
// ],
|
||||
// 'ding.wav');
|
||||
// Get.to(() => RatePassenger(), arguments: {
|
||||
// 'passengerId': passengerId,
|
||||
// 'rideId': rideId,
|
||||
// 'price': paymentAmount.toString(), //price
|
||||
// 'walletChecked': walletChecked
|
||||
// });
|
||||
// // Get.back();
|
||||
// }
|
||||
|
||||
void cancelCheckRideFromPassenger() async {
|
||||
var res = await CRUD().get(
|
||||
@@ -1426,7 +1310,9 @@ class MapDriverController extends GetxController {
|
||||
if (activeRouteSteps.isNotEmpty) {
|
||||
currentInstruction =
|
||||
_parseInstruction(activeRouteSteps[0]['html_instructions']);
|
||||
Get.find<TextToSpeechController>().speakText(currentInstruction);
|
||||
Get.isRegistered<TextToSpeechController>()
|
||||
? Get.find<TextToSpeechController>().speakText(currentInstruction)
|
||||
: Get.put(TextToSpeechController()).speakText(currentInstruction);
|
||||
}
|
||||
|
||||
// تحديث الكاميرا لتناسب المسار الجديد
|
||||
@@ -1491,7 +1377,9 @@ class MapDriverController extends GetxController {
|
||||
currentStepIndex++;
|
||||
currentInstruction = _parseInstruction(
|
||||
activeRouteSteps[currentStepIndex]['html_instructions']);
|
||||
Get.find<TextToSpeechController>().speakText(currentInstruction);
|
||||
Get.isRegistered<TextToSpeechController>()
|
||||
? Get.find<TextToSpeechController>().speakText(currentInstruction)
|
||||
: Get.put(TextToSpeechController()).speakText(currentInstruction);
|
||||
|
||||
// -->> هنا يتم تحديث لون المسار <<--
|
||||
_updateTraveledPath();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -7,6 +8,7 @@ import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:google_polyline_algorithm/google_polyline_algorithm.dart';
|
||||
import 'package:sefer_driver/constant/colors.dart';
|
||||
import 'package:sefer_driver/env/env.dart';
|
||||
|
||||
// استخدام نفس مسارات الاستيراد التي قدمتها
|
||||
import '../../../constant/api_key.dart';
|
||||
@@ -399,9 +401,11 @@ class NavigationController extends GetxController {
|
||||
}
|
||||
|
||||
Future<void> getRoute(LatLng origin, LatLng destination) async {
|
||||
final String key = Platform.isAndroid ? Env.mapAPIKEY : Env.mapAPIKEYIOS;
|
||||
final url =
|
||||
'${AppLink.googleMapsLink}directions/json?language=ar&destination=${destination.latitude},${destination.longitude}&origin=${origin.latitude},${origin.longitude}&key=${AK.mapAPIKEY}';
|
||||
'${AppLink.googleMapsLink}directions/json?language=ar&destination=${destination.latitude},${destination.longitude}&origin=${origin.latitude},${origin.longitude}&key=${key}&mode=driving';
|
||||
var response = await CRUD().getGoogleApi(link: url, payload: {});
|
||||
Log.print('response: ${response}');
|
||||
|
||||
if (response == null || response['routes'].isEmpty) {
|
||||
Get.snackbar('خطأ', 'لم يتم العثور على مسار.');
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
|
||||
import 'package:sefer_driver/views/home/on_boarding_page.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
|
||||
import 'package:sefer_driver/views/auth/captin/login_captin.dart';
|
||||
import 'package:sefer_driver/views/home/on_boarding_page.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../../views/auth/captin/login_captin.dart';
|
||||
|
||||
// Assuming you have a home page to navigate to after successful login.
|
||||
// If not, you might need to adjust the navigation target.
|
||||
// import 'package:sefer_driver/views/home/home_page.dart';
|
||||
|
||||
class SplashScreenController extends GetxController
|
||||
with GetTickerProviderStateMixin {
|
||||
@@ -20,73 +24,116 @@ class SplashScreenController extends GetxController
|
||||
|
||||
String packageInfo = '';
|
||||
|
||||
Future<void> _getPackageInfo() async {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
packageInfo = info.version;
|
||||
box.write(BoxName.packagInfo, packageInfo);
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_getPackageInfo();
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1500), // Reduced duration
|
||||
)..forward();
|
||||
|
||||
animation =
|
||||
CurvedAnimation(parent: _animationController, curve: Curves.easeOut);
|
||||
|
||||
startTimer();
|
||||
_startProgressTimer();
|
||||
_setupAnimations();
|
||||
_initializeAndNavigate();
|
||||
}
|
||||
|
||||
void _startProgressTimer() {
|
||||
Log.print(
|
||||
'box.read(BoxName.phoneDriver): ${box.read(BoxName.phoneDriver)}');
|
||||
Log.print(
|
||||
'box.read(BoxName.phoneVerified): ${box.read(BoxName.phoneVerified)}');
|
||||
const totalTime = 3000; // 5 seconds in milliseconds
|
||||
const interval = 50; // Update every 50ms
|
||||
void _setupAnimations() {
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1500),
|
||||
);
|
||||
animation =
|
||||
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
|
||||
_animationController.forward();
|
||||
}
|
||||
|
||||
/// This is the core function that initializes the app.
|
||||
/// It runs two tasks simultaneously and navigates only when necessary.
|
||||
Future<void> _initializeAndNavigate() async {
|
||||
// Start getting package info, no need to wait for it.
|
||||
_getPackageInfo();
|
||||
|
||||
const minSplashDurationMs = 4000;
|
||||
_animateProgressBar(minSplashDurationMs);
|
||||
|
||||
// Define the two concurrent tasks
|
||||
final minDuration =
|
||||
Future.delayed(const Duration(milliseconds: minSplashDurationMs));
|
||||
final navigationTargetFuture = _getNavigationTarget();
|
||||
|
||||
// Wait for both tasks to complete
|
||||
await Future.wait([minDuration, navigationTargetFuture]);
|
||||
|
||||
// The future now returns a nullable Widget (Widget?)
|
||||
final Widget? targetPage = await navigationTargetFuture;
|
||||
|
||||
// *** FIX: Only navigate if the targetPage is not null. ***
|
||||
// This prevents navigating again if the login function already handled it.
|
||||
if (targetPage != null) {
|
||||
Get.off(() => targetPage,
|
||||
transition: Transition.fadeIn,
|
||||
duration: const Duration(milliseconds: 500));
|
||||
} else {
|
||||
Log.print(
|
||||
"Navigation was handled internally by the login process. Splash screen will not navigate.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Animates the progress bar over a given duration.
|
||||
void _animateProgressBar(int totalMilliseconds) {
|
||||
const interval = 50;
|
||||
int elapsed = 0;
|
||||
|
||||
_progressTimer?.cancel();
|
||||
_progressTimer =
|
||||
Timer.periodic(const Duration(milliseconds: interval), (timer) async {
|
||||
Timer.periodic(const Duration(milliseconds: interval), (timer) {
|
||||
elapsed += interval;
|
||||
progress.value = (elapsed / totalTime).clamp(0.0, 1.0);
|
||||
|
||||
if (elapsed >= totalTime) {
|
||||
progress.value = (elapsed / totalMilliseconds).clamp(0.0, 1.0);
|
||||
if (elapsed >= totalMilliseconds) {
|
||||
timer.cancel();
|
||||
// Get.off(SyrianCardAI());
|
||||
box.read(BoxName.onBoarding) == null
|
||||
? Get.off(() => OnBoardingPage())
|
||||
: box.read(BoxName.phoneDriver) != null &&
|
||||
box.read(BoxName.phoneVerified).toString() == '1'
|
||||
? await Get.put(LoginDriverController())
|
||||
.loginWithGoogleCredential(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString())
|
||||
: Get.off(() => LoginCaptin());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void startTimer() async {
|
||||
Timer(const Duration(seconds: 5), () async {
|
||||
// box.read(BoxName.onBoarding) == null
|
||||
// ? Get.off(() => OnBoardingPage())
|
||||
// : box.read(BoxName.email) != null &&
|
||||
// box.read(BoxName.phone) != null &&
|
||||
// box.read(BoxName.isVerified) == '1'
|
||||
// // ? Get.off(() => const MapPagePassenger())
|
||||
// ? await Get.put(LoginController()).loginUsingCredentials(
|
||||
// box.read(BoxName.passengerID).toString(),
|
||||
// box.read(BoxName.email).toString(),
|
||||
// )
|
||||
// : Get.off(() => LoginPage());
|
||||
});
|
||||
/// Determines the correct page to navigate to, or returns null if navigation
|
||||
/// is expected to be handled by an internal process (like login).
|
||||
Future<Widget?> _getNavigationTarget() async {
|
||||
try {
|
||||
final onBoardingShown = box.read(BoxName.onBoarding) != null;
|
||||
if (!onBoardingShown) {
|
||||
return OnBoardingPage();
|
||||
}
|
||||
|
||||
final isDriverDataAvailable = box.read(BoxName.phoneDriver) != null;
|
||||
final isPhoneVerified = box.read(BoxName.phoneVerified).toString() == '1';
|
||||
|
||||
if (isDriverDataAvailable && isPhoneVerified) {
|
||||
Log.print('Attempting to log in with stored credentials...');
|
||||
final loginController = Get.put(LoginDriverController());
|
||||
|
||||
// Assume loginWithGoogleCredential handles its own navigation on success.
|
||||
await loginController.loginWithGoogleCredential(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
|
||||
// *** FIX: Return null to signify that navigation has been handled. ***
|
||||
return null;
|
||||
} else {
|
||||
Log.print('No valid driver session found. Navigating to login page.');
|
||||
return LoginCaptin();
|
||||
}
|
||||
} catch (e) {
|
||||
Log.print("Error during navigation logic: $e");
|
||||
// Fallback to the login page in case of any error.
|
||||
return LoginCaptin();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _getPackageInfo() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
packageInfo = info.version;
|
||||
await box.write(BoxName.packagInfo, packageInfo);
|
||||
update(); // To update any UI element that might be listening
|
||||
} catch (e) {
|
||||
Log.print("Could not get package info: $e");
|
||||
packageInfo = '1.0.0'; // Default value
|
||||
await box.write(BoxName.packagInfo, packageInfo);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
Reference in New Issue
Block a user