2026-04-05-maplibra succsess for all and add navigation paage

This commit is contained in:
Hamza-Ayed
2026-04-05 02:50:22 +03:00
parent 8d5fefc9e3
commit 4d5800ff9b
11 changed files with 3512 additions and 1306 deletions

View File

@@ -1,5 +1,8 @@
import 'dart:math';
import 'package:Intaleq/views/widgets/elevated_btn.dart';
import 'package:Intaleq/views/widgets/error_snakbar.dart';
import 'package:Intaleq/views/widgets/mycircular.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
@@ -8,10 +11,9 @@ import 'dart:ui'; // مهم لإضافة تأثير الضبابية
import '../../../constant/colors.dart';
import '../../../controller/functions/tts.dart';
import '../../../controller/home/ios_live_activity_service.dart';
import '../../../controller/home/map_passenger_controller.dart';
import '../../../controller/home/vip_waitting_page.dart';
import '../../../print.dart';
import '../navigation/navigation_view.dart';
// --- الدالة الرئيسية بالتصميم الجديد ---
GetBuilder<MapPassengerController> leftMainMenuIcons() {
@@ -44,7 +46,7 @@ GetBuilder<MapPassengerController> leftMainMenuIcons() {
_buildMapActionButton(
icon: Icons.satellite_alt_outlined,
tooltip: 'Toggle Map Type',
onPressed: () => controller.changeMapType(),
onPressed: () => Get.to(() => NavigationView()),
),
// _buildVerticalDivider(),
// _buildMapActionButton(
@@ -131,78 +133,17 @@ class TestPage extends StatelessWidget {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// زر البدء
ElevatedButton(
onPressed: () async {
print("🍎 محاولة تشغيل Live Activity (Start)...");
try {
await IosLiveActivityService.startRideActivity(
rideId: "123",
driverName: "تجربة مبدئية",
carDetails: "تويوتا • أسود",
etaText: "5 دقائق",
progress: 0.2,
);
Log.print(
"✅ تم تشغيل Live Activity بنجاح! أغلق الشاشة لترى النتيجة.");
} catch (e) {
Log.print("❌ خطأ في Start Live Activity: $e");
}
},
child: const Text('Start Activity'),
MyCircularProgressIndicator(),
MyElevatedButton(
title: 'title',
onPressed: () {},
),
const SizedBox(height: 16),
// زر التحديث العشوائي
ElevatedButton(
onPressed: () async {
Log.print("🔄 محاولة تحديث Live Activity (Update)...");
// توليد بيانات عشوائية للاختبار
final statuses = ['waiting', 'ongoing'];
final status = statuses[random.nextInt(statuses.length)];
final int minutes = random.nextInt(15) + 1; // 115
final String eta = "$minutes دقائق";
final double progress = (random.nextDouble() * 0.9) + 0.05;
// بين 0.05 و 0.95 تقريبًا
try {
await IosLiveActivityService.updateRideActivity(
status: status,
driverName:
status == 'waiting' ? 'السائق في الطريق' : 'السائق معك',
carDetails: "تويوتا • أسود",
etaText: eta,
progress: progress,
);
Log.print(
"✅ تم تحديث Live Activity: status=$status, eta=$eta, progress=$progress");
} catch (e) {
Log.print("❌ خطأ في Update Live Activity: $e");
}
},
child: const Text('Update (Random)'),
),
const SizedBox(height: 16),
// زر الإنهاء
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () async {
Log.print("🛑 محاولة إنهاء Live Activity (End)...");
try {
await IosLiveActivityService.endRideActivity();
Log.print("✅ تم إنهاء Live Activity.");
} catch (e) {
Log.print("❌ خطأ في End Live Activity: $e");
}
},
onPressed: () async {},
child: const Text('End Activity'),
),
],

View File

@@ -0,0 +1,632 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:Intaleq/views/widgets/error_snakbar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:maplibre_gl/maplibre_gl.dart'; // Replaced Google Maps
import 'package:http/http.dart' as http;
import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../constant/country_polygons.dart';
import '../../../constant/links.dart';
import '../../../controller/functions/crud.dart';
import '../../../controller/functions/tts.dart';
import '../../../controller/home/decode_polyline_isolate.dart';
import '../../../env/env.dart';
import '../../../main.dart';
import '../../../print.dart';
class NavigationController extends GetxController {
bool isLoading = false;
MaplibreMapController? mapController;
bool isStyleLoaded = false;
final TextEditingController placeDestinationController =
TextEditingController();
LatLng? myLocation;
double heading = 0.0;
// MapLibre Object Tracking
Symbol? carSymbol;
Symbol? destinationSymbol;
Line? remainingRouteLine;
Line? traveledRouteLine;
Timer? _locationUpdateTimer;
final Duration _currentUpdateInterval = const Duration(seconds: 1);
LatLng? _lastRecordedLocation;
List<dynamic> placesDestination = [];
Timer? _debounce;
LatLng? _finalDestination;
List<Map<String, dynamic>> routeSteps = [];
List<LatLng> _fullRouteCoordinates = [];
int _lastTraveledIndexInFullRoute = 0;
bool _nextInstructionSpoken = false;
String currentInstruction = "";
String nextInstruction = "";
int currentStepIndex = 0;
double currentSpeed = 0.0;
String distanceToNextStep = "";
static final String _routeApiBaseUrl =
"${AppLink.routesOsm}/route/v1/driving";
@override
void onInit() {
super.onInit();
_initialize();
}
Future<void> _initialize() async {
await _getCurrentLocationAndStartUpdates();
if (!Get.isRegistered<TextToSpeechController>()) {
Get.put(TextToSpeechController());
}
}
@override
void onClose() {
_locationUpdateTimer?.cancel();
mapController?.dispose();
_debounce?.cancel();
placeDestinationController.dispose();
super.onClose();
}
// =======================================================================
// Map Initialization & Callbacks
// =======================================================================
void onMapCreated(MaplibreMapController controller) {
mapController = controller;
}
Future<void> onStyleLoaded() async {
isStyleLoaded = true;
await _loadCustomIcons();
if (myLocation != null) {
animateCameraToPosition(myLocation!);
_updateCarMarker();
}
if (_fullRouteCoordinates.isNotEmpty) {
_updatePolylinesSets([], _fullRouteCoordinates);
}
}
Future<void> onMapLongPressed(Point<double> point, LatLng tappedPoint) async {
Get.dialog(
AlertDialog(
title: const Text('بدء الملاحة؟'),
content: const Text('هل تريد الذهاب إلى هذا الموقع المحدد؟'),
actionsAlignment: MainAxisAlignment.spaceBetween,
actions: [
TextButton(
child: const Text('إلغاء', style: TextStyle(color: Colors.grey)),
onPressed: () => Get.back(),
),
TextButton(
child: const Text('اذهب الآن'),
onPressed: () {
Get.back();
startNavigationTo(tappedPoint, infoWindowTitle: 'الموقع المحدد');
},
),
],
),
);
}
// =======================================================================
// Location Management
// =======================================================================
Future<void> _getCurrentLocationAndStartUpdates() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
myLocation = LatLng(position.latitude, position.longitude);
update();
if (isStyleLoaded) animateCameraToPosition(myLocation!);
_startLocationTimer();
} catch (e) {
Log.print("Error getting initial location: $e");
}
}
void _startLocationTimer() {
_locationUpdateTimer?.cancel();
_locationUpdateTimer = Timer.periodic(_currentUpdateInterval, (timer) {
_updateLocationAndProcess();
});
}
Future<void> _updateLocationAndProcess() async {
try {
final position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
final newLoc = LatLng(position.latitude, position.longitude);
if (_lastRecordedLocation != null) {
double dist = Geolocator.distanceBetween(
newLoc.latitude,
newLoc.longitude,
_lastRecordedLocation!.latitude,
_lastRecordedLocation!.longitude);
if (dist < 2.0) return;
}
myLocation = newLoc;
_lastRecordedLocation = newLoc;
heading = position.heading;
currentSpeed = position.speed * 3.6;
if (isStyleLoaded) _updateCarMarker();
if (_fullRouteCoordinates.isNotEmpty) {
animateCameraToPosition(myLocation!, bearing: heading, zoom: 18.0);
_updateTraveledPolylineSmart(myLocation!);
_checkNavigationStep(myLocation!);
}
update();
} catch (e) {
// Log.print("Loc update error: $e");
}
}
Future<void> _updateCarMarker() async {
if (myLocation == null || mapController == null || !isStyleLoaded) return;
if (carSymbol == null) {
carSymbol = await mapController!.addSymbol(SymbolOptions(
geometry: myLocation,
iconImage: 'car_icon',
iconSize: 1.0,
iconRotate: heading,
));
} else {
mapController!.updateSymbol(
carSymbol!,
SymbolOptions(
geometry: myLocation,
iconRotate: heading,
));
}
}
void animateCameraToPosition(LatLng position,
{double zoom = 17.0, double bearing = 0.0}) {
mapController?.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: position, zoom: zoom, bearing: bearing, tilt: 45.0),
),
);
}
// =======================================================================
// Route Management
// =======================================================================
void _updateTraveledPolylineSmart(LatLng currentPos) {
if (_fullRouteCoordinates.isEmpty) return;
int searchWindow = 60;
int startIndex = _lastTraveledIndexInFullRoute;
int endIndex = min(startIndex + searchWindow, _fullRouteCoordinates.length);
double minDistance = double.infinity;
int closestIndex = startIndex;
bool foundCloser = false;
for (int i = startIndex; i < endIndex; i++) {
final point = _fullRouteCoordinates[i];
final dist = Geolocator.distanceBetween(currentPos.latitude,
currentPos.longitude, point.latitude, point.longitude);
if (dist < minDistance) {
minDistance = dist;
closestIndex = i;
foundCloser = true;
}
}
if (foundCloser &&
minDistance < 50 &&
closestIndex > _lastTraveledIndexInFullRoute) {
_lastTraveledIndexInFullRoute = closestIndex;
final remaining =
_fullRouteCoordinates.sublist(_lastTraveledIndexInFullRoute);
final traveled =
_fullRouteCoordinates.sublist(0, _lastTraveledIndexInFullRoute + 1);
_updatePolylinesSets(traveled, remaining);
}
}
Future<void> _updatePolylinesSets(
List<LatLng> traveled, List<LatLng> remaining) async {
if (mapController == null || !isStyleLoaded) return;
if (remainingRouteLine != null)
await mapController!.removeLine(remainingRouteLine!);
if (traveledRouteLine != null)
await mapController!.removeLine(traveledRouteLine!);
if (remaining.isNotEmpty) {
remainingRouteLine = await mapController!.addLine(LineOptions(
geometry: remaining,
lineColor: '#0D47A1',
lineWidth: 6.0,
lineJoin: 'round',
));
}
if (traveled.isNotEmpty) {
traveledRouteLine = await mapController!.addLine(LineOptions(
geometry: traveled,
lineColor: '#BDBDBD',
lineWidth: 6.0,
lineJoin: 'round',
));
}
}
// =======================================================================
// Routing API & Navigation
// =======================================================================
Future<void> getRoute(LatLng origin, LatLng destination) async {
String coords =
"${origin.longitude},${origin.latitude};${destination.longitude},${destination.latitude}";
String url =
"$_routeApiBaseUrl/$coords?steps=true&overview=full&geometries=polyline";
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode != 200) {
mySnackbarWarning('تعذر الاتصال بخدمة التوجيه.');
return;
}
final responseData = jsonDecode(response.body);
if (responseData['code'] != 'Ok' ||
(responseData['routes'] as List).isEmpty) {
mySnackbarWarning('لم يتم العثور على مسار.');
return;
}
var route = responseData['routes'][0];
final pointsString = route['geometry'];
// فك تشفير Polyline بطريقة آمنة نوعياً (Type-Safe)
_fullRouteCoordinates = await compute<String, List<LatLng>>(
decodePolylineIsolate, pointsString.toString());
_lastTraveledIndexInFullRoute = 0;
if (isStyleLoaded) _updatePolylinesSets([], _fullRouteCoordinates);
var legs = route['legs'] as List;
if (legs.isNotEmpty) {
var steps = legs[0]['steps'] as List;
routeSteps = List<Map<String, dynamic>>.from(steps);
} else {
routeSteps = [];
}
for (var step in routeSteps) {
step['instruction_text'] = _createInstructionFromManeuver(step);
}
currentStepIndex = 0;
_nextInstructionSpoken = false;
if (routeSteps.isNotEmpty) {
currentInstruction = routeSteps[0]['instruction_text'];
nextInstruction = routeSteps.length > 1
? "ثم ${routeSteps[1]['instruction_text']}"
: "الوجهة النهائية";
Get.find<TextToSpeechController>().speakText(currentInstruction);
}
if (_fullRouteCoordinates.isNotEmpty) {
final bounds = _boundsFromLatLngList(_fullRouteCoordinates);
mapController?.animateCamera(CameraUpdate.newLatLngBounds(bounds,
bottom: 200, top: 150, left: 50, right: 50));
}
update();
} catch (e) {
Log.print("GetRoute Error: $e");
Get.snackbar('خطأ', 'حدث خطأ غير متوقع.');
}
}
// --- Map Object Handlers ---
Future<void> startNavigationTo(LatLng destination,
{String infoWindowTitle = ''}) async {
isLoading = true;
update();
try {
_finalDestination = destination;
await clearRoute(isNewRoute: true);
if (isStyleLoaded && mapController != null) {
destinationSymbol = await mapController!.addSymbol(SymbolOptions(
geometry: destination,
iconImage: 'dest_icon',
iconSize: 1.0,
textField: infoWindowTitle,
textOffset: const Offset(0, 2),
));
}
if (myLocation != null) await getRoute(myLocation!, destination);
} finally {
isLoading = false;
update();
}
}
Future<void> recalculateRoute() async {
if (myLocation == null || _finalDestination == null || isLoading) return;
isLoading = true;
update();
Get.snackbar('إعادة التوجيه', 'جاري حساب مسار جديد...',
backgroundColor: AppColor.goldenBronze);
await getRoute(myLocation!, _finalDestination!);
isLoading = false;
update();
}
Future<void> clearRoute({bool isNewRoute = false}) async {
if (!isNewRoute) {
if (destinationSymbol != null && mapController != null) {
await mapController!.removeSymbol(destinationSymbol!);
destinationSymbol = null;
}
if (remainingRouteLine != null && mapController != null) {
await mapController!.removeLine(remainingRouteLine!);
remainingRouteLine = null;
}
if (traveledRouteLine != null && mapController != null) {
await mapController!.removeLine(traveledRouteLine!);
traveledRouteLine = null;
}
_finalDestination = null;
}
routeSteps.clear();
_fullRouteCoordinates.clear();
_lastTraveledIndexInFullRoute = 0;
currentInstruction = "";
nextInstruction = "";
distanceToNextStep = "";
update();
}
Future<void> _loadCustomIcons() async {
if (mapController == null) return;
final ByteData carBytes = await rootBundle.load('assets/images/car.png');
final Uint8List carList = carBytes.buffer.asUint8List();
await mapController!.addImage('car_icon', carList);
final ByteData destBytes = await rootBundle.load('assets/images/b.png');
final Uint8List destList = destBytes.buffer.asUint8List();
await mapController!.addImage('dest_icon', destList);
}
// --- Step Tracking & Instructions (Omitted unchanged logic to save space, retain your existing string matchers) ---
void _checkNavigationStep(LatLng currentPosition) {
if (routeSteps.isEmpty || currentStepIndex >= routeSteps.length) return;
final step = routeSteps[currentStepIndex];
final maneuver = step['maneuver'];
final List<dynamic> location = maneuver['location'];
final endLatLng = LatLng(location[1], location[0]);
final distance = Geolocator.distanceBetween(
currentPosition.latitude,
currentPosition.longitude,
endLatLng.latitude,
endLatLng.longitude,
);
distanceToNextStep = distance > 1000
? "${(distance / 1000).toStringAsFixed(1)} كم"
: "${distance.toStringAsFixed(0)} متر";
if (distance < 50 &&
!_nextInstructionSpoken &&
nextInstruction.isNotEmpty) {
Get.find<TextToSpeechController>().speakText(nextInstruction);
_nextInstructionSpoken = true;
}
if (distance < 20) _advanceStep();
}
void _advanceStep() {
currentStepIndex++;
if (currentStepIndex < routeSteps.length) {
currentInstruction = routeSteps[currentStepIndex]['instruction_text'];
nextInstruction = (currentStepIndex + 1) < routeSteps.length
? "ثم ${routeSteps[currentStepIndex + 1]['instruction_text']}"
: "ستصل إلى وجهتك";
_nextInstructionSpoken = false;
update();
} else {
_finishNavigation();
}
}
void _finishNavigation() {
currentInstruction = "لقد وصلت إلى وجهتك";
nextInstruction = "";
distanceToNextStep = "";
Get.find<TextToSpeechController>().speakText(currentInstruction);
update();
}
String _createInstructionFromManeuver(Map<String, dynamic> step) {
if (step['maneuver'] == null) return "تابع المسير";
final maneuver = step['maneuver'];
final type = maneuver['type'] ?? 'continue';
final modifier = maneuver['modifier'] ?? 'straight';
final name = step['name'] ?? '';
String instruction = "";
switch (type) {
case 'depart':
instruction = "انطلق";
break;
case 'arrive':
return "لقد وصلت إلى وجهتك، $name";
case 'turn':
case 'fork':
case 'roundabout':
case 'merge':
case 'on ramp':
case 'off ramp':
case 'end of road':
instruction = _getTurnInstruction(modifier);
break;
case 'new name':
instruction = "تابع المسير";
break;
default:
instruction = "تابع المسير";
}
if (name.isNotEmpty)
instruction += (type == 'new name' || type == 'continue')
? " على $name"
: " نحو $name";
return instruction;
}
String _getTurnInstruction(String modifier) {
switch (modifier) {
case 'uturn':
return "قم بالاستدارة والعودة";
case 'sharp right':
return "انعطف يميناً بحدة";
case 'right':
return "انعطف يميناً";
case 'slight right':
return "انعطف يميناً قليلاً";
case 'straight':
return "استمر للأمام";
case 'slight left':
return "انعطف يساراً قليلاً";
case 'left':
return "انعطف يساراً";
case 'sharp left':
return "انعطف يساراً بحدة";
default:
return "اتجه";
}
}
// --- Search & Utils (Retained entirely, no map logic here) ---
Future<void> getPlaces() async {
final q = placeDestinationController.text.trim();
if (q.length < 3) {
placesDestination = [];
update();
return;
}
if (myLocation == null) return;
final lat = myLocation!.latitude;
final lng = myLocation!.longitude;
const radiusKm = 200.0;
final payload = {
'query': q,
'lat_min': (lat - _kmToLatDelta(radiusKm)).toString(),
'lat_max': (lat + _kmToLatDelta(radiusKm)).toString(),
'lng_min': (lng - _kmToLngDelta(radiusKm, lat)).toString(),
'lng_max': (lng + _kmToLngDelta(radiusKm, lat)).toString(),
};
try {
final response =
await CRUD().post(link: AppLink.getPlacesSyria, payload: payload);
List list;
if (response is Map && response['status'] == 'success')
list = List.from(response['message'] as List);
else if (response is List)
list = List.from(response);
else
return;
for (final p in list) {
final plat = double.tryParse(p['latitude']?.toString() ?? '0.0') ?? 0.0;
final plng =
double.tryParse(p['longitude']?.toString() ?? '0.0') ?? 0.0;
p['distanceKm'] = _haversineKm(lat, lng, plat, plng);
}
list.sort((a, b) =>
(a['distanceKm'] as double).compareTo(b['distanceKm'] as double));
placesDestination = list;
update();
} catch (e) {
print('Exception in getPlaces: $e');
}
}
Future<void> selectDestination(dynamic place) async {
placeDestinationController.clear();
placesDestination = [];
final double lat = double.parse(place['latitude'].toString());
final double lng = double.parse(place['longitude'].toString());
await startNavigationTo(LatLng(lat, lng),
infoWindowTitle: place['name'] ?? 'وجهة');
}
void onSearchChanged(String query) {
if (_debounce?.isActive ?? false) _debounce!.cancel();
_debounce = Timer(const Duration(milliseconds: 700), () => getPlaces());
}
double _haversineKm(double lat1, double lon1, double lat2, double lon2) {
const R = 6371.0;
final dLat = (lat2 - lat1) * (pi / 180.0);
final dLon = (lon2 - lon1) * (pi / 180.0);
final a = sin(dLat / 2) * sin(dLat / 2) +
cos(lat1 * pi / 180) *
cos(lat2 * pi / 180) *
sin(dLon / 2) *
sin(dLon / 2);
return R * 2 * atan2(sqrt(a), sqrt(1 - a));
}
double _kmToLatDelta(double km) => km / 111.32;
double _kmToLngDelta(double km, double lat) =>
km / (111.32 * cos(lat * pi / 180));
LatLngBounds _boundsFromLatLngList(List<LatLng> list) {
double? x0, x1, y0, y1;
for (LatLng latLng in list) {
if (x0 == null) {
x0 = x1 = latLng.latitude;
y0 = y1 = latLng.longitude;
} else {
if (latLng.latitude > x1!) x1 = latLng.latitude;
if (latLng.latitude < x0) x0 = latLng.latitude;
if (latLng.longitude > y1!) y1 = latLng.longitude;
if (latLng.longitude < y0!) y0 = latLng.longitude;
}
}
return LatLngBounds(
northeast: LatLng(x1!, y1!), southwest: LatLng(x0!, y0!));
}
}

