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.

Aggregate data

How getHealthAggregateDataFromTypes fails on both platforms in health 13.x, and the read methods to use instead.

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

getHealthAggregateDataFromTypes is meant to return aggregate summaries across multiple types in one call, such as workouts with their energy and distance.

Known issue

getHealthAggregateDataFromTypes does not work in health 13.x: the Android handler expects different arguments, and iOS has no native handler for it. Every call throws, so the method never returns data. Use getHealthIntervalDataFromTypes for values per time interval, such as daily step totals, and getHealthDataFromTypes for workouts.

Signature

Future<List<HealthDataPoint>> getHealthAggregateDataFromTypes({
  required List<HealthDataType> types,
  required DateTime startDate,
  required DateTime endDate,
  int activitySegmentDuration = 1,
  bool includeManualEntry = true,
})
ParameterTypeRequiredDefaultDescription
typesList<HealthDataType>Yes-Health data types to query
startDateDateTimeYes-Start of time range
endDateDateTimeYes-End of time range
activitySegmentDurationintNo1Not used: neither platform reads it
includeManualEntryboolNotrueNot used: neither platform reads it

Read workout summaries

Read workouts with getHealthDataFromTypes instead. Each WORKOUT point holds a WorkoutHealthValue with the workout's totals:

final workoutSummaries = await health.getHealthDataFromTypes(
  types: [HealthDataType.WORKOUT],
  startTime: DateTime.now().subtract(Duration(days: 7)),
  endTime: DateTime.now(),
);

for (var point in workoutSummaries) {
  if (point.type == HealthDataType.WORKOUT) {
    final workout = point.value as WorkoutHealthValue;
    print('Workout: ${workout.workoutActivityType.name}');
    print('Duration: ${point.dateTo.difference(point.dateFrom)}');
    
    if (workout.totalEnergyBurned != null) {
      print('Calories: ${workout.totalEnergyBurned}');
    }
  }
}

For how each platform computes the totals, see Workout values.

Activity segment duration

activitySegmentDuration has no effect, and no read method in health 13.x splits workouts into segments. To read a quantity type, such as STEPS or ACTIVE_ENERGY_BURNED, in fixed time buckets, see Interval data.

Filter manual entries

includeManualEntry has no effect. To leave out manually entered workouts, pass recordingMethodsToFilter: [RecordingMethod.manual] to getHealthDataFromTypes:

// Exclude manual entries
final autoOnly = await health.getHealthDataFromTypes(
  types: [HealthDataType.WORKOUT],
  startTime: start,
  endTime: end,
  recordingMethodsToFilter: [RecordingMethod.manual],
);

// Include manual entries (default)
final all = await health.getHealthDataFromTypes(
  types: [HealthDataType.WORKOUT],
  startTime: start,
  endTime: end,
);

Query multiple types

Query several related metrics at once with getHealthDataFromTypes. It returns the individual points of each type, not summaries:

final activityData = await health.getHealthDataFromTypes(
  types: [
    HealthDataType.WORKOUT,
    HealthDataType.ACTIVE_ENERGY_BURNED,
    Platform.isAndroid
        ? HealthDataType.DISTANCE_DELTA
        : HealthDataType.DISTANCE_WALKING_RUNNING,
    HealthDataType.STEPS,
    HealthDataType.HEART_RATE,
  ],
  startTime: DateTime.now().subtract(Duration(days: 30)),
  endTime: DateTime.now(),
);

// Group by type
final byType = <HealthDataType, List<HealthDataPoint>>{};
for (var point in activityData) {
  byType.putIfAbsent(point.type, () => []).add(point);
}

print('Workouts: ${byType[HealthDataType.WORKOUT]?.length ?? 0}');
print('Energy data points: ${byType[HealthDataType.ACTIVE_ENERGY_BURNED]?.length ?? 0}');

Examples

The examples read workouts with getHealthDataFromTypes, which works on both platforms.

Workout dashboard

class WorkoutStats {
  final int totalWorkouts;
  final Duration totalDuration;
  final double totalCalories;
  final double totalDistance;
  
  WorkoutStats({
    required this.totalWorkouts,
    required this.totalDuration,
    required this.totalCalories,
    required this.totalDistance,
  });
}

Future<WorkoutStats> getWorkoutStats(DateTime start, DateTime end) async {
  final data = await health.getHealthDataFromTypes(
    types: [HealthDataType.WORKOUT],
    startTime: start,
    endTime: end,
  );
  
  int workoutCount = 0;
  Duration totalDuration = Duration.zero;
  double totalCalories = 0;
  double totalDistance = 0;
  
  for (var point in data) {
    if (point.type == HealthDataType.WORKOUT) {
      workoutCount++;
      totalDuration += point.dateTo.difference(point.dateFrom);
      
      final workout = point.value as WorkoutHealthValue;
      totalCalories += workout.totalEnergyBurned ?? 0;
      totalDistance += workout.totalDistance ?? 0;
    }
  }
  
  return WorkoutStats(
    totalWorkouts: workoutCount,
    totalDuration: totalDuration,
    totalCalories: totalCalories,
    totalDistance: totalDistance,
  );
}

Activity type breakdown

Future<Map<HealthWorkoutActivityType, int>> getWorkoutTypeBreakdown(
  DateTime start,
  DateTime end,
) async {
  final workouts = await health.getHealthDataFromTypes(
    types: [HealthDataType.WORKOUT],
    startTime: start,
    endTime: end,
  );
  
  final breakdown = <HealthWorkoutActivityType, int>{};
  
  for (var point in workouts) {
    final workout = point.value as WorkoutHealthValue;
    breakdown[workout.workoutActivityType] = 
        (breakdown[workout.workoutActivityType] ?? 0) + 1;
  }
  
  return breakdown;
}

// Usage
final breakdown = await getWorkoutTypeBreakdown(
  DateTime.now().subtract(Duration(days: 30)),
  DateTime.now(),
);

breakdown.forEach((type, count) {
  print('${type.name}: $count workouts');
});

Platform differences

The call fails on both platforms, with a different exception on each:

AndroidiOS
  • When Health Connect is not available, the call throws an UnsupportedError.
  • A type that the plugin does not support on Android, such as DISTANCE_WALKING_RUNNING, throws a HealthException.
  • Otherwise, the native handler fails, because it reads the dataTypeKey and interval arguments of an interval read, which this call does not send. The call throws a PlatformException.
  • For workouts, getHealthDataFromTypes sums the distance, total calories burned and steps that all apps recorded during each workout.
  • A type that the plugin does not support on iOS, such as DISTANCE_DELTA, throws a HealthException.
  • Otherwise, the call throws a MissingPluginException, because the plugin has no native handler for it.
  • For workouts, getHealthDataFromTypes returns the energy and distance totals that each workout stores, and no step total.

Quick links

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