emitCurrentPermissionStatus static method

Future<Stream<BluetoothPermissionStatus>> emitCurrentPermissionStatus(
  1. MethodChannel channel
)

Emits the current Bluetooth permission status to the Dart side.

This method communicates with the native platform code to obtain the current Bluetooth permission status and emits it to any listeners on the Dart side.

Listeners on the Dart side will receive one of the following enum values from BluetoothPermissionStatus:

  • BluetoothPermissionStatus.GRANTED: Indicates that Bluetooth permission is granted.
  • BluetoothPermissionStatus.DENIED: Indicates that Bluetooth permission is denied.

Returns a Stream of BluetoothPermissionStatus values representing the current Bluetooth permission status on the device.

Important: The stream is a broadcast stream, but you should set up your listener immediately after calling this method to ensure you receive the initial status emission.

Implementation

static Future<Stream<BluetoothPermissionStatus>> emitCurrentPermissionStatus(
  MethodChannel channel,
) async {
  final StreamController<BluetoothPermissionStatus> streamController =
      StreamController<BluetoothPermissionStatus>.broadcast();

  channel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'permissionStatusUpdated') {
      final String permissionStatusString = call.arguments as String;

      // Convert the string status to its corresponding enum value
      final BluetoothPermissionStatus status =
          BluetoothPermissionStatus.values.firstWhere(
        (status) => status.identifier == permissionStatusString,
      );

      streamController.add(status);
    }
  });

  // Use a microtask to ensure the stream is returned before the native method is invoked
  // This gives the caller a chance to set up their listener before the first value is emitted
  unawaited(
    Future.microtask(() async {
      await channel.invokeMethod('emitCurrentPermissionStatus');
    }),
  );

  return streamController.stream;
}