This commit is contained in:
Hamza-Ayed
2023-10-19 20:19:02 +03:00
parent 805754a599
commit 02bdc83e72
14 changed files with 407 additions and 121 deletions

View File

@@ -0,0 +1,77 @@
import 'dart:convert';
import 'package:flutter/animation.dart';
import 'package:get/get.dart';
import 'package:ride/constant/box_name.dart';
import 'package:ride/constant/links.dart';
import 'package:ride/controller/functions/crud.dart';
import 'package:ride/main.dart';
class DurationController extends GetxController
with GetSingleTickerProviderStateMixin {
final data = <DurationData>[].obs;
late AnimationController animationController;
@override
void onInit() {
super.onInit();
fetchData();
animationController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 500), // Adjust the animation duration as needed
);
animationController.forward(); // Start the animation
}
@override
void onClose() {
animationController.dispose();
super.onClose();
}
Map<String, dynamic> jsonData = {};
bool isLoading = false;
String totalDurationToday = '';
Future<void> fetchData() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getTotalDriverDuration,
payload: {'driver_id': box.read(BoxName.driverID)},
);
jsonData = jsonDecode(res);
final parsedData = parseData(jsonData['message']);
data.value = parsedData;
isLoading = false;
update(); // Notify the observers about the data and loading state change
}
List<DurationData> parseData(List<dynamic> json) {
return json.map((entry) {
final Map<String, dynamic> entryMap = entry;
final day = DateTime.parse(entryMap['day']);
final totalDuration = _parseDuration(entryMap['total_duration']);
return DurationData(day, totalDuration);
}).toList();
}
Duration _parseDuration(String durationString) {
final parts = durationString.split(':');
final hours = int.parse(parts[0]);
final minutes = int.parse(parts[1]);
final seconds = int.parse(parts[2]);
return Duration(hours: hours, minutes: minutes, seconds: seconds);
}
}
class DurationData {
final DateTime day;
final Duration totalDuration;
DurationData(this.day, this.totalDuration);
}

View File

@@ -15,7 +15,9 @@ class HomeCaptainController extends GetxController {
Duration activeDuration = Duration.zero;
Timer? activeTimer;
Map data = {};
String totalToday = '0';
String totalMoneyToday = '0';
String totalDurationToday = '0';
Timer? timer;
// Inject the LocationController class
final locationController = Get.find<LocationController>();
@@ -55,10 +57,22 @@ class HomeCaptainController extends GetxController {
return totalDuration;
}
void startPeriodicExecution() {
Timer.periodic(const Duration(seconds: 30), (timer) async {
await getCaptainDurationOnToday();
});
}
void stopTimer() {
print('Stopping timer');
timer?.cancel();
}
@override
void onInit() async {
addToken();
getPaymentToday();
startPeriodicExecution();
super.onInit();
}
@@ -75,13 +89,24 @@ class HomeCaptainController extends GetxController {
link: AppLink.getDriverpaymentToday,
payload: {'driverID': box.read(BoxName.driverID).toString()});
data = jsonDecode(res);
totalToday = data['message'][0]['total_amount'];
totalMoneyToday = data['message'][0]['total_amount'];
update();
}
Future<void> getCaptainDurationOnToday() async {
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();
}
@override
void dispose() {
activeTimer?.cancel();
stopTimer();
super.dispose();
}
}

View File

