ensurePermissionOrOpenSettings method

Future<bool> ensurePermissionOrOpenSettings(
  1. KruzrPermission kruzrPermission
)

Ensures a permission is granted through a comprehensive flow.

This is a convenience method that implements a complete permission handling strategy with error handling:

  1. First checks if the permission is already granted
  2. If not granted, requests the permission from the user
  3. If the request is denied, opens the device settings for manual configuration

This method provides the most user-friendly approach to permission handling by automatically escalating through the available options.

Parameters:

Returns: A Future<bool> that resolves to:

  • true if the permission is granted (either initially or after request)
  • false if the permission was not granted and settings were opened

Throws:

  • Exception with message "Unable to ensure permission or open settings" if the underlying permission flow fails

Flow diagram:

Check Permission
      ↓
  Granted? → Yes → Return true
      ↓ No
Request Permission
      ↓
  Granted? → Yes → Return true
      ↓ No
 Open Settings
      ↓
  Return false

Note:

  • When this method returns false, the settings page has been opened but the permission status is still denied
  • Consider checking the permission again when the app regains focus in case the user granted it in settings

Example:

try {
  bool hasPermission = await ensurePermissionOrOpenSettings(KruzrPermission.location);
  if (hasPermission) {
    // Permission is granted, proceed with feature
    startLocationTracking();
  } else {
    // Settings were opened, consider checking again when app regains focus
    showMessage('Please grant location permission in settings and restart the feature.');
  }
} catch (e) {
  // Handle permission flow error
  print('Failed to ensure permission: $e');
}

Implementation

Future<bool> ensurePermissionOrOpenSettings(
  KruzrPermission kruzrPermission,
) async {
  try {
    return await kruzr_comm.ensurePermissionOrOpenSettings(kruzrPermission);
  } on Exception catch (e, stackTrace) {
    if (kDebugMode) {
      print("Error in ensurePermissionOrOpenSettings");
      print(stackTrace);
      print(e);
    }
    return Future.error("Unable to ensure permission or open settings");
  }
}