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'; import '../constants/app_strings.dart'; class BluetoothConnectionScreen extends StatefulWidget { const BluetoothConnectionScreen({super.key}); @override State createState() => _BluetoothConnectionScreenState(); } class _BluetoothConnectionScreenState extends State { List _scanResults = []; bool _isScanning = false; BluetoothDevice? _connectedDevice; late StreamSubscription> _scanResultsSubscription; late StreamSubscription _isScanningSubscription; @override void initState() { super.initState(); _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) { if (mounted) { setState(() { // Filtra os dispositivos para mostrar apenas aqueles 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.bluetoothAdvertise, Permission.location, ].request(); bool allGranted = true; if (statuses[Permission.bluetoothScan]?.isDenied ?? true) allGranted = false; if (statuses[Permission.bluetoothConnect]?.isDenied ?? true) allGranted = false; final bool scanPermanentlyDenied = statuses[Permission.bluetoothScan]?.isPermanentlyDenied ?? false; final bool connectPermanentlyDenied = statuses[Permission.bluetoothConnect]?.isPermanentlyDenied ?? false; if (scanPermanentlyDenied || connectPermanentlyDenied) { if (mounted) { _showSettingsDialog(); } return; } if (allGranted) { _startScan(); } else { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(AppStrings.permissionsDenied), behavior: SnackBarBehavior.floating, ), ); } } } else { _startScan(); } } void _showSettingsDialog() { showDialog( context: context, builder: (context) => AlertDialog( title: Text(AppStrings.permissionsNeeded), content: Text(AppStrings.permissionsDeniedPermanent), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text(AppStrings.btnCancel), ), TextButton( onPressed: () { openAppSettings(); Navigator.pop(context); }, child: Text(AppStrings.settingsTitle), ), ], ), ); } Future _startScan() async { try { if (await FlutterBluePlus.adapterState.first != BluetoothAdapterState.on) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(AppStrings.turnOnBluetooth), behavior: SnackBarBehavior.floating, ), ); } return; } await FlutterBluePlus.startScan( timeout: const Duration(seconds: 15), ); } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${AppStrings.scanError}$e'), behavior: SnackBarBehavior.floating, ), ); } } } Future _stopScan() async { try { await FlutterBluePlus.stopScan(); } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${AppStrings.stopScanError}$e'), behavior: SnackBarBehavior.floating, ), ); } } } Future _connectToDevice(BluetoothDevice device) async { try { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${AppStrings.connectingTo}${device.platformName.isEmpty ? AppStrings.unknownDevice : 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( SnackBar( content: Text(AppStrings.connectedSuccess), backgroundColor: AppColors.success, behavior: SnackBarBehavior.floating, ), ); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${AppStrings.connectFail}$e'), backgroundColor: AppColors.error, 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: Text( AppStrings.bluetoothTitle, style: const 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), 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.withValues(alpha: 0.05)), boxShadow: [ BoxShadow( color: Colors.black.withValues(alpha: 0.3), blurRadius: 20, offset: const Offset(0, 10), ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _connectedDevice != null ? AppStrings.statusConnected : (_isScanning ? AppStrings.searching : AppStrings.statusReady), 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 ? AppStrings.oneDevice : '${_scanResults.length} ${AppStrings.foundDevices}', 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.withValues(alpha: 0.1) : AppColors.coral.withValues(alpha: 0.1), shape: BoxShape.circle, border: Border.all( color: _isScanning ? Colors.red.withValues(alpha: 0.5) : AppColors.coral.withValues(alpha: 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.withValues(alpha: 0.1), shape: BoxShape.circle, border: Border.all( color: Colors.red.withValues(alpha: 0.5), width: 2, ), ), child: const Icon( Icons.close_rounded, color: Colors.red, size: 28, ), ), ), ], ), ), ), const SizedBox(height: 30), 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.isEmpty ? AppStrings.unknownDevice : device.platformName; return Padding( padding: const EdgeInsets.only(bottom: 18), child: Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: AppColors.backgroundGrey.withValues(alpha: 0.4), borderRadius: BorderRadius.circular(25), border: Border.all(color: Colors.white.withValues(alpha: 0.03)), ), child: Row( children: [ Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: AppColors.background.withValues(alpha: 0.8), borderRadius: BorderRadius.circular(15), ), child: Icon( Icons.bluetooth_audio_rounded, color: _connectedDevice != null ? Colors.greenAccent : AppColors.coral.withValues(alpha: 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) const Positioned( bottom: 0, left: 0, right: 0, child: LinearProgressIndicator( backgroundColor: Colors.transparent, valueColor: AlwaysStoppedAnimation(AppColors.coral), minHeight: 2, ), ), ], ), ); } }