Mudança na tela bluetooth

This commit is contained in:
2026-02-26 17:35:05 +00:00
parent 67811db547
commit e20de5f992

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'dart:async'; import 'dart:async';
import 'constants/app_colors.dart';
class BluetoothScreen extends StatefulWidget { class BluetoothScreen extends StatefulWidget {
const BluetoothScreen({super.key}); const BluetoothScreen({super.key});
@@ -20,14 +21,27 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
void initState() { void initState() {
super.initState(); super.initState();
// Ouvir os resultados da busca e ordenar
_scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) { _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
if (mounted) { if (mounted) {
// Criar uma cópia da lista e ordenar
List<ScanResult> sortedResults = List.from(results);
sortedResults.sort((a, b) {
bool aHasName = _hasRealName(a);
bool bHasName = _hasRealName(b);
if (aHasName && !bHasName) return -1; // 'a' vem primeiro
if (!aHasName && bHasName) return 1; // 'b' vem primeiro
return 0; // Mantém a ordem original entre iguais
});
setState(() { setState(() {
_scanResults = results; _scanResults = sortedResults;
}); });
} }
}); });
// Ouvir o estado da busca
_isScanningSubscription = FlutterBluePlus.isScanning.listen((state) { _isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
if (mounted) { if (mounted) {
setState(() { setState(() {
@@ -37,6 +51,11 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
}); });
} }
// Função auxiliar para verificar se tem nome real
bool _hasRealName(ScanResult r) {
return r.advertisementData.advName.isNotEmpty || r.device.platformName.isNotEmpty;
}
@override @override
void dispose() { void dispose() {
_scanResultsSubscription?.cancel(); _scanResultsSubscription?.cancel();
@@ -45,7 +64,6 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
} }
Future<void> startScan() async { Future<void> startScan() async {
// 1. Pedir permissões
Map<Permission, PermissionStatus> statuses = await [ Map<Permission, PermissionStatus> statuses = await [
Permission.bluetoothScan, Permission.bluetoothScan,
Permission.bluetoothConnect, Permission.bluetoothConnect,
@@ -56,15 +74,16 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
statuses[Permission.bluetoothConnect]!.isGranted) { statuses[Permission.bluetoothConnect]!.isGranted) {
try { try {
// 2. Iniciar Scan _scanResults.clear();
await FlutterBluePlus.startScan( await FlutterBluePlus.startScan(
timeout: const Duration(seconds: 15), timeout: const Duration(seconds: 15),
androidUsesFineLocation: true,
continuousUpdates: true,
); );
// Se não encontrar nada (ex: no emulador), avisa o usuário Future.delayed(const Duration(seconds: 8), () {
Future.delayed(const Duration(seconds: 5), () {
if (mounted && _scanResults.isEmpty && _isScanning) { if (mounted && _scanResults.isEmpty && _isScanning) {
_showSnackBar("Nenhum dispositivo encontrado (Verifique se o Bluetooth/GPS estão ligados)", Colors.orange); _showSnackBar("Nenhum dispositivo encontrado.", AppColors.coral);
} }
}); });
@@ -72,14 +91,22 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
_showSnackBar("Erro ao iniciar busca: $e", Colors.red); _showSnackBar("Erro ao iniciar busca: $e", Colors.red);
} }
} else { } else {
_showSnackBar("Permissões de Bluetooth negadas", Colors.orange); _showSnackBar("Permissões negadas.", AppColors.coral);
}
}
Future<void> stopScan() async {
try {
await FlutterBluePlus.stopScan();
} catch (e) {
_showSnackBar("Erro ao parar busca: $e", Colors.red);
} }
} }
Future<void> connectToDevice(BluetoothDevice device) async { Future<void> connectToDevice(BluetoothDevice device) async {
try { try {
String name = device.platformName.isEmpty ? 'Dispositivo' : device.platformName; String name = device.platformName.isNotEmpty ? device.platformName : "Dispositivo";
_showSnackBar("Conectando a $name...", Colors.blue); _showSnackBar("Conectando a $name...", Colors.white70);
await device.connect(); await device.connect();
_showSnackBar("Conectado com sucesso!", Colors.green); _showSnackBar("Conectado com sucesso!", Colors.green);
} catch (e) { } catch (e) {
@@ -87,6 +114,18 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
} }
} }
// Lógica para capturar o nome
String _getDeviceName(ScanResult r) {
if (r.advertisementData.advName.isNotEmpty) {
return r.advertisementData.advName;
} else if (r.device.platformName.isNotEmpty) {
return r.device.platformName;
} else {
String id = r.device.remoteId.toString();
return "Disp. [${id.length > 5 ? id.substring(id.length - 5) : id}]";
}
}
void _showSnackBar(String message, Color color) { void _showSnackBar(String message, Color color) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -94,6 +133,7 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
content: Text(message), content: Text(message),
backgroundColor: color, backgroundColor: color,
duration: const Duration(seconds: 3), duration: const Duration(seconds: 3),
behavior: SnackBarBehavior.floating,
), ),
); );
} }
@@ -102,74 +142,189 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Conexão Bluetooth'), title: const Text('Bluetooth', style: TextStyle(fontWeight: FontWeight.bold)),
backgroundColor: Colors.black87, centerTitle: true,
foregroundColor: Colors.white, backgroundColor: Colors.transparent,
elevation: 0,
foregroundColor: AppColors.white,
), ),
backgroundColor: Colors.grey[900], extendBodyBehindAppBar: true,
body: Column( backgroundColor: AppColors.background,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
AppColors.coral.withOpacity(0.1),
AppColors.background,
],
),
),
child: Column(
children: [ children: [
const SizedBox(height: 20), const SizedBox(height: 100),
Center( Center(
child: Column( child: Column(
children: [ children: [
const Icon(Icons.bluetooth, size: 80, color: Colors.blue), Container(
const SizedBox(height: 10), padding: const EdgeInsets.all(25),
ElevatedButton.icon( decoration: BoxDecoration(
onPressed: _isScanning ? null : startScan, shape: BoxShape.circle,
icon: _isScanning color: _isScanning
? const SizedBox( ? AppColors.coral.withOpacity(0.1)
: AppColors.backgroundGrey.withOpacity(0.3),
border: Border.all(
color: _isScanning ? AppColors.coral : AppColors.backgroundGrey,
width: 2,
),
),
child: Icon(
_isScanning ? Icons.bluetooth_searching : Icons.bluetooth,
size: 60,
color: _isScanning ? AppColors.coral : AppColors.white.withOpacity(0.7),
),
),
const SizedBox(height: 30),
SizedBox(
width: 220,
height: 50,
child: ElevatedButton(
onPressed: _isScanning ? stopScan : startScan,
style: ElevatedButton.styleFrom(
backgroundColor: _isScanning ? AppColors.backgroundGrey : AppColors.white,
foregroundColor: _isScanning ? AppColors.white : AppColors.background,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
elevation: 0,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isScanning)
const Padding(
padding: EdgeInsets.only(right: 10),
child: SizedBox(
width: 18, width: 18,
height: 18, height: 18,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.black), child: CircularProgressIndicator(
) strokeWidth: 2,
: const Icon(Icons.search), color: AppColors.white,
label: Text(_isScanning ? 'Buscando...' : 'Procurar Dispositivos'), ),
style: ElevatedButton.styleFrom( ),
backgroundColor: Colors.white, ),
foregroundColor: Colors.black, Text(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), _isScanning ? 'PARAR BUSCA' : 'BUSCAR AGORA',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
letterSpacing: 1.2,
), ),
), ),
], ],
), ),
), ),
const SizedBox(height: 20), ),
],
),
),
const SizedBox(height: 40),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Row(
children: [
Text(
_isScanning ? "Procurando..." : "Dispositivos próximos",
style: const TextStyle(
color: AppColors.white,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const Spacer(),
if (_isScanning)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: AppColors.coral.withOpacity(0.2),
borderRadius: BorderRadius.circular(10),
),
child: const Text(
"ATIVO",
style: TextStyle(color: AppColors.coral, fontSize: 10, fontWeight: FontWeight.bold),
),
),
],
),
),
const SizedBox(height: 15),
Expanded( Expanded(
child: _scanResults.isEmpty && !_isScanning child: _scanResults.isEmpty && !_isScanning
? const Center( ? Center(
child: Text( child: Column(
"Clique em Procurar para encontrar dispositivos.\n(Nota: Requer telemóvel físico para Bluetooth real)", mainAxisAlignment: MainAxisAlignment.center,
textAlign: TextAlign.center, children: [
style: TextStyle(color: Colors.white54), Icon(Icons.bluetooth_disabled, size: 40, color: AppColors.white.withOpacity(0.1)),
const SizedBox(height: 16),
Text(
"Inicie a busca para conectar",
style: TextStyle(color: AppColors.white.withOpacity(0.3)),
),
],
), ),
) )
: ListView.builder( : ListView.builder(
padding: const EdgeInsets.only(top: 0, bottom: 20),
itemCount: _scanResults.length, itemCount: _scanResults.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final r = _scanResults[index]; final r = _scanResults[index];
final name = r.device.platformName.isEmpty final name = _getDeviceName(r);
? "Dispositivo Desconhecido" final isUnknown = name.startsWith("Disp. [");
: r.device.platformName;
return Card( return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
color: Colors.white10, decoration: BoxDecoration(
color: AppColors.backgroundGrey.withOpacity(0.2),
borderRadius: BorderRadius.circular(15),
),
child: ListTile( child: ListTile(
leading: const Icon(Icons.bluetooth, color: Colors.blue), contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
leading: CircleAvatar(
backgroundColor: AppColors.backgroundGrey.withOpacity(0.3),
child: Icon(
isUnknown ? Icons.devices_other : Icons.bluetooth,
color: isUnknown ? AppColors.white.withOpacity(0.4) : AppColors.white,
size: 20
),
),
title: Text( title: Text(
name, name,
style: const TextStyle( style: TextStyle(
color: Colors.white, color: isUnknown ? AppColors.white.withOpacity(0.5) : AppColors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.w600,
fontSize: 15,
), ),
), ),
subtitle: Text( subtitle: Text(
r.device.remoteId.toString(), r.device.remoteId.toString(),
style: const TextStyle(color: Colors.white70), style: TextStyle(color: AppColors.white.withOpacity(0.3), fontSize: 11),
), ),
trailing: ElevatedButton( trailing: ElevatedButton(
onPressed: () => connectToDevice(r.device), onPressed: () => connectToDevice(r.device),
child: const Text("Conectar"), style: ElevatedButton.styleFrom(
backgroundColor: AppColors.coral,
foregroundColor: AppColors.white,
padding: const EdgeInsets.symmetric(horizontal: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
elevation: 0,
),
child: const Text("CONECTAR", style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold)),
), ),
), ),
); );
@@ -178,6 +333,7 @@ class _BluetoothScreenState extends State<BluetoothScreen> {
), ),
], ],
), ),
),
); );
} }
} }