View File

@@ -0,0 +1,368 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:maplibre_gl/maplibre_gl.dart'; // Replaced Google Maps
import 'dart:ui';
import 'navigation_controller.dart';
const Color kPrimaryColor = Color(0xFF0D47A1);
class NavigationView extends StatelessWidget {
const NavigationView({super.key});
@override
Widget build(BuildContext context) {
final NavigationController controller = Get.put(NavigationController());
return Scaffold(
body: GetBuilder<NavigationController>(
builder: (_) => Stack(
children: [
// --- الخريطة ---
MapLibreMap(
onMapCreated: controller.onMapCreated,
onStyleLoadedCallback: controller.onStyleLoaded,
onMapLongClick: controller.onMapLongPressed,
styleString: "assets/style.json",
initialCameraPosition: CameraPosition(
target: controller.myLocation ?? const LatLng(33.5138, 36.2765),
zoom: 16.0,
),
myLocationEnabled: false,
compassEnabled: false,
),
// --- واجهة البحث (تصميم زجاجي) ---
_buildGlassSearchUI(controller),
// --- إرشادات الملاحة (تصميم عائم) ---
if (controller.currentInstruction.isNotEmpty)
_buildFloatingNavigationUI(controller),
// --- أزرار التحكم (تصميم عائم) ---
_buildFloatingMapControls(controller),
// --- مؤشر التحميل ---
if (controller.isLoading)
Container(
color: Colors.black.withOpacity(0.5),
child: const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
strokeWidth: 3,
),
),
),
],
),
),
);
}
// --- All UI Sub-Widgets remain identical, simply change the 'if' checks to rely on the new variables ---
Widget _buildGlassSearchUI(NavigationController controller) {
return Positioned(
top: 0,
left: 0,
right: 0,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(28.0),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: Container(
height: 56,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.85),
borderRadius: BorderRadius.circular(28.0),
border: Border.all(color: Colors.white.withOpacity(0.4)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 15,
offset: const Offset(0, 5)),
],
),
child: Row(
children: [
const Padding(
padding: EdgeInsets.only(left: 18.0, right: 10.0),
child: Icon(Icons.search,
color: kPrimaryColor, size: 24),
),
Expanded(
child: TextField(
controller: controller.placeDestinationController,
onChanged: controller.onSearchChanged,
textInputAction: TextInputAction.search,
style: const TextStyle(
fontSize: 16, color: Colors.black87),
decoration: const InputDecoration(
hintText: 'إلى أين تريد الذهاب؟',
hintStyle: TextStyle(
color: Colors.black45, fontSize: 16),
border: InputBorder.none,
contentPadding: EdgeInsets.only(bottom: 2),
),
),
),
if (controller
.placeDestinationController.text.isNotEmpty)
_buildClearButton(controller)
else if (controller.destinationSymbol !=
null) // Changed condition here
_buildCancelRouteButton(controller),
],
),
),
),
),
const SizedBox(height: 10),
if (controller.placesDestination.isNotEmpty)
_buildSearchResultsList(controller),
],
),
),
),
);
}
Widget _buildClearButton(NavigationController controller) {
return IconButton(
icon: const Icon(Icons.clear, color: Colors.grey, size: 22),
onPressed: () {
controller.placeDestinationController.clear();
controller.placesDestination = [];
controller.update();
},
);
}
Widget _buildCancelRouteButton(NavigationController controller) {
return IconButton(
tooltip: 'إلغاء المسار',
icon: const Icon(Icons.close, color: Colors.redAccent, size: 22),
onPressed: () => controller.clearRoute(),
);
}
Widget _buildSearchResultsList(NavigationController controller) {
return ClipRRect(
borderRadius: BorderRadius.circular(24.0),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: Container(
constraints: const BoxConstraints(maxHeight: 220),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.85),
borderRadius: BorderRadius.circular(24.0),
border: Border.all(color: Colors.white.withOpacity(0.4)),
),
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8.0),
itemCount: controller.placesDestination.length,
itemBuilder: (context, index) {
final place = controller.placesDestination[index];
final distance = place['distanceKm'] as double?;
final address = (place['address'] ?? '').toString();
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => controller.selectDestination(place),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 12.0),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: kPrimaryColor.withOpacity(0.1),
shape: BoxShape.circle),
child: const Icon(Icons.location_on_outlined,
color: kPrimaryColor, size: 20),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(place['name'] ?? 'اسم غير معروف',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
color: Colors.black87),
maxLines: 1,
overflow: TextOverflow.ellipsis),
if (address.isNotEmpty)
Text(address,
style: const TextStyle(
color: Colors.black54, fontSize: 13),
maxLines: 1,
overflow: TextOverflow.ellipsis),
],
),
),
const SizedBox(width: 10),
if (distance != null)
Text('${distance.toStringAsFixed(1)} كم',
style: const TextStyle(
color: kPrimaryColor,
fontWeight: FontWeight.w500,
fontSize: 13)),
],
),
),
),
);
},
),
),
),
);
}
Widget _buildFloatingMapControls(NavigationController controller) {
return Positioned(
bottom: controller.currentInstruction.isNotEmpty ? 190 : 24,
right: 16,
child: Column(
children: [
if (controller.destinationSymbol != null) ...[
// Changed condition
FloatingActionButton(
heroTag: 'rerouteBtn',
backgroundColor: Colors.white,
elevation: 6,
onPressed: () => controller.recalculateRoute(),
tooltip: 'إعادة حساب المسار',
child: const Icon(Icons.sync_alt, color: kPrimaryColor, size: 24),
),
const SizedBox(height: 12),
],
FloatingActionButton(
heroTag: 'gpsBtn',
backgroundColor: Colors.white,
elevation: 6,
onPressed: () {
if (controller.myLocation != null) {
controller.animateCameraToPosition(controller.myLocation!,
bearing: controller.heading, zoom: 18.5);
}
},
child: const Icon(Icons.gps_fixed, color: Colors.black54, size: 24),
),
],
),
);
}
Widget _buildFloatingNavigationUI(NavigationController controller) {
return Positioned(
bottom: 16,
left: 16,
right: 16,
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF1E88E5), Color(0xFF0D47A1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
borderRadius: BorderRadius.circular(28),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 25,
offset: const Offset(0, 10))
],
),
child: Padding(
padding: const EdgeInsets.fromLTRB(22, 20, 22, 22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
shape: BoxShape.circle),
child: const Icon(Icons.navigation_rounded,
color: Colors.white, size: 28),
),
const SizedBox(width: 16),
Expanded(
child: Text(
controller.currentInstruction,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
height: 1.3),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 16),
Text(controller.distanceToNextStep,
style: const TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold)),
],
),
if (controller.nextInstruction.isNotEmpty ||
controller.currentSpeed > 0)
const Padding(
padding: EdgeInsets.symmetric(vertical: 14.0),
child: Divider(color: Colors.white30, height: 1),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: controller.nextInstruction.isNotEmpty
? Text(
'التالي: ${controller.nextInstruction}',
style: const TextStyle(
color: Colors.white70,
fontSize: 15,
fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
)
: const SizedBox(),
),
Row(
children: [
Text(controller.currentSpeed.toStringAsFixed(0),
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold)),
const SizedBox(width: 6),
const Text('كم/س',
style: TextStyle(
color: Colors.white70,
fontSize: 14,
fontWeight: FontWeight.w500)),
],
),
],
),
],
),
),
),
);
}
}

