Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Change tracking

Sync the records added, updated or deleted in Health Connect since your last read using getChangesToken and getChanges.

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

getChangesToken and getChanges track the changes in Health Connect: the records that apps added, updated or deleted after a point in time. Instead of reading a range again, an app fetches only what changed, which saves Health Connect API quota. Change tracking is Android only; on iOS, both methods return null.

getChangesToken

Future<String?> getChangesToken({required List<HealthDataType> types})
ParameterTypeRequiredDescription
typesList<HealthDataType>YesData types to track; must not be empty

getChangesToken returns a changes token: a string that marks the present moment in the change history of types. getChanges returns the changes after that moment. On iOS, the method returns null.

Some types are tracked through the Health Connect record type that holds their data, so their changes come as data points of another type:

Type in typesChanges come as
BODY_MASS_INDEXWEIGHT and HEIGHT data points
WORKOUT_ROUTEWORKOUT data points
Any sleep type, such as SLEEP_DEEPSLEEP_SESSION data points
BLOOD_PRESSURE_SYSTOLIC or BLOOD_PRESSURE_DIASTOLICA BLOOD_PRESSURE_SYSTOLIC and a BLOOD_PRESSURE_DIASTOLIC data point per record

One token per data type

Use a separate token for each data type that the app syncs on its own, as Google's guide to syncing data with Health Connect recommends. When the user revokes the permission of one type, only the token of that type then fails.

getChanges

Future<HealthChangesResponse?> getChanges({
  required String changesToken,
  bool includeSelf = false,
})
ParameterTypeRequiredDefaultDescription
changesTokenStringYes—The token from getChangesToken, or the nextChangesToken of the previous call; must not be empty
includeSelfboolNofalseWhether to include the records that this app added or updated

getChanges returns the next page of changes after changesToken, with the token for the next call. On iOS, the method returns null.

By default, getChanges leaves out the records that this app added or updated, as the app knows its own writes. Deletions always come, as Health Connect does not say which app deleted a record.

Return value

getChanges returns a HealthChangesResponse with these fields:

FieldTypeDescription
changesList<HealthChange>The changes in this page, in the order Health Connect reports them
nextChangesTokenStringThe token for the next call
hasMoreboolWhether more changes are waiting; call getChanges again with nextChangesToken
changesTokenExpiredboolWhether the token can no longer be used; see Handle an expired token
upsertedDataPointsList<HealthDataPoint>The data points of the added or updated records
deletedRecordIdsList<String>The IDs of the deleted records

Each HealthChange in changes has these fields:

FieldTypeDescription
typeHealthChangeTypeupsert for a record that was added or updated, delete for a deleted record
dataPointHealthDataPoint?The data point of an upsert; null for a deletion
dataTypeHealthDataType?The type of dataPoint; null for a deletion
recordIdString?The Health Connect ID of the deleted record; null for an upsert
rawDataPointMap<String, dynamic>?The data point of an upsert as the platform sent it; null for a deletion

An upsert holds a data point as a read returns it, with the Health Connect ID of its record as uuid. A WORKOUT data point comes without its route, and without its totals, which are records of their own. A deletion holds only the record ID: Health Connect does not say the type of a deleted record.

Sync changes

Create the token before you read the data that the app keeps, and store it. Changes made while you read then come with the first getChanges call instead of being missed.

To sync, pass the stored token to getChanges, apply the changes and store nextChangesToken for the next sync. While hasMore is true, more changes are waiting.

One call, as in the example app, where localStore maps record IDs to data points:

final token = await health.getChangesToken(types: [HealthDataType.STEPS, HealthDataType.WORKOUT]);
if (token != null) {
  final response = await health.getChanges(changesToken: token);
  if (response != null) {
    for (final change in response.changes) {
      if (change.type == HealthChangeType.delete) {
        localStore.remove(change.recordId);
      } else if (change.dataPoint case final point?) {
        localStore[point.uuid] = point;
      }
    }
    final nextToken = response.nextChangesToken; // store it for the next call
  }
}

An upserted data point carries the record ID as uuid, and the deletion of the record as recordId. Both find the same entry in localStore.

A record of a series type, such as heart rate, comes as one data point per sample, and a blood pressure record as two. All of them share the record's uuid. To track such types, keep all data points of a record under its ID, as synced_records.dart in the example app does.

The token moves on with every call. When a call fails, call getChanges again later with the same token.

Handle an expired token

changesTokenExpired is true when the token can no longer be used:

  • Health Connect expires a token that is not used within 30 days;
  • Health Connect cannot return the pending changes because they are too many;
  • one change holds more than 100,000 data points.

In the last two cases, the plugin returns an expired response instead of throwing. A call with the same token would fail the same way. To keep the batches of changes small, sync often.

Create a new token, read the data since your last sync again and use the new token from then on. Do not store the nextChangesToken of an expired response.

For reading a long range again, see Data pages.

Examples

Keep a local copy in sync

This function applies the changes to a map of data points keyed by record ID, and returns the token for the next sync:

/// The steps and workouts read from Health Connect, by record ID
final localStore = <String, HealthDataPoint>{};

/// Applies the changes since [token] to [localStore] and returns the token
/// for the next sync, or null if the token expired
Future<String?> syncChanges(String token) async {
  // Each call counts against the Health Connect API quota: stop after 20
  for (var calls = 0; calls < 20; calls++) {
    final response = await health.getChanges(changesToken: token);
    // null on iOS
    if (response == null || response.changesTokenExpired) return null;

    for (final change in response.changes) {
      if (change.type == HealthChangeType.delete) {
        localStore.remove(change.recordId);
      } else if (change.dataPoint case final point?) {
        localStore[point.uuid] = point;
      }
    }

    token = response.nextChangesToken;
    if (!response.hasMore) break;
  }
  return token;
}

After 20 calls, the returned token keeps the place, and the next sync goes on from there. When syncChanges returns null, create a new token and read the data again. If a call throws, the stored token stays as it was, and the next sync applies some changes again, which localStore absorbs.

Error handling

ExceptionMethodWhen
ArgumentErrorBothtypes or changesToken is empty.
HealthException with notSupportedgetChangesTokenA type is not available on Android or on this device, such as MINDFULNESS without the Health Connect feature. The plugin throws it before Health Connect is called.
UnsupportedErrorBothHealth Connect is not available on the device.
HealthPlatformExceptionBothHealth Connect reports an error, for example rateLimitExceeded when the API quota is used up.

Too many changes do not throw: getChanges returns changesTokenExpired: true instead. When the user revokes the READ permission of a type that the token tracks, the call may fail with permissionDenied. After a retryable error, call getChanges again later with the same token:

try {
  final response = await health.getChanges(changesToken: token);
  if (response != null && !response.changesTokenExpired) {
    // ... apply response.changes and store response.nextChangesToken
  }
} on HealthPlatformException catch (e) {
  if (e.isRetryable) {
    // For example rateLimitExceeded: try again later with the same token
  }
}

For every error code and what it means, see Error handling.

Platform differences

AndroidiOS
  • Each getChanges call counts against the Health Connect API quota. A page of more than 100,000 data points is read again with fewer changes, at one more call each time.
  • Health Connect expires a token that is not used within 30 days.
  • Syncing in the background needs READ_HEALTH_DATA_IN_BACKGROUND.
  • The app's own additions and updates come only with includeSelf: true.
  • getChangesToken and getChanges return null without calling HealthKit.
  • They do not throw, also not for an empty types list or token.
  • To sync, read the data since your last sync again, for example with getHealthDataPages.
  • Store the points with an upsert keyed by type, uuid and dateFrom, so that points read twice are stored once.

Quick links

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