i am trying to scan for devices but i'm getting so many devices available with no names on them. When i scan with another bluetooth app i find no device or maybe one or two. So i guess there's something wrong in my dart code and i seem to not be able to figure it out.so please help
So here's my bluetoothManager class, any help will be appreciated. Thanks
import 'dart:async';
import 'package:flutter_blue/flutter_blue.dart';
class BluetoothManager {
final FlutterBlue _flutterBlue = FlutterBlue.instance;
bool isConnected = false;
BluetoothDevice? connectedDevice;
late StreamSubscription<List<ScanResult>> _scanSubscription;
Future<Stream<BluetoothState>> getBluetoothState() async {
return _flutterBlue.state;
}
Future<List<BluetoothDevice>> scanForDevices() async {
List<BluetoothDevice> devices = [];
try {
devices.clear();
// Start scanning for devices
await _flutterBlue.startScan(timeout: const Duration(seconds: 10));
// Listen for discovered devices and handle the subscription
_scanSubscription = _flutterBlue.scanResults.listen((results) {
for (ScanResult result in results) {
if (!devices.contains(result.device)) {
devices.add(result.device);
print('Discovered device: ${result.device.name}');
}
}
}, onError: (error) {
print('Error in scanResults stream: $error');
}, onDone: () {
print('Scan completed');
});
// Wait for the scan to complete
await Future.delayed(Duration(seconds: 10));
// Stop scanning for devices
await _flutterBlue.stopScan();
} catch (error) {
print('Error scanning for devices: $error');
} finally {
// Cancel the subscription after scan completion or error
_scanSubscription.cancel();
}
return devices;
}
Future<void> connectToDevice(BluetoothDevice device) async {
try {
// Check if the device is already connected
if (isConnected && connectedDevice == device) {
print('Device is already connected');
return;
}
// Disconnect from any previously connected device
if (isConnected && connectedDevice != null) {
await connectedDevice!.disconnect();
isConnected = false;
}
// Connect to the new device
await device.connect();
connectedDevice = device;
isConnected = true;
print('Connected to device: ${device.name ?? 'Unknown'}');
} catch (error) {
print('Error connecting to device: $error');
}
}
void sendCommand(String command) {
if (isConnected && connectedDevice != null) {
// Replace this with your logic to send data to the connected device
print('Sending command: $command');
} else {
print('No device connected');
}
}
}
A Bluetooth LE device can transmit its name in the advertisement message, but it does not have to. The assumption that every Bluetooth LE broadcaster transmits its device name in the advertisement is incorrect. I think your app is doing everything right and that the reference app you are using is simply filtering out all Bluetooth LE devices without names.