requestAuthorization method

Future<bool> requestAuthorization(
  1. List<HealthDataType> types, {
  2. List<HealthDataAccess>? permissions,
})

Requests permissions to access data types in Apple Health or Google Fit.

Returns true if successful, false otherwise

Parameters:

  • types - a list of HealthDataType which the permissions are requested for.
  • permissions - Optional.
    • If unspecified, each HealthDataType in types is requested for READ HealthDataAccess.
    • If specified, each HealthDataAccess in this list is requested for its corresponding indexed entry in types. In addition, the length of this list must be equal to that of types.

Caveat:

As Apple HealthKit will not disclose if READ access has been granted for a data type due to privacy concern, this method will return true if the window asking for permission was showed to the user without errors if it is called on iOS with a READ or READ_WRITE access.

Implementation

Future<bool> requestAuthorization(
  List<HealthDataType> types, {
  List<HealthDataAccess>? permissions,
}) async {
  if (permissions != null && permissions.length != types.length) {
    throw ArgumentError(
        'The length of [types] must be same as that of [permissions].');
  }

  if (permissions != null) {
    for (int i = 0; i < types.length; i++) {
      final type = types[i];
      final permission = permissions[i];
      if (type == HealthDataType.ELECTROCARDIOGRAM &&
          permission != HealthDataAccess.READ) {
        throw ArgumentError(
            'Requesting WRITE permission on ELECTROCARDIOGRAM is not allowed.');
      }
    }
  }

  final mTypes = List<HealthDataType>.from(types, growable: true);
  final mPermissions = permissions == null
      ? List<int>.filled(types.length, HealthDataAccess.READ.index,
          growable: true)
      : permissions.map((permission) => permission.index).toList();

  // on Android, if BMI is requested, then also ask for weight and height
  if (_platformType == PlatformType.ANDROID) _handleBMI(mTypes, mPermissions);

  List<String> keys = mTypes.map((e) => _enumToString(e)).toList();
  final bool? isAuthorized = await _channel.invokeMethod(
      'requestAuthorization', {'types': keys, "permissions": mPermissions});
  return isAuthorized ?? false;
}