rework do design, mapa, e adicao de uma tela provisoria sobre a conexao bluetooth que esta a funcionar (placeholder para oque o fabio fez ate aquilo estar tudo certo)

This commit is contained in:
2026-03-04 16:15:48 +00:00
parent bbd6185401
commit 666f06ab6a
10 changed files with 1093 additions and 256 deletions

View File

@@ -0,0 +1,373 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import '../constants/app_colors.dart';
class BluetoothConnectionScreen extends StatefulWidget {
const BluetoothConnectionScreen({super.key});
@override
State<BluetoothConnectionScreen> createState() => _BluetoothConnectionScreenState();
}
class _BluetoothConnectionScreenState extends State<BluetoothConnectionScreen> {
List<ScanResult> _scanResults = [];
bool _isScanning = false;
BluetoothDevice? _connectedDevice; // Track connected device
late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
late StreamSubscription<bool> _isScanningSubscription;
@override
void initState() {
super.initState();
_scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
if (mounted) {
setState(() {
// FILTRO: Mantém apenas dispositivos que possuem um nome identificado
_scanResults = results.where((r) => r.device.platformName.isNotEmpty).toList();
});
}
});
_isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
if (mounted) {
setState(() {
_isScanning = state;
});
}
});
}
@override
void dispose() {
_scanResultsSubscription.cancel();
_isScanningSubscription.cancel();
super.dispose();
}
Future<void> _requestPermissionsAndStartScan() async {
if (Platform.isAndroid) {
Map<Permission, PermissionStatus> statuses = await [
Permission.bluetoothScan,
Permission.bluetoothConnect,
Permission.location,
].request();
if (statuses[Permission.bluetoothScan]!.isGranted &&
statuses[Permission.bluetoothConnect]!.isGranted) {
_startScan();
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Permissões de Bluetooth negadas.'),
behavior: SnackBarBehavior.floating,
),
);
}
}
} else {
_startScan();
}
}
Future<void> _startScan() async {
try {
if (await FlutterBluePlus.adapterState.first != BluetoothAdapterState.on) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ligue o Bluetooth para buscar dispositivos.'),
behavior: SnackBarBehavior.floating,
),
);
}
return;
}
await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao iniciar scan: $e'),
behavior: SnackBarBehavior.floating,
),
);
}
}
}
Future<void> _stopScan() async {
try {
await FlutterBluePlus.stopScan();
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao parar scan: $e'),
behavior: SnackBarBehavior.floating,
),
);
}
}
}
Future<void> _connectToDevice(BluetoothDevice device) async {
try {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Conectando a ${device.platformName}...'),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
),
);
await device.connect();
if (mounted) {
setState(() {
_connectedDevice = device;
_isScanning = false;
});
FlutterBluePlus.stopScan();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Conectado com sucesso!'),
backgroundColor: Colors.green,
behavior: SnackBarBehavior.floating,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao conectar: $e'),
backgroundColor: Colors.red,
behavior: SnackBarBehavior.floating,
),
);
}
}
}
Future<void> _disconnectDevice() async {
if (_connectedDevice != null) {
await _connectedDevice!.disconnect();
setState(() {
_connectedDevice = null;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text(
'DISPOSITIVOS',
style: TextStyle(
fontWeight: FontWeight.w900,
letterSpacing: 2,
color: Colors.white,
),
),
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white, size: 20),
onPressed: () => Navigator.pop(context),
),
),
body: Stack(
children: [
Column(
children: [
const SizedBox(height: 20),
// Header Card
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: Container(
padding: const EdgeInsets.all(25),
decoration: BoxDecoration(
color: AppColors.backgroundGrey,
borderRadius: BorderRadius.circular(30),
border: Border.all(color: Colors.white.withOpacity(0.05)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_connectedDevice != null
? 'STATUS: CONECTADO'
: (_isScanning ? 'STATUS: BUSCANDO...' : 'STATUS: PRONTO'),
style: TextStyle(
color: _connectedDevice != null ? Colors.greenAccent : (_isScanning ? AppColors.coral : Colors.white54),
fontSize: 10,
fontWeight: FontWeight.w900,
letterSpacing: 1,
),
),
const SizedBox(height: 8),
Text(
_connectedDevice != null
? '1 Dispositivo'
: '${_scanResults.length} Encontrados',
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w900,
),
),
],
),
if (_connectedDevice == null)
GestureDetector(
onTap: _isScanning ? _stopScan : _requestPermissionsAndStartScan,
child: Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: _isScanning ? Colors.red.withOpacity(0.1) : AppColors.coral.withOpacity(0.1),
shape: BoxShape.circle,
border: Border.all(
color: _isScanning ? Colors.red.withOpacity(0.5) : AppColors.coral.withOpacity(0.5),
width: 2,
),
),
child: Icon(
_isScanning ? Icons.stop_rounded : Icons.search_rounded,
color: _isScanning ? Colors.red : AppColors.coral,
size: 28,
),
),
)
else
GestureDetector(
onTap: _disconnectDevice,
child: Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: Colors.red.withOpacity(0.1),
shape: BoxShape.circle,
border: Border.all(
color: Colors.red.withOpacity(0.5),
width: 2,
),
),
child: const Icon(
Icons.close_rounded,
color: Colors.red,
size: 28,
),
),
),
],
),
),
),
const SizedBox(height: 30),
// Device List
Expanded(
child: ListView.builder(
itemCount: _connectedDevice != null ? 1 : _scanResults.length,
padding: const EdgeInsets.symmetric(horizontal: 25),
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
final BluetoothDevice device = _connectedDevice ?? _scanResults[index].device;
final name = device.platformName;
return Padding(
padding: const EdgeInsets.only(bottom: 18),
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.backgroundGrey.withOpacity(0.4),
borderRadius: BorderRadius.circular(25),
border: Border.all(color: Colors.white.withOpacity(0.03)),
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.background.withOpacity(0.8),
borderRadius: BorderRadius.circular(15),
),
child: Icon(
Icons.bluetooth_audio_rounded,
color: _connectedDevice != null ? Colors.greenAccent : AppColors.coral.withOpacity(0.8),
size: 24
),
),
const SizedBox(width: 20),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w900
),
),
const SizedBox(height: 4),
Text(
device.remoteId.toString(),
style: const TextStyle(
color: Colors.white38,
fontSize: 11,
fontWeight: FontWeight.bold
),
),
],
),
),
if (_connectedDevice == null)
GestureDetector(
onTap: () => _connectToDevice(device),
child: const Icon(Icons.add_link_rounded, color: Colors.white24),
)
else
const Icon(Icons.check_circle_rounded, color: Colors.greenAccent),
],
),
),
);
},
),
),
],
),
if (_isScanning)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: LinearProgressIndicator(
backgroundColor: Colors.transparent,
valueColor: const AlwaysStoppedAnimation<Color>(AppColors.coral),
minHeight: 2,
),
),
],
),
);
}
}