View File

@@ -1,21 +1,26 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart';
import 'package:Intaleq/views/widgets/mycircular.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/launch.dart';
import '../../../controller/home/profile/order_history_controller.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/mycircular.dart';
// --- الويدجت الرئيسية بالتصميم الجديد ---
// ─────────────────────────────────────────────────────────────────────────────
// Main Screen
// ─────────────────────────────────────────────────────────────────────────────
class OrderHistory extends StatelessWidget {
const OrderHistory({super.key});
@override
Widget build(BuildContext context) {
// نفس منطق استدعاء الكنترولر
Get.put(OrderHistoryController());
return MyScafolld(
@@ -24,7 +29,6 @@ class OrderHistory extends StatelessWidget {
body: [
GetBuilder<OrderHistoryController>(
builder: (controller) {
// --- نفس منطق التحميل والحالة الفارغة ---
if (controller.isloading) {
return const MyCircularProgressIndicator();
}
@@ -33,159 +37,550 @@ class OrderHistory extends StatelessWidget {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.map_outlined,
size: 80, color: AppColor.writeColor.withOpacity(0.4)),
Icon(Icons.route_outlined,
size: 80, color: AppColor.writeColor.withOpacity(0.3)),
const SizedBox(height: 16),
Text('No trip history found'.tr,
style: AppStyle.headTitle2),
Text("Your past trips will appear here.".tr,
const SizedBox(height: 6),
Text('Your past trips will appear here.'.tr,
style: AppStyle.subtitle),
],
),
);
}
// --- استخدام ListView.separated لفصل البطاقات ---
return ListView.separated(
padding: const EdgeInsets.all(16.0),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
itemCount: controller.orderHistoryListPassenger.length,
separatorBuilder: (context, index) => const SizedBox(height: 16),
itemBuilder: (BuildContext context, int index) {
separatorBuilder: (_, __) => const SizedBox(height: 14),
itemBuilder: (context, index) {
final ride = controller.orderHistoryListPassenger[index];
// --- استدعاء ويدجت البطاقة الجديدة ---
return _buildHistoryCard(context, ride);
return _HistoryCard(
key: ValueKey(ride['id'] ?? index),
ride: ride,
);
},
);
},
)
),
],
);
}
}
// --- ويدجت بناء بطاقة الرحلة ---
Widget _buildHistoryCard(BuildContext context, Map<String, dynamic> ride) {
// --- نفس منطق حساب إحداثيات الخريطة ---
final LatLng startLocation = LatLng(
double.parse(ride['start_location'].toString().split(',')[0]),
double.parse(ride['start_location'].toString().split(',')[1]),
);
final LatLng endLocation = LatLng(
double.parse(ride['end_location'].toString().split(',')[0]),
double.parse(ride['end_location'].toString().split(',')[1]),
);
final LatLngBounds bounds = LatLngBounds(
northeast: LatLng(
startLocation.latitude > endLocation.latitude
? startLocation.latitude
: endLocation.latitude,
startLocation.longitude > endLocation.longitude
? startLocation.longitude
: endLocation.longitude,
),
southwest: LatLng(
startLocation.latitude < endLocation.latitude
? startLocation.latitude
: endLocation.latitude,
startLocation.longitude < endLocation.longitude
? startLocation.longitude
: endLocation.longitude,
),
);
// ─────────────────────────────────────────────────────────────────────────────
// Coordinate helpers
// ─────────────────────────────────────────────────────────────────────────────
LatLng _parseLatLng(String raw, LatLng fallback) {
try {
final parts = raw.split(',');
return LatLng(double.parse(parts[0]), double.parse(parts[1]));
} catch (_) {
return fallback;
}
}
return InkWell(
// --- نفس دالة onTap القديمة ---
onTap: () {
String mapUrl =
'https://www.google.com/maps/dir/${ride['start_location']}/${ride['end_location']}/';
showInBrowser(mapUrl);
},
borderRadius: BorderRadius.circular(16),
child: Container(
decoration: BoxDecoration(
color: AppColor.secondaryColor,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
blurRadius: 8,
offset: const Offset(0, 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// --- 1. قسم الخريطة ---
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
const LatLng _kDamascus = LatLng(33.5, 36.3);
// ─────────────────────────────────────────────────────────────────────────────
// Lightweight card — NO native map in the list
// ─────────────────────────────────────────────────────────────────────────────
class _HistoryCard extends StatelessWidget {
final Map<String, dynamic> ride;
const _HistoryCard({Key? key, required this.ride}) : super(key: key);
@override
Widget build(BuildContext context) {
final start = _parseLatLng(ride['start_location'] ?? '', _kDamascus);
final end = _parseLatLng(ride['end_location'] ?? '', _kDamascus);
final status = ride['status'] ?? '';
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => _openDetail(context, ride, start, end),
borderRadius: BorderRadius.circular(18),
child: Ink(
decoration: BoxDecoration(
color: AppColor.secondaryColor,
borderRadius: BorderRadius.circular(18),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.12),
blurRadius: 10,
offset: const Offset(0, 4),
),
child: SizedBox(
height: 150, // ارتفاع ثابت للخريطة
child: AbsorbPointer(
// لمنع التفاعل المباشر مع الخريطة داخل القائمة
child: MapLibreMap(
styleString: "assets/style.json",
initialCameraPosition:
CameraPosition(target: startLocation, zoom: 12),
onStyleLoadedCallback: () async {
// This is a bit tricky in a list, but we can do it:
// Since we don't have the controller here easily without state,
// we'll rely on the simple map view or use a stateful widget for each card.
// For now, let's keep it simple.
},
onMapCreated: (MapLibreMapController controller) async {
await controller.addSymbol(SymbolOptions(
geometry: startLocation,
iconImage: 'start_icon',
));
await controller.addSymbol(SymbolOptions(
geometry: endLocation,
iconImage: 'end_icon',
));
await controller.addLine(LineOptions(
geometry: [startLocation, endLocation],
lineColor: '#${AppColor.primaryColor.value.toRadixString(16).substring(2)}',
lineWidth: 4,
));
controller.animateCamera(
CameraUpdate.newLatLngBounds(bounds, left: 20, top: 20, right: 20, bottom: 20));
},
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ── Lightweight route preview (pure Flutter, zero native cost) ──
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(18),
topRight: Radius.circular(18),
),
child: SizedBox(
height: 130,
width: double.infinity,
child: CustomPaint(
painter: _RoutePainter(start: start, end: end),
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(8),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.45),
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.map_outlined,
color: Colors.white, size: 13),
const SizedBox(width: 4),
Text('View Map'.tr,
style: const TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.w600)),
],
),
),
),
),
),
),
),
// ── Details ──────────────────────────────────────────────────
Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(Icons.access_time_rounded,
size: 14,
color: AppColor.writeColor.withOpacity(0.5)),
const SizedBox(width: 4),
Text(
'${ride['date']} · ${ride['time']}',
style: AppStyle.subtitle.copyWith(
fontSize: 12,
color: AppColor.writeColor.withOpacity(0.6)),
),
],
),
_StatusChip(status: status),
],
),
const Divider(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Total Price'.tr,
style: AppStyle.title.copyWith(fontSize: 15)),
Text(
'${ride['price']} ${'SYP'.tr}',
style: AppStyle.headTitle.copyWith(
fontSize: 20, color: AppColor.primaryColor),
),
],
),
],
),
),
],
),
),
),
);
}
void _openDetail(BuildContext context, Map<String, dynamic> ride,
LatLng start, LatLng end) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => _RideDetailSheet(ride: ride, start: start, end: end),
);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Pure-Flutter route painter — grid background + animated dashed line
// ─────────────────────────────────────────────────────────────────────────────
class _RoutePainter extends CustomPainter {
final LatLng start;
final LatLng end;
const _RoutePainter({required this.start, required this.end});
@override
void paint(Canvas canvas, Size size) {
// Background gradient
final bgPaint = Paint()
..shader = LinearGradient(
colors: [
AppColor.primaryColor.withOpacity(0.08),
AppColor.primaryColor.withOpacity(0.18),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), bgPaint);
// Subtle grid
final gridPaint = Paint()
..color = AppColor.primaryColor.withOpacity(0.06)
..strokeWidth = 1;
const step = 20.0;
for (double x = 0; x < size.width; x += step) {
canvas.drawLine(Offset(x, 0), Offset(x, size.height), gridPaint);
}
for (double y = 0; y < size.height; y += step) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), gridPaint);
}
// Map lat/lng to canvas — simple linear projection
final minLat = math.min(start.latitude, end.latitude);
final maxLat = math.max(start.latitude, end.latitude);
final minLng = math.min(start.longitude, end.longitude);
final maxLng = math.max(start.longitude, end.longitude);
final latRange = maxLat - minLat;
final lngRange = maxLng - minLng;
final pad = 32.0;
Offset project(LatLng p) {
double x, y;
if (lngRange < 0.0005) {
x = size.width / 2;
} else {
x = pad + ((p.longitude - minLng) / lngRange) * (size.width - 2 * pad);
}
if (latRange < 0.0005) {
y = size.height / 2;
} else {
// Invert y (latitude grows up, canvas grows down)
y = size.height -
pad -
((p.latitude - minLat) / latRange) * (size.height - 2 * pad);
}
return Offset(x, y);
}
final startPt = project(start);
final endPt = project(end);
// Dashed route line
final linePaint = Paint()
..color = AppColor.primaryColor
..strokeWidth = 2.5
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke;
_drawDashedLine(canvas, startPt, endPt, linePaint, 8, 5);
// Glow behind markers
final glowPaint = Paint()
..color = AppColor.primaryColor.withOpacity(0.2)
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 8);
canvas.drawCircle(startPt, 14, glowPaint);
canvas.drawCircle(endPt, 14, glowPaint);
// Start dot (A)
_drawMarker(canvas, startPt, AppColor.primaryColor, 'A');
// End dot (B)
_drawMarker(canvas, endPt, AppColor.redColor, 'B');
}
void _drawDashedLine(Canvas canvas, Offset p1, Offset p2, Paint paint,
double dashLen, double gapLen) {
final dx = p2.dx - p1.dx;
final dy = p2.dy - p1.dy;
final dist = math.sqrt(dx * dx + dy * dy);
if (dist == 0) return;
final ux = dx / dist;
final uy = dy / dist;
double traveled = 0;
bool drawing = true;
while (traveled < dist) {
final segLen = drawing ? dashLen : gapLen;
final next = math.min(traveled + segLen, dist);
if (drawing) {
canvas.drawLine(
Offset(p1.dx + ux * traveled, p1.dy + uy * traveled),
Offset(p1.dx + ux * next, p1.dy + uy * next),
paint,
);
}
traveled = next;
drawing = !drawing;
}
}
void _drawMarker(Canvas canvas, Offset center, Color color, String label) {
// Outer ring
canvas.drawCircle(center, 12, Paint()..color = color.withOpacity(0.25));
// Solid circle
canvas.drawCircle(center, 8, Paint()..color = color);
// White inner
canvas.drawCircle(center, 4, Paint()..color = Colors.white);
// Label text
final tp = TextPainter(
text: TextSpan(
text: label,
style: TextStyle(
color: color, fontSize: 7, fontWeight: FontWeight.w900)),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, center - Offset(tp.width / 2, tp.height / 2));
}
@override
bool shouldRepaint(_RoutePainter old) => old.start != start || old.end != end;
}
// ─────────────────────────────────────────────────────────────────────────────
// Status chip
// ─────────────────────────────────────────────────────────────────────────────
class _StatusChip extends StatelessWidget {
final String status;
const _StatusChip({required this.status});
@override
Widget build(BuildContext context) {
Color color;
IconData icon;
if (status == 'Canceled'.tr) {
color = AppColor.redColor;
icon = Icons.cancel_outlined;
} else if (status == 'Finished'.tr) {
color = AppColor.greenColor;
icon = Icons.check_circle_outline;
} else {
color = AppColor.yellowColor;
icon = Icons.hourglass_empty_rounded;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.12),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: color.withOpacity(0.3), width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 13),
const SizedBox(width: 4),
Text(status,
style: AppStyle.subtitle.copyWith(
color: color, fontWeight: FontWeight.bold, fontSize: 11)),
],
),
);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Detail bottom sheet — ONE MapLibre instance, only when user requests it
// ─────────────────────────────────────────────────────────────────────────────
class _RideDetailSheet extends StatefulWidget {
final Map<String, dynamic> ride;
final LatLng start;
final LatLng end;
const _RideDetailSheet(
{required this.ride, required this.start, required this.end});
@override
State<_RideDetailSheet> createState() => _RideDetailSheetState();
}
class _RideDetailSheetState extends State<_RideDetailSheet> {
MapLibreMapController? _mc;
LatLngBounds? get _bounds {
final latDiff = (widget.start.latitude - widget.end.latitude).abs();
final lngDiff = (widget.start.longitude - widget.end.longitude).abs();
if (latDiff < 0.0005 && lngDiff < 0.0005) return null;
return LatLngBounds(
northeast: LatLng(
math.max(widget.start.latitude, widget.end.latitude),
math.max(widget.start.longitude, widget.end.longitude),
),
southwest: LatLng(
math.min(widget.start.latitude, widget.end.latitude),
math.min(widget.start.longitude, widget.end.longitude),
),
);
}
void _onMapCreated(MapLibreMapController c) => _mc = c;
Future<void> _onStyleLoaded() async {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await Future.delayed(const Duration(milliseconds: 400));
if (!mounted || _mc == null) return;
await _draw();
});
}
Future<void> _draw() async {
final mc = _mc;
if (mc == null || !mounted) return;
try {
final aData = await rootBundle.load('assets/images/A.png');
await mc.addImage('det_start', aData.buffer.asUint8List());
final bData = await rootBundle.load('assets/images/b.png');
await mc.addImage('det_end', bData.buffer.asUint8List());
} catch (_) {}
await mc.addLine(LineOptions(
geometry: [widget.start, widget.end],
lineColor:
'#${AppColor.primaryColor.value.toRadixString(16).substring(2)}',
lineWidth: 4.0,
lineOpacity: 1.0,
));
await mc.addSymbol(SymbolOptions(
geometry: widget.start,
iconImage: 'det_start',
iconSize: 0.8,
iconAnchor: 'bottom',
));
await mc.addSymbol(SymbolOptions(
geometry: widget.end,
iconImage: 'det_end',
iconSize: 0.8,
iconAnchor: 'bottom',
));
final b = _bounds;
if (b != null) {
await mc.animateCamera(CameraUpdate.newLatLngBounds(b,
left: 60, top: 60, right: 60, bottom: 60));
} else {
await mc.animateCamera(CameraUpdate.newLatLngZoom(widget.start, 14));
}
}
@override
void dispose() {
_mc?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final ride = widget.ride;
final center = LatLng(
(widget.start.latitude + widget.end.latitude) / 2,
(widget.start.longitude + widget.end.longitude) / 2,
);
return DraggableScrollableSheet(
initialChildSize: 0.88,
minChildSize: 0.5,
maxChildSize: 0.95,
builder: (_, scrollController) => Container(
decoration: BoxDecoration(
color: AppColor.secondaryColor,
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
),
child: Column(
children: [
// Handle
Container(
margin: const EdgeInsets.symmetric(vertical: 10),
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColor.writeColor.withOpacity(0.2),
borderRadius: BorderRadius.circular(2),
),
),
// --- 2. قسم تفاصيل الرحلة ---
Padding(
padding: const EdgeInsets.all(12.0),
// Map — only ONE instance, created on demand
Expanded(
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
child: MapLibreMap(
styleString: 'assets/style.json',
initialCameraPosition:
CameraPosition(target: center, zoom: 12),
onMapCreated: _onMapCreated,
onStyleLoadedCallback: _onStyleLoaded,
myLocationEnabled: false,
trackCameraPosition: false,
),
),
),
// Trip info strip
Container(
padding: const EdgeInsets.fromLTRB(20, 14, 20, 20),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${ride['date']} - ${ride['time']}',
style: AppStyle.subtitle.copyWith(
color: AppColor.writeColor.withOpacity(0.7)),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${ride['date']} · ${ride['time']}',
style: AppStyle.subtitle.copyWith(
fontSize: 12,
color:
AppColor.writeColor.withOpacity(0.55))),
const SizedBox(height: 2),
Text('${ride['price']} ${'SYP'.tr}',
style: AppStyle.headTitle.copyWith(
fontSize: 22, color: AppColor.primaryColor)),
],
),
// --- ويدجت جديدة لعرض حالة الرحلة ---
_buildStatusChip(ride['status']),
_StatusChip(status: ride['status'] ?? ''),
],
),
const Divider(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Total Price'.tr,
style: AppStyle.title.copyWith(fontSize: 16)),
Text(
'${ride['price']} ${'SYP'.tr}',
style: AppStyle.headTitle.copyWith(
fontSize: 20, color: AppColor.primaryColor),
const SizedBox(height: 14),
// Open in Google Maps
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
final url =
'https://www.google.com/maps/dir/${ride['start_location']}/${ride['end_location']}/';
showInBrowser(url);
},
icon: const Icon(Icons.open_in_new, size: 16),
label: Text('Open in Google Maps'.tr),
style: ElevatedButton.styleFrom(
backgroundColor: AppColor.primaryColor,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 13),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
],
),
),
],
),
@@ -195,42 +590,4 @@ class OrderHistory extends StatelessWidget {
),
);
}
// --- ويدجت مساعدة لعرض حالة الرحلة بشكل أنيق ---
Widget _buildStatusChip(String status) {
Color chipColor;
IconData chipIcon;
// --- نفس منطق تحديد اللون ---
if (status == 'Canceled'.tr) {
chipColor = AppColor.redColor;
chipIcon = Icons.cancel_outlined;
} else if (status == 'Finished'.tr) {
chipColor = AppColor.greenColor;
chipIcon = Icons.check_circle_outline;
} else {
chipColor = AppColor.yellowColor;
chipIcon = Icons.hourglass_empty_rounded;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: chipColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(chipIcon, color: chipColor, size: 16),
const SizedBox(width: 6),
Text(
status,
style: AppStyle.subtitle.copyWith(
color: chipColor, fontWeight: FontWeight.bold, fontSize: 12),
),
],
),
);
}
}

File diff suppressed because it is too large Load Diff