Files
DiasAbertos_RunVisionPro/lib/screens/google_map_screen.dart

534 lines
20 KiB
Dart

import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import '../constants/app_colors.dart';
import '../constants/app_strings.dart';
class GoogleMapScreen extends StatefulWidget {
const GoogleMapScreen({super.key});
@override
State<GoogleMapScreen> createState() => _GoogleMapScreenState();
}
class _GoogleMapScreenState extends State<GoogleMapScreen> {
GoogleMapController? _mapController;
StreamSubscription<Position>? _positionStreamSubscription;
Timer? _stopwatchTimer;
DateTime? _lastUpdate;
final List<LatLng> _routePoints = [];
final Set<Polyline> _polylines = {};
final Set<Marker> _markers = {};
bool _isRunning = false;
bool _isLoading = true;
double _currentSpeed = 0.0;
double _maxSpeed = 0.0;
double _totalDistance = 0.0;
LatLng _currentPosition = const LatLng(0, 0);
int _secondsElapsed = 0;
int _countdownValue = 3;
bool _isCountingDown = false;
BitmapDescriptor? _arrowIcon;
@override
void initState() {
super.initState();
_setupIconsAndTracking();
}
Future<void> _setupIconsAndTracking() async {
_arrowIcon = await _createArrowMarker(Colors.black, Colors.white, 25);
await _initTracking();
}
Future<BitmapDescriptor> _createArrowMarker(Color color, Color borderColor, double size) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final Path path = Path();
path.moveTo(size / 2, 0);
path.lineTo(size * 0.9, size);
path.lineTo(size / 2, size * 0.7);
path.lineTo(size * 0.1, size);
path.close();
canvas.drawPath(
path.shift(const Offset(0, 2)),
Paint()
..color = Colors.black38
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 2));
canvas.drawPath(path, Paint()..color = color);
double strokeWidth = size * 0.12;
canvas.drawPath(path, Paint()..color = borderColor..style = ui.PaintingStyle.stroke..strokeWidth = strokeWidth);
final ui.Image image = await recorder.endRecording().toImage(size.toInt(), size.toInt() + 4);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.bytes(byteData!.buffer.asUint8List());
}
@override
void dispose() {
_positionStreamSubscription?.cancel();
_stopwatchTimer?.cancel();
_mapController?.dispose();
super.dispose();
}
Future<void> _initTracking() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) return;
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) return;
}
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);
_currentPosition = LatLng(position.latitude, position.longitude);
_routePoints.add(_currentPosition);
setState(() => _isLoading = false);
_updateMarkers();
_startLocationStream();
}
void _startLocationStream() {
_positionStreamSubscription = Geolocator.getPositionStream(
locationSettings: const LocationSettings(accuracy: LocationAccuracy.bestForNavigation, distanceFilter: 1)
).listen((Position position) {
final now = DateTime.now();
if (_lastUpdate == null || now.difference(_lastUpdate!).inMilliseconds > 2000) {
_lastUpdate = now;
_updatePosition(LatLng(position.latitude, position.longitude), position.speed);
}
});
}
void _updatePosition(LatLng newPoint, double speed) {
if (!mounted) return;
setState(() {
double currentSpeedKmh = speed * 3.6;
if (currentSpeedKmh < 0) currentSpeedKmh = 0;
_currentSpeed = currentSpeedKmh;
if (_isRunning) {
if (currentSpeedKmh > _maxSpeed) {
_maxSpeed = currentSpeedKmh;
}
_totalDistance += Geolocator.distanceBetween(
_currentPosition.latitude, _currentPosition.longitude,
newPoint.latitude, newPoint.longitude
);
_routePoints.add(newPoint);
_updateTraveledPolylines();
} else {
if (_routePoints.length >= 2) _routePoints.removeAt(0);
_routePoints.add(newPoint);
}
_currentPosition = newPoint;
_updateMarkers();
});
if (_mapController != null) {
_mapController!.animateCamera(CameraUpdate.newLatLng(newPoint));
}
}
void _updateTraveledPolylines() {
if (_routePoints.length > 1) {
_polylines.clear();
_polylines.add(Polyline(
polylineId: const PolylineId('route_glow'),
points: List.from(_routePoints),
color: AppColors.coral.withOpacity(0.3),
width: 12,
zIndex: 9
));
_polylines.add(Polyline(
polylineId: const PolylineId('route'),
points: List.from(_routePoints),
color: AppColors.coral,
width: 5,
jointType: JointType.round,
zIndex: 10
));
}
}
void _updateMarkers() {
_markers.clear();
_markers.add(Marker(
markerId: const MarkerId('follower'),
position: _currentPosition,
rotation: _calculateRotation(_routePoints),
flat: true,
anchor: const Offset(0.5, 0.5),
icon: _arrowIcon ?? BitmapDescriptor.defaultMarker,
zIndex: 12
));
}
double _calculateRotation(List<LatLng> points) {
if (points.length < 2) return 0;
LatLng p1 = points[points.length - 2];
LatLng p2 = points.last;
return Geolocator.bearingBetween(p1.latitude, p1.longitude, p2.latitude, p2.longitude);
}
void _showStartConfirmation() {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: AppColors.backgroundGrey,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
title: const Text("Iniciar Corrida?", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
content: const Text("Deseja começar o monitoramento agora?", style: TextStyle(color: Colors.white70)),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text(AppStrings.cancel, style: TextStyle(color: Colors.white54))),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
_startCountdown();
},
style: ElevatedButton.styleFrom(backgroundColor: AppColors.coral, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
child: const Text(AppStrings.yes, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
),
],
),
);
}
void _startCountdown() {
setState(() {
_isCountingDown = true;
_countdownValue = 3;
});
Timer.periodic(const Duration(seconds: 1), (timer) {
if (_countdownValue == 1) {
timer.cancel();
_startRun();
} else {
setState(() => _countdownValue--);
}
});
}
void _startRun() {
setState(() {
_isCountingDown = false;
_isRunning = true;
_totalDistance = 0.0;
_maxSpeed = 0.0;
_secondsElapsed = 0;
_routePoints.clear();
_routePoints.add(_currentPosition);
_polylines.clear();
});
_stopwatchTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() => _secondsElapsed++);
});
}
void _finishRun() {
_stopwatchTimer?.cancel();
final finalRoute = List<LatLng>.from(_routePoints);
final finalDistance = _totalDistance;
final finalTime = _secondsElapsed;
final finalMaxSpeed = _maxSpeed;
setState(() {
_isRunning = false;
});
showGeneralDialog(
context: context,
barrierDismissible: false,
barrierLabel: "Resultados",
pageBuilder: (context, anim1, anim2) => const SizedBox(),
transitionBuilder: (context, anim1, anim2, child) {
return FadeTransition(
opacity: anim1,
child: ScaleTransition(
scale: anim1,
child: AlertDialog(
backgroundColor: AppColors.background,
contentPadding: EdgeInsets.zero,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(35), side: const BorderSide(color: Colors.white10, width: 2)),
content: Container(
width: MediaQuery.of(context).size.width * 0.85,
padding: const EdgeInsets.all(25),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(15),
decoration: const BoxDecoration(color: AppColors.coral, shape: BoxShape.circle),
child: const Icon(Icons.emoji_events_rounded, color: Colors.white, size: 40),
),
const SizedBox(height: 20),
const Text(AppStrings.runFinished, style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.w900, letterSpacing: 1)),
const SizedBox(height: 30),
Container(
height: 180,
decoration: BoxDecoration(
color: AppColors.backgroundGrey,
borderRadius: BorderRadius.circular(25),
border: Border.all(color: Colors.white10),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(23),
child: GoogleMap(
initialCameraPosition: CameraPosition(target: finalRoute.isNotEmpty ? finalRoute.first : _currentPosition, zoom: 15),
onMapCreated: (controller) {
if (finalRoute.isNotEmpty) {
Future.delayed(const Duration(milliseconds: 500), () {
controller.animateCamera(CameraUpdate.newLatLngBounds(
_getBounds(finalRoute), 40
));
});
}
},
polylines: {
Polyline(polylineId: const PolylineId('final_path'), points: finalRoute, color: AppColors.coral, width: 4)
},
zoomControlsEnabled: false,
myLocationButtonEnabled: false,
compassEnabled: false,
mapToolbarEnabled: false,
liteModeEnabled: true,
),
),
),
const SizedBox(height: 25),
_buildResultRow(AppStrings.totalDistance, _formatDistance(finalDistance)),
const Divider(color: Colors.white10, height: 25),
_buildResultRow(AppStrings.totalTime, _formatTime(finalTime)),
const Divider(color: Colors.white10, height: 25),
_buildResultRow("VELOCIDADE MÁX", "${finalMaxSpeed.toStringAsFixed(1)} ${AppStrings.kmhUnit}"),
const SizedBox(height: 35),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
setState(() {
_polylines.clear();
_routePoints.clear();
_routePoints.add(_currentPosition);
});
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: AppColors.background,
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
elevation: 0,
),
child: Text(AppStrings.close.toUpperCase(), style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 2)),
),
),
],
),
),
),
),
);
},
);
}
LatLngBounds _getBounds(List<LatLng> points) {
double? minLat, maxLat, minLng, maxLng;
for (LatLng p in points) {
if (minLat == null || p.latitude < minLat) minLat = p.latitude;
if (maxLat == null || p.latitude > maxLat) maxLat = p.latitude;
if (minLng == null || p.longitude < minLng) minLng = p.longitude;
if (maxLng == null || p.longitude > maxLng) maxLng = p.longitude;
}
return LatLngBounds(
southwest: LatLng(minLat!, minLng!),
northeast: LatLng(maxLat!, maxLng!),
);
}
String _formatDistance(double meters) {
if (meters < 1000) return "${meters.toStringAsFixed(0)} ${AppStrings.metersUnit}";
return "${(meters / 1000).toStringAsFixed(2)} ${AppStrings.kmUnit}";
}
String _formatTime(int seconds) {
int hours = seconds ~/ 3600;
int minutes = (seconds % 3600) ~/ 60;
int remainingSeconds = seconds % 60;
if (hours > 0) {
return "${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}";
}
return "${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}";
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: Text(
_isRunning ? AppStrings.mapTitleRunning : AppStrings.appTitle.toUpperCase(),
style: const TextStyle(fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 2, fontSize: 18)
),
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white),
onPressed: () => Navigator.pop(context)
)
),
extendBodyBehindAppBar: true,
body: Stack(
children: [
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.94,
height: MediaQuery.of(context).size.height * 0.72,
decoration: BoxDecoration(
color: AppColors.backgroundGrey,
borderRadius: BorderRadius.circular(55),
border: Border.all(color: Colors.white10, width: 3),
boxShadow: const [BoxShadow(color: Colors.black54, blurRadius: 40, spreadRadius: -10)]
),
child: ClipRRect(
borderRadius: BorderRadius.circular(52),
child: _isLoading
? const Center(child: CircularProgressIndicator(color: AppColors.coral))
: GoogleMap(
initialCameraPosition: CameraPosition(target: _currentPosition, zoom: 17.5),
onMapCreated: (controller) => _mapController = controller,
markers: _markers,
polylines: _polylines,
zoomControlsEnabled: false,
myLocationButtonEnabled: false,
compassEnabled: false,
mapToolbarEnabled: false,
)
)
),
),
Positioned(
top: 115, left: 25, right: 25,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 22, horizontal: 10),
decoration: BoxDecoration(
color: AppColors.background.withOpacity(0.9),
borderRadius: BorderRadius.circular(30),
border: Border.all(color: Colors.white10),
boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.3), blurRadius: 15)]
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildStat(AppStrings.mapPace, _currentSpeed.toStringAsFixed(1), AppStrings.kmhUnit),
_buildDivider(),
_buildStat(AppStrings.mapRoute, _formatDistanceValue(_totalDistance), _totalDistance < 1000 ? AppStrings.metersUnit : AppStrings.kmUnit),
_buildDivider(),
_buildStat(AppStrings.mapTime, _formatTimeShort(_secondsElapsed), ""),
],
),
),
),
if (_isCountingDown)
Container(
color: Colors.black87,
width: double.infinity,
height: double.infinity,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("PREPARAR", style: TextStyle(color: Colors.white54, fontSize: 24, fontWeight: FontWeight.bold, letterSpacing: 5)),
const SizedBox(height: 20),
Text("$_countdownValue", style: const TextStyle(color: AppColors.coral, fontSize: 160, fontWeight: FontWeight.w900)),
],
),
),
),
],
),
floatingActionButton: _isCountingDown ? null : Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: FloatingActionButton.extended(
onPressed: _isRunning ? _finishRun : _showStartConfirmation,
label: Text(
_isRunning ? AppStrings.btnStop : AppStrings.btnStartRun,
style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 1.5, fontSize: 16)
),
icon: Icon(_isRunning ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 28),
backgroundColor: _isRunning ? AppColors.coral : Colors.white,
foregroundColor: _isRunning ? Colors.white : AppColors.background,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
elevation: 10,
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
Widget _buildResultRow(String label, String value) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(color: Colors.white54, fontWeight: FontWeight.bold, fontSize: 13)),
Text(value, style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w900)),
],
);
}
String _formatDistanceValue(double meters) {
if (meters < 1000) return meters.toStringAsFixed(0);
return (meters / 1000).toStringAsFixed(2);
}
String _formatTimeShort(int seconds) {
int mins = seconds ~/ 60;
int secs = seconds % 60;
return "${mins.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}";
}
Widget _buildDivider() => Container(width: 1, height: 35, color: Colors.white10);
Widget _buildStat(String label, String value, String unit) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(label, style: const TextStyle(color: Colors.white54, fontSize: 10, fontWeight: FontWeight.w900, letterSpacing: 1.5)),
const SizedBox(height: 6),
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(value, style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.w900)),
if (unit.isNotEmpty) ...[
const SizedBox(width: 3),
Text(unit, style: const TextStyle(color: Colors.white38, fontSize: 10, fontWeight: FontWeight.bold))
],
],
),
],
);
}
}