Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Upgrading from 13.x

Update an app from health 13.x to 14.0.0 for the new SDK requirements, exceptions and changed return values.

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

health 14.0.0 raises the SDK requirements, throws exceptions where 13.x returned no data, and changes what several methods return. Each section below shows what to change in 13.x code and links the page that documents the new behavior. The 13.x docs describe the previous version.

What to change depends on the APIs the app uses:

AreaWhat changes
Flutter and the pluginDart 3.12 or later and Flutter 3.44 or later. See Update Flutter and the plugin.
Android buildcompileSdk 37 or later, Android Gradle plugin (AGP) 9.1.0 or later and Gradle 9.3.1 or later. See Update the Android build.
Read errorsReads throw a HealthPlatformException where 13.x returned an empty list or null. See Handle read errors.
Step totalsgetTotalStepsInInterval() returns an int and throws on errors. See Update step totals.
Aggregate readsgetHealthAggregateDataFromTypes() throws an UnsupportedError. See Replace aggregate reads.
Interval readsIntervals without data are left out, and every value is a NumericHealthValue. See Update interval reads.
Sleep stages (Android)Reads return the stages that start in the time range. See Update sleep stage reads (Android).
TOTAL_CALORIES_BURNEDRemoved from iOS. See Replace TOTAL_CALORIES_BURNED (iOS).
Data pointssourceDeviceId and deviceModel hold values, so points read with 14.0.0 do not equal points stored with 13.x. See Match stored data points.
WorkoutsOn Android, the totals count only the records of the app that wrote the workout. See Update workout code.
Writes and deletesSeveral writes throw before the platform is called, and delete() on iOS removes only the given sleep or headache type. See Update writes and deletes.
Preferred units (Android)A unit that Android does not convert to throws a HealthException. See Check preferred units (Android).
Audiograms (iOS)A threshold is null where an ear was not tested. See Handle untested audiogram frequencies (iOS).
Fakes and testsClasses that implement Health or HealthException need the new members. See Update fakes and tests.

Update Flutter and the plugin

health 14.0.0 requires Dart 3.12 or later and Flutter 3.44 or later. iOS 15.0 or later has been required since 13.3.2. Upgrade Flutter, then raise the version constraint:

flutter pub add "health:^14.0.0"

With an older Flutter SDK, the command fails: pub cannot resolve 14.0.0.

Update the Android build

health 14.0.0 uses androidx.health.connect:connect-client 1.2.0-alpha06, which requires compileSdk 37 or later and AGP 9.1.0 or later. With a lower API level or AGP version, the build fails in the Android Archive (AAR) metadata check of connect-client. Flutter's flutter.compileSdkVersion is 36, so set the API level in the app:

android/app/build.gradle.kts
android {
    compileSdk = flutter.compileSdkVersion 
    compileSdk = 37
    // ...
}

Set AGP to 9.1.0 or later:

android/settings.gradle.kts
plugins {
    id("com.android.application") version "9.1.0" apply false
    // ...
}

AGP 9.1.0 requires Gradle 9.3.1 or later with every Flutter version, so raise the Gradle wrapper too:

android/gradle/wrapper/gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip

The plugin no longer applies the Kotlin Gradle plugin. The Kotlin Gradle plugin that Flutter applies compiles its Kotlin code when the app sets android.builtInKotlin=false, as Flutter's app templates do. With android.builtInKotlin=true, AGP's built-in Kotlin compiles it, which needs Flutter 3.47 or later: Flutter 3.44 applies the Kotlin Gradle plugin to every plugin, and AGP then fails the build. Flutter 3.47 also fails the build with Kotlin older than 2.2.20, and Flutter 3.44 warns.

See Installation.

Handle read errors

In 13.x, Android reads returned an empty list when Health Connect reported an error, and getChangesToken() and getChanges() returned null. In 14.0.0, they throw a HealthPlatformException.

iOS reads threw a PlatformException in 13.x; in 14.0.0, it is a HealthPlatformException with a classified errorCode, such as deviceLocked. An empty list now means only that there is no data the app may read.

Catch the exception where the app reads:

try {
  final points = await health.getHealthDataFromTypes(types: types, startTime: start, endTime: end);
} on HealthPlatformException catch (e) {
  if (e.isRetryable) {
    // For example HealthErrorCode.rateLimitExceeded: try again later.
  } else if (e.errorCode == HealthErrorCode.permissionDenied) {
    // Ask for the permission.
  }
  // e.platformCode is the native code, e.details holds more information.
} on HealthException catch (e) {
  // For example a type that is not available on this platform (HealthErrorCode.notSupported).
}

HealthPlatformException extends PlatformException and implements HealthException, so existing on PlatformException and on HealthException clauses keep catching these errors. Put on HealthPlatformException before on PlatformException, or the earlier clause catches it. Without READ permission, a read is not an error: it returns only the data the app wrote itself.

