checkAndRequestPermissions method

Future<bool> checkAndRequestPermissions()

Checks and requests the Bluetooth permissions needed to scan and connect.

On Android 12+ (API 31+) requests:

  • Permission.bluetoothScan
  • Permission.bluetoothConnect

On Android < 12 requests:

  • Permission.bluetooth
  • Permission.locationWhenInUse (required by the OS to discover nearby devices)

On iOS requests:

  • Permission.bluetooth

Returns true when every required permission is granted, false otherwise. If any permission is permanently denied the method opens the app settings so the user can enable it manually.

Implementation

Future<bool> checkAndRequestPermissions() async {
  final List<Permission> required = _requiredBluetoothPermissions();

  // Check current status for all required permissions.
  final Map<Permission, PermissionStatus> statuses = await required.request();

  bool allGranted = true;
  bool anyPermanentlyDenied = false;

  for (final entry in statuses.entries) {
    if (entry.value.isPermanentlyDenied) {
      anyPermanentlyDenied = true;
      allGranted = false;
    } else if (!entry.value.isGranted) {
      allGranted = false;
    }
  }

  // If a permission is permanently denied, guide the user to app settings.
  if (anyPermanentlyDenied) {
    await openAppSettings();
  }

  return allGranted;
}