Use the platform's daily totals for summed metrics on iOS

Steps, distance and active energy were added up from the raw HealthKit
samples, so a day recorded by both an iPhone and an Apple Watch was
counted twice. Android already takes the deduplicated total from Health
Connect for such days; iOS now does the same through HealthKit's
statistics query, which resolves overlapping sources by the user's
priority like the Health app does.

Existing iOS installs read the history of these metrics once more on
their next sync, which corrects the days stored with the raw sum.

See wger-project/wger#2608
This commit is contained in:
Roland Geider
2026-11-24 16:23:56 +01:00
parent a6c2cf94db
commit 1dda51b6f6
3 changed files with 99 additions and 15 deletions

View File

@@ -202,23 +202,26 @@ class HealthRepository {
return true;
}
/// Whether [platformTotal] can answer here at all: Health Connect only.
bool get hasPlatformTotals => !kIsWeb && Platform.isAndroid;
/// Whether [platformTotal] can answer here at all: on Health Connect and
/// on Apple Health. Callers check this before asking.
bool get hasPlatformTotals => !kIsWeb && (Platform.isAndroid || Platform.isIOS);
/// The total of a cumulative [type] (steps, distance, active energy)
/// between [start] and [end] as Health Connect itself reports it.
/// between [start] and [end] as the health platform itself reports it.
///
/// Health Connect resolves overlapping records from several apps by the
/// user's data source priority, and drops an app's second copy of the same
/// interval (e.g. a watch writing both its interval buckets and a workout
/// record). Adding up the raw records instead counts those twice. The value
/// is in the platform's raw unit (count, meters, kcal), like a raw read.
/// Both platforms resolve overlapping records from several sources by the
/// user's data source priority (a phone and a watch counting the same
/// steps), which is the number their own apps show. Health Connect also
/// drops an app's second copy of the same interval (e.g. a watch writing
/// both its interval buckets and a workout record). Adding up the raw
/// records instead counts those twice. The value is in the platform's raw
/// unit (count, meters, kcal), like a raw read.
///
/// Null on iOS, on failure, or when the platform returned nothing (it omits
/// a range without data from the user's priority list), so the caller can
/// fall back to the raw sum.
/// Null on failure or when the platform returned nothing (it omits a range
/// without data, on Android one without data from the user's priority
/// list), so the caller can fall back to the raw sum.
Future<double?> platformTotal(HealthDataType type, DateTime start, DateTime end) async {
if (!hasPlatformTotals || !end.isAfter(start)) {
if (!end.isAfter(start)) {
return null;
}
try {
@@ -231,7 +234,9 @@ class HealthRepository {
);
final values = [
for (final point in points)
if (point.value is NumericHealthValue)
// HealthKit's query takes in records reaching across [end] and can
// list the bucket after it too, holding their part past the range
if (point.dateFrom.isBefore(end) && point.value is NumericHealthValue)
(point.value as NumericHealthValue).numericValue.toDouble(),
];
if (values.isEmpty) {

View File

@@ -1573,10 +1573,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.14"
version: "0.7.12"
timezone:
dependency: "direct main"
description:

View File

@@ -365,6 +365,85 @@ void main() {
});
});
group('platformTotal', () {
final day = DateTime(2026, 11, 13);
final nextDay = DateTime(2026, 11, 14);
HealthDataPoint bucket(DateTime from, DateTime to, num value) => HealthDataPoint(
uuid: '',
value: NumericHealthValue(numericValue: value),
type: HealthDataType.STEPS,
unit: HealthDataUnit.COUNT,
dateFrom: from,
dateTo: to,
sourcePlatform: HealthPlatformType.appleHealth,
sourceDeviceId: 'device',
sourceId: '',
sourceName: 'com.apple.health.phone, com.apple.health.watch',
);
void stubBuckets(List<HealthDataPoint> buckets) {
when(
health.getHealthIntervalDataFromTypes(
startDate: anyNamed('startDate'),
endDate: anyNamed('endDate'),
types: anyNamed('types'),
interval: anyNamed('interval'),
),
).thenAnswer((_) async => buckets);
}
test('asks for the range as one bucket and returns its total', () async {
stubBuckets([bucket(day, nextDay, 12797)]);
expect(await repository.platformTotal(HealthDataType.STEPS, day, nextDay), 12797);
final captured = verify(
health.getHealthIntervalDataFromTypes(
startDate: captureAnyNamed('startDate'),
endDate: captureAnyNamed('endDate'),
types: captureAnyNamed('types'),
interval: captureAnyNamed('interval'),
),
).captured;
expect(captured, [
day,
nextDay,
[HealthDataType.STEPS],
nextDay.difference(day).inSeconds,
]);
});
test('leaves out the bucket after the range', () async {
// The part past midnight of a record reaching across it
stubBuckets([
bucket(day, nextDay, 12797),
bucket(nextDay, DateTime(2026, 11, 15), 240),
]);
expect(await repository.platformTotal(HealthDataType.STEPS, day, nextDay), 12797);
});
test('is null without data, so the caller keeps its raw sum', () async {
stubBuckets([]);
expect(await repository.platformTotal(HealthDataType.STEPS, day, nextDay), isNull);
});
test('is null when the platform fails', () async {
when(
health.getHealthIntervalDataFromTypes(
startDate: anyNamed('startDate'),
endDate: anyNamed('endDate'),
types: anyNamed('types'),
interval: anyNamed('interval'),
),
).thenThrow(PlatformException(code: 'STATISTICS_ERROR'));
expect(await repository.platformTotal(HealthDataType.STEPS, day, nextDay), isNull);
});
});
group('readableTypes', () {
test('a declined type costs only itself', () async {
// Asked for both at once, the platform says false as soon as one is