On Android, a type that the device's Health Connect does not have now throws a HealthException with HealthErrorCode.notSupported before Health Connect is called. For example, ACTIVITY_INTENSITY needs Android 16, or Android 14 or 15 with SDK extension 16: check isActivityIntensityAvailable() first. See Error handling.

Update step totals

getTotalStepsInInterval() returns Future<int> instead of Future<int?>, and the count is 0 when there are no steps. Where 13.x returned null on Android, 14.0.0 throws a HealthPlatformException, for example with permissionDenied without READ permission for STEPS. Remove the null handling:

final steps = await health.getTotalStepsInInterval(start, end);
print('Steps: ${steps ?? 0}');
print('Steps: $steps');

The analyzer warns about ?? 0 and null checks on the result, which can no longer be null. See Step totals.

Replace aggregate reads

getHealthAggregateDataFromTypes() is deprecated and throws an UnsupportedError without calling the platform. It did not work in 13.x either: iOS had no implementation of it, and on Android the call failed. Replace each use with the read that fits:

13.x aggregate readReplacement
Workouts and their totalsgetHealthDataFromTypes() with WORKOUT. See Read workouts.
Sums and averages of other typesgetHealthIntervalDataFromTypes(). See Read sums and averages.
activitySegmentDurationNone. For time buckets, use the interval of getHealthIntervalDataFromTypes(), in seconds.
includeManualEntry: falserecordingMethodsToFilter: [RecordingMethod.manual]. On Android, interval reads apply it only to sleep types. For a step total, use getTotalStepsInInterval() with includeManualEntry: false.

For the 13.x examples, see Aggregate data.

Read workouts

Read WORKOUT data points with getHealthDataFromTypes(). The value of each point is a WorkoutHealthValue with the workout's activity type and totals, so the 13.x workout examples need only the new call:

