import 'package:flutter/material.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:gps_map_flowpoint/deviceFlowMap.dart'; class DeviceSelection extends StatefulWidget { const DeviceSelection({super.key, required this.title}); final String title; @override State createState() => _DeviceSelectionState(); } class _DeviceSelectionState extends State { // List to hold the scanned devices List scanResults = []; TextEditingController tecSearch = TextEditingController(); bool isScanning = false; // Initialize Bluetooth scanning and subscription in initState @override void initState() { super.initState(); FlutterBluePlus.isSupported.then((isSupported) { if (!isSupported) { showDialog( context: context, builder: (context) { return AlertDialog( title: Text("Bluetooth non activé"), content: Text( "Le Bluetooth n'est pas activé sur cet appareil. Veillez l'activer pour continuer."), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("OK"), ), ], ); }, ); } }); FlutterBluePlus.onScanResults.listen( (results) { setState(() { scanResults = results; }); }, onError: (e) => print(e), ); } @override Widget build(BuildContext context) { // Filtered list of devices List filteredDevices = scanResults .where((result) => result.device.name .toLowerCase() .contains(tecSearch.text.toLowerCase())) .toList(); return Scaffold( appBar: AppBar( backgroundColor: Colors.blue, title: Text("Selection de l'appareil BLE", style: TextStyle(color: Colors.white)), ), body: Column( children: [ Padding( padding: const EdgeInsets.all(16.0), child: TextFormField( controller: tecSearch, decoration: InputDecoration( hintText: 'Rechercher un appareil', prefixIcon: Icon(Icons.search), ), onChanged: (value) { setState(() {}); }, ), ), SizedBox(height: 16.0), Expanded( child: ListView.builder( itemCount: filteredDevices.length, itemBuilder: (context, index) { ScanResult result = filteredDevices[index]; return ListTile( title: Text(result.device.name), subtitle: Text(result.device.id.id), onTap: () { //Stop scanning when a device is selected FlutterBluePlus.stopScan(); setState(() { isScanning = false; }); Navigator.push( context, MaterialPageRoute( builder: (context) => DeviceFlowMap( title: 'GPS Map Flowpoint', deviceName: result.device.name, deviceAddress: result.device.id.id, ), ), ); }, ); }, ), ), ], ), floatingActionButton: FloatingActionButton( backgroundColor: Colors.blue, onPressed: () { print('Scanning'); setState(() { isScanning = !isScanning; if (isScanning) { FlutterBluePlus.startScan(); } else { FlutterBluePlus.stopScan(); } }); }, child: Icon(isScanning ? Icons.stop : Icons.play_arrow, color: Colors.white), ), ); } }