View File

@@ -1,5 +1,11 @@
import 'dart:async';
import 'dart:math';
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';
class GoogleMapScreen extends StatefulWidget {
const GoogleMapScreen({super.key});
@@ -9,26 +15,234 @@ class GoogleMapScreen extends StatefulWidget {
}
class _GoogleMapScreenState extends State<GoogleMapScreen> {
late GoogleMapController mapController;
GoogleMapController? _mapController;
StreamSubscription<Position>? _positionStreamSubscription;
Timer? _simulationTimer;
final List<LatLng> _routePoints = [];
final Set<Polyline> _polylines = {};
final Set<Marker> _markers = {};
LatLng? _plannedStart;
LatLng? _plannedEnd;
bool _isPlanningMode = false;
final LatLng _center = const LatLng(38.7223, -9.1393); // Lisbon coordinates
double _currentSpeed = 0.0;
double _totalDistance = 0.0;
LatLng _currentPosition = const LatLng(38.7223, -9.1393);
bool _isLoading = true;
bool _isSimulating = false;
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
BitmapDescriptor? _startIcon;
BitmapDescriptor? _arrowIcon;
BitmapDescriptor? _finishIcon;
@override
void initState() {
super.initState();
_setupIconsAndTracking();
}
Future<void> _setupIconsAndTracking() async {
_startIcon = await _createPremiumMarker(Colors.greenAccent, Icons.play_arrow_rounded, 85);
_finishIcon = await _createPremiumMarker(AppColors.coral, Icons.flag_rounded, 85);
_arrowIcon = await _createArrowMarker(Colors.black, Colors.white, 95);
await _initTracking();
}
Future<BitmapDescriptor> _createPremiumMarker(Color color, IconData icon, double size) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final Paint shadowPaint = Paint()..color = Colors.black.withOpacity(0.4)..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6);
canvas.drawCircle(Offset(size / 2, size / 2 + 3), size / 2, shadowPaint);
canvas.drawCircle(Offset(size / 2, size / 2), size / 2, Paint()..color = Colors.white);
canvas.drawCircle(Offset(size / 2, size / 2), size / 2 - 5, Paint()..color = color);
TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr);
textPainter.text = TextSpan(text: String.fromCharCode(icon.codePoint), style: TextStyle(fontSize: size * 0.6, fontFamily: icon.fontFamily, color: Colors.white, fontWeight: FontWeight.bold));
textPainter.layout();
textPainter.paint(canvas, Offset((size - textPainter.width) / 2, (size - textPainter.height) / 2));
final ui.Image image = await recorder.endRecording().toImage(size.toInt(), size.toInt() + 6);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
}
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, 4)), Paint()..color = Colors.black38..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4));
canvas.drawPath(path, Paint()..color = color);
canvas.drawPath(path, Paint()..color = borderColor..style = ui.PaintingStyle.stroke..strokeWidth = 7);
final ui.Image image = await recorder.endRecording().toImage(size.toInt(), size.toInt() + 6);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
}
@override
void dispose() {
_positionStreamSubscription?.cancel();
_simulationTimer?.cancel();
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();
_currentPosition = LatLng(position.latitude, position.longitude);
setState(() => _isLoading = false);
_startLocationStream();
}
void _startLocationStream() {
_positionStreamSubscription = Geolocator.getPositionStream(locationSettings: const LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 5)).listen((Position position) {
if (!_isSimulating) _updatePosition(LatLng(position.latitude, position.longitude), position.speed);
});
}
void _updatePosition(LatLng newPoint, double speed) {
setState(() {
if (_routePoints.isNotEmpty) {
_totalDistance += Geolocator.distanceBetween(_currentPosition.latitude, _currentPosition.longitude, newPoint.latitude, newPoint.longitude);
}
_currentSpeed = speed;
_routePoints.add(newPoint);
_currentPosition = newPoint;
// Update only the dynamic follower arrow
_markers.removeWhere((m) => m.markerId.value == 'follower');
_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,
));
if (_routePoints.length > 1) {
_polylines.removeWhere((p) => p.polylineId.value == 'route' || p.polylineId.value == 'route_glow');
_polylines.add(Polyline(
polylineId: const PolylineId('route_glow'),
points: List.from(_routePoints),
color: Colors.lightBlueAccent.withOpacity(0.3),
width: 14,
zIndex: 9,
));
_polylines.add(Polyline(
polylineId: const PolylineId('route'),
points: List.from(_routePoints),
color: Colors.white,
width: 6,
patterns: [PatternItem.dot, PatternItem.gap(15)],
jointType: JointType.round,
zIndex: 10,
));
}
});
_mapController?.animateCamera(CameraUpdate.newLatLng(newPoint));
}
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 _onMapTap(LatLng point) {
if (!_isPlanningMode) return;
setState(() {
if (_plannedStart == null) {
_plannedStart = point;
_markers.add(Marker(markerId: const MarkerId('planned_start'), position: point, icon: _startIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
} else if (_plannedEnd == null) {
_plannedEnd = point;
_markers.add(Marker(markerId: const MarkerId('planned_end'), position: point, icon: _finishIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
_polylines.add(Polyline(polylineId: const PolylineId('planned_route'), points: [_plannedStart!, _plannedEnd!], color: Colors.white.withOpacity(0.1), width: 2, zIndex: 1));
} else {
_plannedStart = point;
_plannedEnd = null;
_markers.removeWhere((m) => m.markerId.value.startsWith('planned'));
_polylines.removeWhere((p) => p.polylineId.value == 'planned_route');
_markers.add(Marker(markerId: const MarkerId('planned_start'), position: point, icon: _startIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
}
});
}
void _toggleSimulation() {
if (_isSimulating) {
_simulationTimer?.cancel();
setState(() => _isSimulating = false);
} else {
setState(() {
_isSimulating = true;
_isPlanningMode = false;
_routePoints.clear();
_polylines.removeWhere((p) => p.polylineId.value == 'route' || p.polylineId.value == 'route_glow');
_totalDistance = 0.0;
// Start from planned start OR current real location
_currentPosition = _plannedStart ?? _currentPosition;
// Initialize routePoints with the start so the arrow appears immediately at the start point
_routePoints.add(_currentPosition);
// Update only the follower arrow. Planned markers are already in the set.
_markers.removeWhere((m) => m.markerId.value == 'follower');
_markers.add(Marker(
markerId: const MarkerId('follower'),
position: _currentPosition,
flat: true,
anchor: const Offset(0.5, 0.5),
icon: _arrowIcon ?? BitmapDescriptor.defaultMarker,
zIndex: 12,
));
});
_simulationTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
double latStep = 0.00025;
double lngStep = 0.00025;
if (_plannedEnd != null) {
double dist = Geolocator.distanceBetween(_currentPosition.latitude, _currentPosition.longitude, _plannedEnd!.latitude, _plannedEnd!.longitude);
if (dist < 12) {
_updatePosition(_plannedEnd!, 0.0);
_toggleSimulation();
return;
}
latStep = (_plannedEnd!.latitude - _currentPosition.latitude) / (max(dist / 8, 1));
lngStep = (_plannedEnd!.longitude - _currentPosition.longitude) / (max(dist / 8, 1));
}
LatLng nextPoint = LatLng(_currentPosition.latitude + latStep, _currentPosition.longitude + lngStep);
_updatePosition(nextPoint, 3.5 + Random().nextDouble());
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Mapa da Corrida'),
backgroundColor: Colors.black, // or your AppColors.background
elevation: 0,
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(target: _center, zoom: 13.0),
),
backgroundColor: AppColors.background,
appBar: AppBar(title: Text(_isPlanningMode ? 'PLANEJAR ROTA' : 'CORRIDA VIVA', style: const TextStyle(fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 2)), centerTitle: true, backgroundColor: Colors.transparent, elevation: 0, leading: IconButton(icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white), onPressed: () => Navigator.pop(context)), actions: [IconButton(icon: Icon(_isPlanningMode ? Icons.check_circle_rounded : Icons.add_location_alt_rounded, color: AppColors.coral, size: 30), onPressed: () => setState(() => _isPlanningMode = !_isPlanningMode))]),
extendBodyBehindAppBar: true,
body: Stack(children: [Center(child: Container(width: MediaQuery.of(context).size.width * 0.94, height: MediaQuery.of(context).size.height * 0.7, decoration: BoxDecoration(color: AppColors.backgroundGrey, borderRadius: BorderRadius.circular(55), border: Border.all(color: Colors.white.withOpacity(0.1), width: 3), boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.7), blurRadius: 50, offset: const Offset(0, 30))]), 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, onTap: _onMapTap, markers: _markers, polylines: _polylines, zoomControlsEnabled: false, myLocationButtonEnabled: false, compassEnabled: false, mapToolbarEnabled: false)))), Positioned(top: 115, left: 45, right: 45, child: Container(padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25), decoration: BoxDecoration(color: AppColors.background.withOpacity(0.95), borderRadius: BorderRadius.circular(25), border: Border.all(color: Colors.white10), boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 10)]), child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [_buildStat("RITMO", "${(_currentSpeed * 3.6).toStringAsFixed(1)}", "KM/H"), Container(width: 1, height: 35, color: Colors.white10), _buildStat("TRAJETO", (_totalDistance / 1000).toStringAsFixed(2), "KM")]))), if (_isPlanningMode) Positioned(bottom: 140, left: 60, right: 60, child: Container(padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: Colors.black.withOpacity(0.85), borderRadius: BorderRadius.circular(20), border: Border.all(color: AppColors.coral.withOpacity(0.5))), child: const Text("Toque para definir Início e Fim", textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.bold))))]),
floatingActionButton: FloatingActionButton.extended(onPressed: _toggleSimulation, label: Text(_isSimulating ? "PARAR" : "INICIAR CORRIDA", style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 1.5)), icon: Icon(_isSimulating ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 32), backgroundColor: _isSimulating ? AppColors.coral : Colors.white, foregroundColor: _isSimulating ? Colors.white : AppColors.background, elevation: 15),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
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: 26, fontWeight: FontWeight.w900)), const SizedBox(width: 3), Text(unit, style: const TextStyle(color: Colors.white54, fontSize: 10, fontWeight: FontWeight.bold))])]);
}
}