connectDevice method

void connectDevice(
  1. ScanResult scanResult, {
  2. BleConnectCallback? callback,
})

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:

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);
    }
  });
}