Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Workout routes

Record the GPS route of a workout using startWorkoutRoute, insertWorkoutRouteData, finishWorkoutRoute and discardWorkoutRoute.

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

startWorkoutRoute, insertWorkoutRouteData, finishWorkoutRoute and discardWorkoutRoute record the GPS route of a workout. startWorkoutRoute opens a route builder, which collects locations while the workout runs. finishWorkoutRoute then attaches the locations to the written workout, and discardWorkoutRoute drops them.

Routes work on both platforms. Health Connect saves a route as part of the workout's exercise session; HealthKit saves it as a sample of its own, linked to the workout.

startWorkoutRoute

Future<String> startWorkoutRoute()

startWorkoutRoute opens a route builder and returns its id, which the other route methods take. The builder stays open until you finish or discard it.

insertWorkoutRouteData

Future<bool> insertWorkoutRouteData({
  required String builderId,
  required List<WorkoutRouteLocation> locations,
})
ParameterTypeRequiredDescription
builderIdStringYesThe id that startWorkoutRoute returned
locationsList<WorkoutRouteLocation>YesThe locations to add, in ascending time order

insertWorkoutRouteData adds a batch of locations to an open builder and returns true when they were added. Call it as often as the app collects locations.

A WorkoutRouteLocation has these fields:

FieldTypeRequiredDescription
latitudedoubleYesDegrees, from -90 to 90
longitudedoubleYesDegrees, from -180 to 180
timestampDateTimeYesWhen the location was recorded
altitudedouble?NoMeters above sea level
horizontalAccuracydouble?NoAccuracy of the position, in meters
verticalAccuracydouble?NoAccuracy of the altitude, in meters
speeddouble?NoSpeed in meters per second (iOS only)
coursedouble?NoHeading in degrees (iOS only)
speedAccuracydouble?NoAccuracy of the speed, in meters per second (iOS only)
courseAccuracydouble?NoAccuracy of the heading, in degrees (iOS only)

On Android, a location outside these ranges, or with a negative accuracy, throws a PlatformException with code INVALID_ARGUMENT.

finishWorkoutRoute

Future<String> finishWorkoutRoute({
  required String builderId,
  required String workoutUuid,
  Map<String, dynamic>? metadata,
})
ParameterTypeRequiredDescription
builderIdStringYesThe id that startWorkoutRoute returned
workoutUuidStringYesThe UUID of the workout, which writeWorkoutDataUUID returns
metadataMap<String, dynamic>?NoMetadata of the route (iOS only)

finishWorkoutRoute attaches the builder's locations to a workout that is already written, and closes the builder. It returns a UUID. On Android, this is the workout's UUID, as the route is part of the workout; on iOS, it is the UUID of the new route.

On Android, the plugin rewrites the workout's exercise session with the route and keeps the session's other fields. Every location must be at or after the workout's start and before its end. Without locations, no route is written.

On iOS, HealthKit saves metadata on the route, together with the workout's UUID under workout_uuid.

discardWorkoutRoute

Future<bool> discardWorkoutRoute(String builderId)

discardWorkoutRoute closes a builder without saving its locations, for example when the user cancels the workout or a step fails. It returns true when the builder was discarded. On Android it returns true even for a builder that is not open, while iOS returns false.

Request permissions

A route belongs to a workout, so request access to WORKOUT_ROUTE together with WORKOUT:

final types = [HealthDataType.WORKOUT, HealthDataType.WORKOUT_ROUTE];

final granted = await health.requestAuthorization(
  types,
  permissions: List.filled(types.length, HealthDataAccess.READ_WRITE),
);

On Android, WRITE for WORKOUT_ROUTE asks for WRITE_EXERCISE_ROUTE and WRITE_EXERCISE, and READ asks for READ_EXERCISE. Declare these permissions, and READ_EXERCISE_ROUTES to read the routes of other apps. The app also needs a location permission to collect the locations:

android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.health.READ_EXERCISE" />
    <uses-permission android:name="android.permission.health.WRITE_EXERCISE" />
    <uses-permission android:name="android.permission.health.READ_EXERCISE_ROUTES" />
    <uses-permission android:name="android.permission.health.WRITE_EXERCISE_ROUTE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- ... the rest of your manifest -->
</manifest>

requestAuthorization does not request READ_EXERCISE_ROUTES. The user grants it in the Health Connect app, under App permissions, by setting Exercise routes to Always allow for the app. Without it, another app's route reads as a WORKOUT_ROUTE data point without locations, whose metadata has route_requires_consent: true.

The plugin does not collect locations: the app records them, which needs the platform's location permission. On Android, that is ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION; on iOS, it is Core Location authorization. Workouts without a route need no location permission.

Record a route