@@ -393,51 +393,47 @@ class MapPassengerController extends GetxController {
}
Future getCarsLocationByPassenger() async {
if (rideConfirm == false) {
carsLocationByPassenger = [];
LatLngBounds bounds =
calculateBounds(myLocation.latitude, myLocation.longitude, 8000);
print(
'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
print(
'Northeast: ${bounds.northeast.latitude}, ${bounds.northeast.longitude}');
// if (rideConfirm == false) {
carsLocationByPassenger = [];
LatLngBounds bounds =
calculateBounds(myLocation.latitude, myLocation.longitude, 8000);
print(
'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
print(
'Northeast: ${bounds.northeast.latitude}, ${bounds.northeast.longitude}');
var res =
await CRUD().get(link: AppLink.getCarsLocationByPassenger, payload: {
'southwestLat': southwest.latitude.toString(),
'southwestLon': southwest.longitude.toString(),
'northeastLat': northeast.latitude.toString(),
'northeastLon': northeast.longitude.toString(),
});
if (res == 'failure') {
Get.defaultDialog(
title: 'No Car in your site.Sorry!',
middleText: '',
confirm: MyElevatedButton(
title: 'Back',
onPressed: () {
Get.back();
markerReloadingTimer.cancel();
}));
} else {
dataCarsLocationByPassenger = jsonDecode(res);
// print(dataCarsLocationByPassenger);
driverId = dataCarsLocationByPassenger['message'][carsOrder]
['driver_id']
.toString();
// print('driverId==============$driverId');
for (var i = 0;
i < dataCarsLocationByPassenger['message'].length;
i++) {
carsLocationByPassenger.add(LatLng(
double.parse(
dataCarsLocationByPassenger['message'][i]['latitude']),
double.parse(
dataCarsLocationByPassenger['message'][i]['longitude'])));
}
update();
var res =
await CRUD().get(link: AppLink.getCarsLocationByPassenger, payload: {
'southwestLat': southwest.latitude.toString(),
'southwestLon': southwest.longitude.toString(),
'northeastLat': northeast.latitude.toString(),
'northeastLon': northeast.longitude.toString(),
});
if (res == 'failure') {
Get.defaultDialog(
title: 'No Car in your site.Sorry!',
middleText: '',
confirm: MyElevatedButton(
title: 'Back',
onPressed: () {
Get.back();
markerReloadingTimer.cancel();
}));
} else {
dataCarsLocationByPassenger = jsonDecode(res);
// print(dataCarsLocationByPassenger);
driverId = dataCarsLocationByPassenger['message'][carsOrder]['driver_id']
.toString();
// print('driverId==============$driverId');
for (var i = 0; i < dataCarsLocationByPassenger['message'].length; i++) {
carsLocationByPassenger.add(LatLng(
double.parse(dataCarsLocationByPassenger['message'][i]['latitude']),
double.parse(
dataCarsLocationByPassenger['message'][i]['longitude'])));
}
update();
// }
}
}
@@ -771,67 +767,72 @@ class MapPassengerController extends GetxController {
void getNearestDriverByPassengerLocation() async {
if (polyLines.isEmpty || data.isEmpty) {
double nearestDistance = double.infinity;
for (var i = 0; i < dataCarsLocationByPassenger['message'].length; i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
if (rideConfirm == false) {
double nearestDistance = double.infinity;
for (var i = 0;
i < dataCarsLocationByPassenger['message'].length;
i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
// double distance1 = Geolocator.distanceBetween(
// mylocation.latitude,
// mylocation.longitude,
// double.parse(carLocation['latitude']),
// double.parse(carLocation['longitude']),
// );
// if (distance1 < nearestDistance) {
// nearestDistance = distance1;
// // nearestCarLocation = carLocation;
// nearestCar = CarLocation(
// distance: distance1,
// id: carLocation['driver_id'],
// latitude: double.parse(carLocation['latitude']),
// longitude: double.parse(carLocation['longitude']),
// );
// }
// isloading = true;
update();
// Make API request to get exact distance and duration
String apiUrl =
'${AppLink.googleMapsLink}distancematrix/json?destinations=${carLocation['latitude']},${carLocation['longitude']}&origins=${myLocation.latitude},${myLocation.longitude}&units=metric&key=${AppCredintials.mapAPIKEY}';
var response = await CRUD().getGoogleApi(link: apiUrl, payload: {});
if (response['status'] == "OK") {
var data = response;
// Extract distance and duration from the response and handle accordingly
int distance1 = data['rows'][0]['elements'][0]['distance']['value'];
distanceByPassenger =
data['rows'][0]['elements'][0]['distance']['text'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
durationFromDriverToPassenger = Duration(seconds: duration1.toInt());
newTime1 = currentTime.add(durationFromDriverToPassenger);
timeFromDriverToPassenger =
newTime1.add(Duration(minutes: 2.toInt()));
durationByPassenger =
data['rows'][0]['elements'][0]['duration']['text'];
// double distance1 = Geolocator.distanceBetween(
// mylocation.latitude,
// mylocation.longitude,
// double.parse(carLocation['latitude']),
// double.parse(carLocation['longitude']),
// );
// if (distance1 < nearestDistance) {
// nearestDistance = distance1;
// // nearestCarLocation = carLocation;
// nearestCar = CarLocation(
// distance: distance1,
// id: carLocation['driver_id'],
// latitude: double.parse(carLocation['latitude']),
// longitude: double.parse(carLocation['longitude']),
// );
// }
// isloading = true;
update();
if (distance1 < nearestDistance) {
nearestDistance = distance1.toDouble();
// Make API request to get exact distance and duration
String apiUrl =
'${AppLink.googleMapsLink}distancematrix/json?destinations=${carLocation['latitude']},${carLocation['longitude']}&origins=${myLocation.latitude},${myLocation.longitude}&units=metric&key=${AppCredintials.mapAPIKEY}';
var response = await CRUD().getGoogleApi(link: apiUrl, payload: {});
if (response['status'] == "OK") {
var data = response;
// Extract distance and duration from the response and handle accordingly
int distance1 = data['rows'][0]['elements'][0]['distance']['value'];
distanceByPassenger =
data['rows'][0]['elements'][0]['distance']['text'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
// isloading = false;
durationFromDriverToPassenger =
Duration(seconds: duration1.toInt());
newTime1 = currentTime.add(durationFromDriverToPassenger);
timeFromDriverToPassenger =
newTime1.add(Duration(minutes: 2.toInt()));
durationByPassenger =
data['rows'][0]['elements'][0]['duration']['text'];
update();
}
}
if (distance1 < nearestDistance) {
nearestDistance = distance1.toDouble();
// Handle the distance and duration as needed
else {
print(
'Failed to retrieve distance and duration: ${response['status']}');
// Handle the failure case
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
// isloading = false;
update();
}
}
// Handle the distance and duration as needed
else {
print(
'Failed to retrieve distance and duration: ${response['status']}');
// Handle the failure case
}
}
}
}