writeHealthData method
Future<bool>
writeHealthData({
- required double value,
- HealthDataUnit? unit,
- required HealthDataType type,
- required DateTime startTime,
- DateTime? endTime,
Write health data.
Returns true if successful, false otherwise.
Parameters:
value
- the health data's value in doubleunit
- iOS ONLY the unit the health data is measured in.type
- the value's HealthDataTypestartTime
- the start time when thisvalue
is measured. It must be equal to or earlier thanendTime
.endTime
- the end time when thisvalue
is measured. It must be equal to or later thanstartTime
. Simply setendTime
equal tostartTime
if thevalue
is measured only at a specific point in time (default).
Values for Sleep and Headache are ignored and will be automatically assigned the default value.
Implementation
Future<bool> writeHealthData({
required double value,
HealthDataUnit? unit,
required HealthDataType type,
required DateTime startTime,
DateTime? endTime,
}) async {
if (type == HealthDataType.WORKOUT) {
throw ArgumentError(
"Adding workouts should be done using the writeWorkoutData method.");
}
endTime ??= startTime;
if (startTime.isAfter(endTime)) {
throw ArgumentError("startTime must be equal or earlier than endTime");
}
if ({
HealthDataType.HIGH_HEART_RATE_EVENT,
HealthDataType.LOW_HEART_RATE_EVENT,
HealthDataType.IRREGULAR_HEART_RATE_EVENT,
HealthDataType.ELECTROCARDIOGRAM,
}.contains(type) &&
Platform.isIOS) {
throw ArgumentError(
"$type - iOS does not support writing this data type in HealthKit");
}
// Assign default unit if not specified
unit ??= dataTypeToUnit[type]!;
// Align values to type in cases where the type defines the value.
// E.g. SLEEP_IN_BED should have value 0
if (type == HealthDataType.SLEEP_ASLEEP ||
type == HealthDataType.SLEEP_AWAKE ||
type == HealthDataType.SLEEP_IN_BED ||
type == HealthDataType.SLEEP_DEEP ||
type == HealthDataType.SLEEP_REM ||
type == HealthDataType.SLEEP_ASLEEP_CORE ||
type == HealthDataType.SLEEP_ASLEEP_DEEP ||
type == HealthDataType.SLEEP_ASLEEP_REM ||
type == HealthDataType.HEADACHE_NOT_PRESENT ||
type == HealthDataType.HEADACHE_MILD ||
type == HealthDataType.HEADACHE_MODERATE ||
type == HealthDataType.HEADACHE_SEVERE ||
type == HealthDataType.HEADACHE_UNSPECIFIED) {
value = _alignValue(type).toDouble();
}
Map<String, dynamic> args = {
'value': value,
'dataTypeKey': type.name,
'dataUnitKey': unit.name,
'startTime': startTime.millisecondsSinceEpoch,
'endTime': endTime.millisecondsSinceEpoch
};
bool? success = await _channel.invokeMethod('writeData', args);
return success ?? false;
}