writeHealthData method

Future<bool> writeHealthData(
  1. double value,
  2. HealthDataType type,
  3. DateTime startTime,
  4. DateTime endTime, {
  5. HealthDataUnit? unit,
})

Saves health data into Apple Health or Google Fit.

Returns true if successful, false otherwise.

Parameters:

  • value - the health data's value in double
  • type - the value's HealthDataType
  • startTime - the start time when this value is measured.
    • It must be equal to or earlier than endTime.
  • endTime - the end time when this value is measured.
    • It must be equal to or later than startTime.
    • Simply set endTime equal to startTime if the value is measured only at a specific point in time.

Values for Sleep and Headache are ignored and will be automatically assigned the coresponding value.

Implementation

Future<bool> writeHealthData(
  double value,
  HealthDataType type,
  DateTime startTime,
  DateTime endTime, {
  HealthDataUnit? unit,
}) async {
  if (type == HealthDataType.WORKOUT)
    throw ArgumentError(
        "Adding workouts should be done using the writeWorkoutData method.");
  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))
    throw ArgumentError(
        "$type - iOS doesnt 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.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.typeToString(),
    'dataUnitKey': unit.typeToString(),
    'startTime': startTime.millisecondsSinceEpoch,
    'endTime': endTime.millisecondsSinceEpoch
  };
  bool? success = await _channel.invokeMethod('writeData', args);
  return success ?? false;
}