requestAuthorization method
Future<bool>
requestAuthorization(
- List<
HealthDataType> types, { - List<
HealthDataAccess> ? permissions,
Requests permissions to access health data types
.
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 oftypes
.
- If unspecified, each HealthDataType in
Caveats:
- This method may block if permissions are already granted. Hence, check hasPermissions before calling this method.
- 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 ||
type == HealthDataType.HIGH_HEART_RATE_EVENT ||
type == HealthDataType.LOW_HEART_RATE_EVENT ||
type == HealthDataType.IRREGULAR_HEART_RATE_EVENT ||
type == HealthDataType.WALKING_HEART_RATE) &&
permission != HealthDataAccess.READ) {
throw ArgumentError(
'Requesting WRITE permission on ELECTROCARDIOGRAM / HIGH_HEART_RATE_EVENT / LOW_HEART_RATE_EVENT / IRREGULAR_HEART_RATE_EVENT / WALKING_HEART_RATE 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 (Platform.isAndroid) _handleBMI(mTypes, mPermissions);
List<String> keys = mTypes.map((e) => e.name).toList();
final bool? isAuthorized = await _channel.invokeMethod(
'requestAuthorization', {'types': keys, "permissions": mPermissions});
return isAuthorized ?? false;
}