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 createState() => _BluetoothConnectionScreenState(); } class _BluetoothConnectionScreenState extends State { List _scanResults = []; bool _isScanning = false; BluetoothDevice? _connectedDevice; // Track connected device late StreamSubscription> _scanResultsSubscription; late StreamSubscription _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 _requestPermissionsAndStartScan() async { if (Platform.isAndroid) { Map 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 _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 _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 _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 _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(AppColors.coral), minHeight: 2, ), ), ], ), ); } }