Recording a route takes four steps:

  1. Open a route builder

    When the workout starts, open a builder and keep its id:

    final builderId = await health.startWorkoutRoute();
  2. Add the locations

    While the workout runs, add the locations that the app collects, in batches in ascending time order:

    await health.insertWorkoutRouteData(
      builderId: builderId,
      locations: [
        WorkoutRouteLocation(
          latitude: 37.334900,
          longitude: -122.009020,
          timestamp: DateTime.now(),
          altitude: 10,
          horizontalAccuracy: 5,
          verticalAccuracy: 8,
        ),
      ],
    );
  3. Write the workout

    When the workout ends, write it with writeWorkoutDataUUID, which returns its UUID, or an empty string when the workout was not saved:

    final workoutUuid = await health.writeWorkoutDataUUID(
      activityType: HealthWorkoutActivityType.WALKING,
      start: start,
      end: end,
    ) ?? '';
  4. Attach the route

    Finish the route for the workout's UUID:

    final routeUuid = await health.finishWorkoutRoute(
      builderId: builderId,
      workoutUuid: workoutUuid,
    );

    If workoutUuid is empty, or the user cancels the workout, call discardWorkoutRoute with the builder id instead.

Read routes

getHealthDataFromTypes returns routes as WORKOUT_ROUTE data points whose value is a WorkoutRouteHealthValue:

final points = await health.getHealthDataFromTypes(
  types: [HealthDataType.WORKOUT_ROUTE],
  startTime: start,
  endTime: end,
);

for (final point in points) {
  final route = point.value as WorkoutRouteHealthValue;
  print('${route.locations.length} locations');
}

locations holds the locations of the route in time order, and the data point runs from the first location to the last. A location saved without an altitude reads back without altitude; on iOS, it also loses its verticalAccuracy.

workoutUuid differs per platform. On Android, it is null: the data point's uuid is the workout's UUID, which its metadata also holds under workout_uuid. On iOS, workoutUuid holds the workout's UUID for routes that finishWorkoutRoute attached, and the data point's uuid is the route's.

On Android, reading routes in the background needs READ_HEALTH_DATA_IN_BACKGROUND, as other Health Connect reads do. Even with it, an app in the background reads the routes of other apps without locations, with route_requires_consent: true in metadata, whatever Exercise routes access the user granted. On Android 14 and 15, reads of workouts and routes may cost extra Health Connect calls. See Health Connect limits.

Examples

Attach a route to a workout

This function writes a walk with its route, and discards the builder when a step fails:

Future<String> attachRoute(List<WorkoutRouteLocation> locations) async {
  final builderId = await health.startWorkoutRoute();
  try {
    final added = await health.insertWorkoutRouteData(
      builderId: builderId,
      locations: locations,
    );
    if (!added) throw StateError('The locations were not added');

    final workoutUuid = await health.writeWorkoutDataUUID(
      activityType: HealthWorkoutActivityType.WALKING,
      start: start,
      end: end,
    );
    if (workoutUuid == null || workoutUuid.isEmpty) {
      throw StateError('The workout was not saved');
    }

    return await health.finishWorkoutRoute(
      builderId: builderId,
      workoutUuid: workoutUuid,
    );
  } catch (_) {
    // A started builder stays open until it is finished or discarded
    await health.discardWorkoutRoute(builderId);
    rethrow;
  }
}

When finishWorkoutRoute fails on iOS after it found the workout, the builder is already closed, and discardWorkoutRoute returns false.

Error handling

The route methods throw a PlatformException, not a HealthPlatformException, so catch PlatformException, which is in package:flutter/services.dart, and check its code:

MethodCodeThrown when
startWorkoutRouteROUTE_ERRORNo builder opens
insertWorkoutRouteDataROUTE_ERRORThe builder is not open, or HealthKit cannot add the locations
insertWorkoutRouteDataINVALID_ARGUMENTA location is out of range (Android only)
finishWorkoutRouteROUTE_ERRORThe builder is not open, the workout is not found or the platform does not save the route. Android does not save a route with a location outside the workout.
finishWorkoutRouteARGUMENT_ERRORworkoutUuid is empty or, on iOS, not a UUID; on Android, also when builderId is empty
discardWorkoutRouteARGUMENT_ERRORbuilderId is empty (Android only; iOS returns false)

When a call fails, discard the builder, as Attach a route to a workout does. For the error types of the plugin, see Error handling.

Platform differences

AndroidiOS
  • The route becomes part of the workout's exercise session. Health Connect lets an app add a route only to a workout it wrote itself.
  • Every location must be at or after the workout's start and before its end.
  • speed, course, their accuracies and metadata are ignored.
  • Reading the routes of other apps needs READ_EXERCISE_ROUTES, which the user grants in the Health Connect app.
  • HealthKit saves the route as a sample of its own, with metadata, and finishWorkoutRoute returns the route's UUID.
  • A location without horizontalAccuracy is saved with a horizontal accuracy of 100 m. One with an altitude but no verticalAccuracy is saved with a vertical accuracy of 100 m.
  • speedAccuracy and courseAccuracy are saved only when both are set.
  • discardWorkoutRoute returns false for a builder that is not open.

Quick links

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