connectDevice method
Initiates a connection to the specified Bluetooth device.
This method begins the connection process to the device represented by
the provided scanResult. It also accepts an optional callback
to provide updates on the connection state. The connection process will
handle Bluetooth adapter states, including turning on the Bluetooth if
it is currently off.
Parameters:
scanResult: TheScanResultobject representing the device to connect to.callback: An optional BleConnectCallback function that will be called to notify the caller of connection state changes. Possible states include:- BleConnectionState.onConnectStart: When the connection process starts.
- BleConnectionState.onConnectFail: When the connection fails.
Note: This method will attempt to turn on the Bluetooth adapter if it is off on Android devices. If the Bluetooth is off on non-Android platforms, the connection will fail. Ensure that the callback is properly implemented to handle the connection state changes effectively.
Implementation
void connectDevice(ScanResult scanResult, {BleConnectCallback? callback}) async {
callback?.call(BleConnectionState.onConnectStart);
if (await FlutterBluePlus.isSupported == false) {
callback?.call(BleConnectionState.onConnectFail);
return;
}
_adapterStateSubscription?.cancel();
_adapterStateSubscription = FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) async {
if (state != BluetoothAdapterState.on) {
if (Platform.isAndroid) {
await FlutterBluePlus.turnOn();
} else {
callback?.call(BleConnectionState.onConnectFail);
}
}
if (state == BluetoothAdapterState.on) {
_connect(scanResult, callback);
}
});
}