Base de dados atualizada

This commit is contained in:
Carlos Correia
2026-03-24 10:43:49 +00:00
parent 1794208143
commit b70ac32327
5 changed files with 865 additions and 204 deletions

View File

@@ -6,6 +6,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import '../constants/app_colors.dart';
import '../constants/app_strings.dart';
import '../services/supabase_service.dart';
class GoogleMapScreen extends StatefulWidget {
const GoogleMapScreen({super.key});
@@ -49,7 +50,11 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
await _initTracking();
}
Future<BitmapDescriptor> _createArrowMarker(Color color, Color borderColor, double size) async {
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();
@@ -60,17 +65,29 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
path.close();
canvas.drawPath(
path.shift(const Offset(0, 2)),
Paint()
..color = Colors.black38
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 2));
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);
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);
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());
}
@@ -90,7 +107,9 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) return;
}
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.bestForNavigation,
);
_currentPosition = LatLng(position.latitude, position.longitude);
_routePoints.add(_currentPosition);
@@ -100,15 +119,23 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
}
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);
}
});
_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) {
@@ -116,19 +143,21 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
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
_currentPosition.latitude,
_currentPosition.longitude,
newPoint.latitude,
newPoint.longitude,
);
_routePoints.add(newPoint);
_updateTraveledPolylines();
} else {
@@ -148,42 +177,53 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
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
));
_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(
_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
));
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);
return Geolocator.bearingBetween(
p1.latitude,
p1.longitude,
p2.latitude,
p2.longitude,
);
}
void _showStartConfirmation() {
@@ -192,17 +232,43 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
builder: (context) => AlertDialog(
backgroundColor: AppColors.backgroundGrey,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
title: Text(AppStrings.startRunQuestion, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
content: Text(AppStrings.startRunDescription, style: const TextStyle(color: Colors.white70)),
title: Text(
AppStrings.startRunQuestion,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
content: Text(
AppStrings.startRunDescription,
style: const TextStyle(color: Colors.white70),
),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: Text(AppStrings.cancel, style: const TextStyle(color: Colors.white54))),
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(
AppStrings.cancel,
style: const TextStyle(color: Colors.white54),
),
),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
_startCountdown();
},
style: ElevatedButton.styleFrom(backgroundColor: AppColors.coral, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15))),
child: Text(AppStrings.yes, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.coral,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: Text(
AppStrings.yes,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
],
),
@@ -253,6 +319,12 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
_isRunning = false;
});
// Calculate pace (minutes per kilometer)
final pace = _calculatePace(finalDistance, finalTime);
// Save run data to database
_saveRunData(finalDistance, pace, finalTime);
showGeneralDialog(
context: context,
barrierDismissible: false,
@@ -266,7 +338,10 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
child: AlertDialog(
backgroundColor: AppColors.background,
contentPadding: EdgeInsets.zero,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(35), side: const BorderSide(color: Colors.white10, width: 2)),
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),
@@ -275,11 +350,26 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
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),
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),
Text(AppStrings.runFinished, style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.w900, letterSpacing: 1)),
Text(
AppStrings.runFinished,
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w900,
letterSpacing: 1,
),
),
const SizedBox(height: 30),
Container(
height: 180,
@@ -291,18 +381,34 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
child: ClipRRect(
borderRadius: BorderRadius.circular(23),
child: GoogleMap(
initialCameraPosition: CameraPosition(target: finalRoute.isNotEmpty ? finalRoute.first : _currentPosition, zoom: 15),
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
));
});
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)
Polyline(
polylineId: const PolylineId('final_path'),
points: finalRoute,
color: AppColors.coral,
width: 4,
),
},
zoomControlsEnabled: false,
myLocationButtonEnabled: false,
@@ -313,11 +419,20 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
),
),
const SizedBox(height: 25),
_buildResultRow(AppStrings.totalDistance, _formatDistance(finalDistance)),
_buildResultRow(
AppStrings.totalDistance,
_formatDistance(finalDistance),
),
const Divider(color: Colors.white10, height: 25),
_buildResultRow(AppStrings.totalTime, _formatTime(finalTime)),
_buildResultRow(
AppStrings.totalTime,
_formatTime(finalTime),
),
const Divider(color: Colors.white10, height: 25),
_buildResultRow(AppStrings.maxSpeed, "${finalMaxSpeed.toStringAsFixed(1)} ${AppStrings.kmhUnit}"),
_buildResultRow(
AppStrings.maxSpeed,
"${finalMaxSpeed.toStringAsFixed(1)} ${AppStrings.kmhUnit}",
),
const SizedBox(height: 35),
SizedBox(
width: double.infinity,
@@ -334,10 +449,18 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
backgroundColor: Colors.white,
foregroundColor: AppColors.background,
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
elevation: 0,
),
child: Text(AppStrings.close.toUpperCase(), style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 2)),
child: Text(
AppStrings.close.toUpperCase(),
style: const TextStyle(
fontWeight: FontWeight.w900,
letterSpacing: 2,
),
),
),
),
],
@@ -365,7 +488,8 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
}
String _formatDistance(double meters) {
if (meters < 1000) return "${meters.toStringAsFixed(0)} ${AppStrings.metersUnit}";
if (meters < 1000)
return "${meters.toStringAsFixed(0)} ${AppStrings.metersUnit}";
return "${(meters / 1000).toStringAsFixed(2)} ${AppStrings.kmUnit}";
}
@@ -379,72 +503,157 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
return "${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}";
}
// Calculate pace (minutes per kilometer)
double _calculatePace(double distanceInMeters, int timeInSeconds) {
if (distanceInMeters <= 0 || timeInSeconds <= 0) return 0.0;
double distanceInKm = distanceInMeters / 1000;
double paceInMinutesPerKm = timeInSeconds / 60.0 / distanceInKm;
return paceInMinutesPerKm;
}
// Save run data to database
Future<void> _saveRunData(double distance, double pace, int duration) async {
try {
await SupabaseService.saveRun(
distance: distance,
pace: pace,
duration: duration,
);
// Show success message (optional)
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Corrida salva com sucesso!'),
backgroundColor: Colors.green,
duration: Duration(seconds: 2),
),
);
}
} catch (e) {
// Show error message
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao salvar corrida: $e'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 3),
),
);
}
}
}
@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,
_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)
)
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,
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,
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),
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)]
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 15,
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildStat(AppStrings.mapPace, _currentSpeed.toStringAsFixed(1), AppStrings.kmhUnit),
_buildStat(
AppStrings.mapPace,
_currentSpeed.toStringAsFixed(1),
AppStrings.kmhUnit,
),
_buildDivider(),
_buildStat(AppStrings.mapRoute, _formatDistanceValue(_totalDistance), _totalDistance < 1000 ? AppStrings.metersUnit : AppStrings.kmUnit),
_buildStat(
AppStrings.mapRoute,
_formatDistanceValue(_totalDistance),
_totalDistance < 1000
? AppStrings.metersUnit
: AppStrings.kmUnit,
),
_buildDivider(),
_buildStat(AppStrings.mapTime, _formatTimeShort(_secondsElapsed), ""),
_buildStat(
AppStrings.mapTime,
_formatTimeShort(_secondsElapsed),
"",
),
],
),
),
@@ -459,30 +668,58 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(AppStrings.prepare, style: const TextStyle(color: Colors.white54, fontSize: 24, fontWeight: FontWeight.bold, letterSpacing: 5)),
Text(
AppStrings.prepare,
style: const 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)),
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,
),
),
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,
);
}
@@ -491,8 +728,22 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
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)),
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,
),
),
],
);
}
@@ -508,22 +759,45 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
return "${mins.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}";
}
Widget _buildDivider() => Container(width: 1, height: 35, color: Colors.white10);
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)),
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)),
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))
const SizedBox(width: 3),
Text(
unit,
style: const TextStyle(
color: Colors.white38,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
],
],
),