Skip to content
CARP Docs
Ask AISystemLightDark
On this page

You are reading the docs for Health 13.x, an older version. Go to 14.x, the latest version.

Numeric data

Write numeric health data such as weight, vital signs, blood glucose and activity metrics using writeHealthData.

Copy MarkdownOpen inOpen in GitHubView as MarkdownOpen in Scira AIOpen in ChatGPTOpen in ClaudeOpen in Cursor

writeHealthData writes a single numeric value of a given type. Request WRITE permission for the type first; see Request write permission.

Signature

Future<bool> writeHealthData({
  required double value,
  HealthDataUnit? unit,
  required HealthDataType type,
  required DateTime startTime,
  String? clientRecordId,
  double? clientRecordVersion,
  DateTime? endTime,
  RecordingMethod recordingMethod = RecordingMethod.automatic,
})
ParameterTypeRequiredDefaultDescription
valuedoubleYes—Numeric value to write
unitHealthDataUnitNoThe type's default unitUnit of value (iOS only)
typeHealthDataTypeYes—Type of health data
startTimeDateTimeYes—When the measurement was taken
clientRecordIdStringNo—Your own ID for the record (Android only). The plugin ignores it without clientRecordVersion.
clientRecordVersiondoubleNo—Version of the record with this clientRecordId (Android only), saved as a whole number
endTimeDateTimeNostartTimeEnd time (for duration-based metrics)
recordingMethodRecordingMethodNoRecordingMethod.automaticHow the data was recorded. On iOS, it must be manual or automatic; see Set the recording method.

Pass value in the type's default unit; see Data types. On iOS, you can pass another unit in unit, which Android ignores. The unit must fit the type, for example a mass unit for WEIGHT: for any other unit, HealthKit throws an exception and the app crashes.

Return value

  • true: the data was written.
  • false: the platform did not save the data, for example because WRITE permission is missing. On Android, writeHealthData also returns false for types it cannot write, such as BODY_MASS_INDEX and the blood pressure types.

Invalid calls and values that Health Connect rejects throw an exception instead; see Error handling.

Supported data types

Body measurements

// Weight
await health.writeHealthData(
  value: 70.5,
  type: HealthDataType.WEIGHT,
  startTime: DateTime.now(),
);

// Height
await health.writeHealthData(
  value: 1.75, // m
  type: HealthDataType.HEIGHT,
  startTime: DateTime.now(),
);

// Body Fat Percentage
await health.writeHealthData(
  value: Platform.isIOS ? 0.185 : 18.5, // 18.5%
  type: HealthDataType.BODY_FAT_PERCENTAGE,
  startTime: DateTime.now(),
);

// BMI (iOS only)
await health.writeHealthData(
  value: 23.0,
  type: HealthDataType.BODY_MASS_INDEX,
  startTime: DateTime.now(),
);

On Android, writeHealthData returns false for BODY_MASS_INDEX: Health Connect has no BMI record. On iOS, HealthKit measures percentages from 0.0 to 1.0, so 0.185 is 18.5%.

Vital signs

// Heart Rate
await health.writeHealthData(
  value: 72.0,
  type: HealthDataType.HEART_RATE,
  startTime: DateTime.now(),
);

// Resting Heart Rate
await health.writeHealthData(
  value: 60.0,
  type: HealthDataType.RESTING_HEART_RATE,
  startTime: DateTime.now(),
);

// Body Temperature
await health.writeHealthData(
  value: 36.8,
  type: HealthDataType.BODY_TEMPERATURE,
  startTime: DateTime.now(),
);

// Respiratory Rate
await health.writeHealthData(
  value: 16.0,
  type: HealthDataType.RESPIRATORY_RATE,
  startTime: DateTime.now(),
);

Blood metrics

// Blood Glucose
await health.writeHealthData(
  value: 95.0, // mg/dL
  type: HealthDataType.BLOOD_GLUCOSE,
  startTime: DateTime.now(),
);

// Electrodermal Activity (iOS only)
await health.writeHealthData(
  value: 0.0000025, // siemens (2.5 µS)
  type: HealthDataType.ELECTRODERMAL_ACTIVITY,
  startTime: DateTime.now(),
);

For blood pressure and blood oxygen, use the dedicated methods in Blood pressure and oxygen.

Activity metrics

Activity metrics cover a duration, so pass both startTime and endTime:

// Steps
await health.writeHealthData(
  value: 1000.0,
  type: HealthDataType.STEPS,
  startTime: DateTime.now().subtract(Duration(hours: 1)),
  endTime: DateTime.now(),
);

// Distance (Android only)
await health.writeHealthData(
  value: 2500.0, // meters
  type: HealthDataType.DISTANCE_DELTA,
  startTime: DateTime.now().subtract(Duration(hours: 1)),
  endTime: DateTime.now(),
);

// Active Energy Burned
await health.writeHealthData(
  value: 150.0, // kcal
  type: HealthDataType.ACTIVE_ENERGY_BURNED,
  startTime: DateTime.now().subtract(Duration(hours: 1)),
  endTime: DateTime.now(),
);

// Flights Climbed
await health.writeHealthData(
  value: 5.0,
  type: HealthDataType.FLIGHTS_CLIMBED,
  startTime: DateTime.now().subtract(Duration(hours: 1)),
  endTime: DateTime.now(),
);