final data = await health.getHealthAggregateDataFromTypes( 
final data = await health.getHealthDataFromTypes( 
  types: [HealthDataType.WORKOUT],
  startDate: start,
  endDate: end,
  startTime: start,
  endTime: end,
);

for (var point in data) {
  final workout = point.value as WorkoutHealthValue;
  print('Workout: ${workout.workoutActivityType.name}');
  print('Duration: ${point.dateTo.difference(point.dateFrom)}');
}

Remove activitySegmentDuration from the call, and replace includeManualEntry: false with recordingMethodsToFilter: [RecordingMethod.manual].

Leave TOTAL_CALORIES_BURNED and DISTANCE_WALKING_RUNNING out of a workout read: each exists on one platform only. A read with a type that the platform does not have throws a HealthException.

On Android, the totals count only the records of the app that wrote the workout. See Update workout code.

Read sums and averages

Read the other types of a 13.x aggregate call with getHealthIntervalDataFromTypes(). It sums cumulative types, such as steps, and averages most others, such as heart rate. For example, the steps and the average heart rate per hour:

List<HealthDataPoint> hourly = await health.getHealthIntervalDataFromTypes(
  types: [HealthDataType.STEPS, HealthDataType.HEART_RATE],
  startDate: now.subtract(Duration(days: 1)),
  endDate: now,
  interval: 3600,
);

Use the distance type of each platform: DISTANCE_DELTA on Android and DISTANCE_WALKING_RUNNING on iOS. WORKOUT has no intervals.

For one total over the whole range, set interval to the length of the range in seconds, rounded up. See Interval data.

Update interval reads

getHealthIntervalDataFromTypes() returns its data points differently in 14.0.0:

13.x14.0.0
Intervals without dataA point with the value 0 on AndroidNo point, on both platforms
Value typeSkinTemperatureHealthValue for SKIN_TEMPERATURE, and an empty list for ACTIVITY_INTENSITY on AndroidA NumericHealthValue for every type
HEART_RATE on AndroidThe number of samplesThe average beats per minute
Sleep typesFailedThe minutes of the interval that the type covers, with overlapping data counted once

Code that expects one point per interval, such as a chart with a bar for every day, must fill the gaps itself. See Interval data.

Update sleep stage reads (Android)

On Android, getHealthDataFromTypes() and getHealthDataPages() return a sleep stage, such as SLEEP_DEEP, when the stage starts in the time range, as on iOS. In 13.x, getHealthDataFromTypes() returned every stage of the sessions that started in the range.

The read also finds the stages of sessions that started up to 24 hours before startTime, and SLEEP_SESSION reads are unchanged. See Data points.

Replace TOTAL_CALORIES_BURNED (iOS)

health 14.0.0 removes TOTAL_CALORIES_BURNED from iOS, because HealthKit has no total calories type. On iOS, reading or writing it throws a HealthException with HealthErrorCode.notSupported before HealthKit is called. Use ACTIVE_ENERGY_BURNED and BASAL_ENERGY_BURNED on iOS instead:

final types = health.isDataTypeAvailable(HealthDataType.TOTAL_CALORIES_BURNED)
    ? [HealthDataType.TOTAL_CALORIES_BURNED]
    : [HealthDataType.ACTIVE_ENERGY_BURNED, HealthDataType.BASAL_ENERGY_BURNED];

isDataTypeAvailable() tells whether the platform has a type. See Data types.

Match stored data points

In 13.x, sourceDeviceId was always 'unknown' and deviceModel was always null. In 14.0.0, sourceDeviceId is set from the phone that read the point: Build.ID on Android and identifierForVendor on iOS. deviceModel is the model of the device that recorded the data, or null when the writing app reported none.

Both fields take part in == and in removeDuplicates(). A point that 14.0.0 reads therefore does not equal the same point that the app stored with 13.x.

== now also compares the contents of metadata. In 13.x, a point with metadata, such as every iOS sample, never equaled the same data read again.

To match points across the two versions, compare type, uuid and dateFrom:

final seen = <(HealthDataType, String, DateTime)>{};
points = points.where((p) => seen.add((p.type, p.uuid, p.dateFrom))).toList();

The HealthDataPoint constructor and HealthDataPoint.fromJson() now keep the value passed to them for sleep, headache and mindfulness types. In 13.x, they replaced it with the duration in minutes.

When the app constructs such a point, pass the minutes as its value. See Data points.

Update workout code

Workout reads and writes change in 14.0.0:

13.x14.0.0
Totals on AndroidThe records of every app during the workoutThe records of the app that wrote the workout, or null when that app wrote none
Missing READ permission for a total (Android)The workout was left outThe total is null; for a workout that the app wrote, WRITE permission is enough
workoutSummary on AndroidnullSet, with 0 for a missing total
WorkoutSummary.workoutType on iOSHealthKit's name, such as cyclingThe HealthWorkoutActivityType name, such as BIKING
Workout types that share a platform typeOn Android, a name that depended on the read method; on iOS, a name picked at random at each app launchOne name, such as DANCING for SOCIAL_DANCE on Android and CLIMBING for ROCK_CLIMBING on iOS
Writing a workout type that the platform does not havefalse on Android for ARCHERY, CURLING and WALKING_TREADMILL, and a HealthException for the other typesA HealthException with HealthErrorCode.notSupported

To count the data of every app during a workout on Android, read DISTANCE_DELTA, TOTAL_CALORIES_BURNED or STEPS over the workout's time range. For the names that each platform reads back, see Workout types. For writing workouts, see Workouts.

Update writes and deletes

Several writes and deletes behave differently in 14.0.0:

13.x14.0.0
writeHealthData() with INSULIN_DELIVERY or MENSTRUATION_FLOW (iOS)Crashed the appAn ArgumentError: use writeInsulinDelivery() or writeMenstruationFlow()
WRITE access to a read-only HealthKit typeAn ArgumentError for some types, a crash or false for othersAn ArgumentError for all 14 types, from requestAuthorization() and from writes
A value that Health Connect rejects, such as 0 steps (Android)A PlatformExceptionwriteHealthData() returns false, and writeHealthDataUUID() an empty string
delete() with a sleep type or headache severity (iOS)Deleted the app's samples of every sleep or headache typeDeletes the app's samples of that type only

writeHealthDataUUID() now throws an ArgumentError for every type with a write method of its own, as writeHealthData() does. These are WORKOUT, ACTIVITY_INTENSITY, the new SEXUAL_ACTIVITY and, on iOS, INSULIN_DELIVERY and MENSTRUATION_FLOW. See Writing data and Deleting data.

Check preferred units (Android)

In 13.x, a preferredUnits entry with a unit that Android does not convert to labeled the values with that unit without converting them. In 14.0.0, such an entry throws a HealthException with HealthErrorCode.invalidArgument before anything is read. Besides the default unit of each type, Android converts only to these units:

TypeUnits
WEIGHTPOUND
HEIGHTCENTIMETER, INCH
BODY_TEMPERATURE, SKIN_TEMPERATUREDEGREE_FAHRENHEIT, KELVIN
BLOOD_GLUCOSEMILLIMOLES_PER_LITER

See Data types for the default unit of each type.

Handle untested audiogram frequencies (iOS)

AudiogramHealthValue.leftEarSensitivities and rightEarSensitivities are List<num?> instead of List<num>: an entry is null where that ear was not tested at the frequency. In 13.x, reading such an audiogram crashed the app.

Skip the null entries before you calculate with the thresholds, for example with whereType<num>(). See Data points.

Update fakes and tests

Health is now made of public mixins, such as HealthDataReads and HealthPermissions, and the API reference documents each method on its mixin. A class that implements Health or HealthException must implement the members that 14.0.0 adds, such as pageSize, isolateMode, getHealthDataPages(), errorCode, platformCode and details.

Reads call the native method getDataPage. A method channel mock that answers only getData keeps working. When the first getDataPage call is not implemented, the plugin reads the type with one getData call.

In widget tests, the default HealthIsolateMode.auto parses replies inline under flutter test; with HealthIsolateMode.worker, wrap the read in tester.runAsync(). See Data pages.

For everything else that 14.0.0 adds and fixes, see Changelog.

Quick links

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