On Android, these types must end after they start: otherwise, the write throws a PlatformException. DISTANCE_DELTA exists only on Android; on iOS, write distance as DISTANCE_WALKING_RUNNING, DISTANCE_CYCLING or DISTANCE_SWIMMING.

Set a client record ID (Android)

writeHealthData has no source parameters: Health Connect and HealthKit record your app as the source. On Android, pass clientRecordId and clientRecordVersion to give the record your own ID:

await health.writeHealthData(
  value: 70.5,
  type: HealthDataType.WEIGHT,
  startTime: DateTime.now(),
  clientRecordId: 'my-smart-scale-0001',
  clientRecordVersion: 1,
);

When you write the same ID again, Health Connect keeps the record with the highest version. iOS ignores both parameters.

Set a time range

For duration-based measurements, pass the start and end of the period:

// Steps during a specific hour
await health.writeHealthData(
  value: 1500.0,
  type: HealthDataType.STEPS,
  startTime: DateTime(2024, 1, 15, 14, 0), // 2:00 PM
  endTime: DateTime(2024, 1, 15, 15, 0),   // 3:00 PM
);

// Calories burned during workout
await health.writeHealthData(
  value: 250.0,
  type: HealthDataType.ACTIVE_ENERGY_BURNED,
  startTime: workoutStart,
  endTime: workoutEnd,
);

Set the recording method

recordingMethod says how the data was recorded: automatic (the default), manual, active or unknown. On iOS, it must be manual or automatic, and the plugin sets HKMetadataKeyWasUserEntered to true for manual:

final measurementTime = DateTime(2024, 1, 15, 8, 0); // Morning measurement

await health.writeHealthData(
  value: 70.5,
  type: HealthDataType.WEIGHT,
  startTime: measurementTime,
  recordingMethod: RecordingMethod.manual, // entered by the user
);

Known issue

On Android, the plugin saves RecordingMethod.manual as actively recorded and RecordingMethod.active as manual entry. A record written with manual reads back as active. To save a manual entry on Android, pass RecordingMethod.active.

Example: weight tracker

This class checks WRITE permission, requests it if needed and then writes the weight:

class WeightTracker {
  final Health health;
  
  WeightTracker(this.health);
  
  Future<bool> saveWeight({
    required double weightKg,
    DateTime? measurementTime,
  }) async {
    // Request permission if needed
    final hasPermission = await health.hasPermissions(
      [HealthDataType.WEIGHT],
      permissions: [HealthDataAccess.WRITE],
    );
    
    if (hasPermission != true) {
      final granted = await health.requestAuthorization(
        [HealthDataType.WEIGHT],
        permissions: [HealthDataAccess.WRITE],
      );
      
      if (!granted) {
        return false;
      }
    }
    
    // Write the weight
    return await health.writeHealthData(
      value: weightKg,
      type: HealthDataType.WEIGHT,
      startTime: measurementTime ?? DateTime.now(),
    );
  }
}

// Usage
final tracker = WeightTracker(health);
final success = await tracker.saveWeight(weightKg: 70.5);

if (success) {
  print('Weight saved!');
} else {
  print('Failed to save weight');
}

Validate before writing

Validate values in your app before you write them:

Future<bool> writeValidatedWeight(double weightKg, DateTime time) async {
  // Validate weight range
  if (weightKg < 20 || weightKg > 300) {
    print('Invalid weight: $weightKg kg');
    return false;
  }
  
  // Validate timestamp (not in future)
  final now = DateTime.now();
  if (time.isAfter(now)) {
    print('Measurement time is in the future');
    return false;
  }
  
  return await health.writeHealthData(
    value: weightKg,
    type: HealthDataType.WEIGHT,
    startTime: time,
  );
}

Error handling

writeHealthData throws instead of returning false in these cases:

ExceptionWhen
UnsupportedErrorHealth Connect is not available (Android).
HealthExceptionThe type does not exist on the platform, such as ELECTRODERMAL_ACTIVITY on Android or DISTANCE_DELTA on iOS.
ArgumentErrorThe start time is after the end time, or the type is WORKOUT or ACTIVITY_INTENSITY. On iOS, also when recordingMethod is not manual or automatic, or when the type is ELECTROCARDIOGRAM or a heart rate event type.
PlatformExceptionHealth Connect rejects the value or the time range (Android), for example a HEIGHT over 3 m or STEPS that do not end after they start.
Future<void> saveHealthMetric(double value, HealthDataType type) async {
  try {
    final success = await health.writeHealthData(
      value: value,
      type: type,
      startTime: DateTime.now(),
    );
    
    if (success) {
      print('✓ ${type.name} saved');
    } else {
      print('✗ Failed to save ${type.name}');
      print('  Check permissions or platform availability');
    }
  } catch (e) {
    print('✗ Error saving ${type.name}: $e');
  }
}

Platform differences

AndroidiOS
  • Requires the Health Connect SDK.
  • Throws an UnsupportedError if Health Connect is not available. Call isHealthConnectAvailable() before writing; see Health Connect.
  • Some types may have platform-specific limitations.
  • Takes percent values as fractions: 0.185 is 18.5%.
  • Data appears immediately in the Health app.
  • Without READ permission, reads return only the data your app wrote.
  • Converts units automatically (for example, between kg and lbs).

Quick links

Page · DocumentationCARP DocumentationPage · DocumentationIntroductionPage · DocumentationQuickstartPage · DocumentationTerminologyPage · DocumentationArchitecture