fix: unit conversion on enable, dashboard refresh, and permission check

- Pass isMetric to enableSync() so the initial sync from the settings
  toggle converts kg to lb when the user's profile is set to lb
- Refresh BodyWeightProvider after sync from settings tile so the
  dashboard and weight screen update immediately
- Fix DashboardWeightWidget to compute sensibleRange() inside the
  Consumer builder so it rebuilds when weight data changes
- Add permission check in syncOnAppOpen() for app restart scenarios
- Add unit tests for weight conversion logic and HealthSyncState

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
John WeidnerandClaude Opus 4.6 committed 2026-03-27 16:32:53 -05:00
1 parent bed1416975
commit 627b8b9fd8
4 files changed
+189 -94

No files matched your search

+4 -3
View File
@@ -95,8 +95,9 @@ class HealthSyncNotifier extends _$HealthSyncNotifier {
return Platform.isIOS;
}
/// Enable health sync: request permissions, save preference, trigger initial sync
Future<int> enableSync() async {
/// Enable health sync: request permissions, save preference, trigger initial sync.
/// If [isMetric] is false, converts kg values from the health platform to lb before POSTing.
Future<int> enableSync({bool isMetric = true}) async {
_logger.info('Enabling health sync');
await _health.configure();
@@ -114,7 +115,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier {
await PreferenceHelper.instance.setHealthSyncEnabled(true);
state = state.copyWith(isEnabled: true);
return syncOnAppOpen();
return syncOnAppOpen(isMetric: isMetric);
}
/// Disable health sync: clear preferences
+14 -4
View File
@@ -18,7 +18,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:provider/provider.dart' as provider;
import 'package:wger/providers/body_weight.dart';
import 'package:wger/providers/health_sync.dart';
import 'package:wger/providers/user.dart';
class HealthSyncSettingsTile extends ConsumerStatefulWidget {
const HealthSyncSettingsTile({super.key});
@@ -62,11 +65,18 @@ class _HealthSyncSettingsTileState extends ConsumerState<HealthSyncSettingsTile>
: (enabled) async {
final notifier = ref.read(healthSyncProvider.notifier);
if (enabled) {
final count = await notifier.enableSync();
final profile = provider.Provider.of<UserProvider>(context, listen: false).profile;
final isMetric = profile?.isMetric ?? true;
final count = await notifier.enableSync(isMetric: isMetric);
if (context.mounted && count > 0) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Synced $count weight entries from Health')),
);
// Refresh weight entries so the dashboard/weight screen updates
await provider.Provider.of<BodyWeightProvider>(context, listen: false)
.fetchAndSetEntries();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Synced $count weight entries from Health')),
);
}
}
} else {
await notifier.disableSync();
+88 -87
View File
@@ -35,101 +35,102 @@ class DashboardWeightWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final profile = context.read<UserProvider>().profile;
final weightProvider = context.read<BodyWeightProvider>();
final (entriesAll, entries7dAvg) = sensibleRange(
weightProvider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(),
);
return Consumer<BodyWeightProvider>(
builder: (context, _, _) => Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: Text(
AppLocalizations.of(context).weight,
style: Theme.of(context).textTheme.headlineSmall,
builder: (context, weightProvider, _) {
final (entriesAll, entries7dAvg) = sensibleRange(
weightProvider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(),
);
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: Text(
AppLocalizations.of(context).weight,
style: Theme.of(context).textTheme.headlineSmall,
),
leading: FaIcon(
FontAwesomeIcons.weightScale,
color: Theme.of(context).textTheme.headlineSmall!.color,
),
),
leading: FaIcon(
FontAwesomeIcons.weightScale,
color: Theme.of(context).textTheme.headlineSmall!.color,
),
),
Column(
children: [
if (weightProvider.items.isNotEmpty)
Column(
children: [
SizedBox(
height: 200,
child: MeasurementChartWidgetFl(
entriesAll,
weightUnit(profile!.isMetric, context),
avgs: entries7dAvg,
Column(
children: [
if (weightProvider.items.isNotEmpty)
Column(
children: [
SizedBox(
height: 200,
child: MeasurementChartWidgetFl(
entriesAll,
weightUnit(profile!.isMetric, context),
avgs: entries7dAvg,
),
),
),
if (entries7dAvg.isNotEmpty)
MeasurementOverallChangeWidget(
entries7dAvg.first,
entries7dAvg.last,
weightUnit(profile.isMetric, context),
),
LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(
AppLocalizations.of(context).goToDetailPage,
overflow: TextOverflow.ellipsis,
if (entries7dAvg.isNotEmpty)
MeasurementOverallChangeWidget(
entries7dAvg.first,
entries7dAvg.last,
weightUnit(profile.isMetric, context),
),
LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(
AppLocalizations.of(context).goToDetailPage,
overflow: TextOverflow.ellipsis,
),
onPressed: () {
Navigator.of(context).pushNamed(WeightScreen.routeName);
},
),
onPressed: () {
Navigator.of(context).pushNamed(WeightScreen.routeName);
},
),
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
WeightForm(
weightProvider.getNewestEntry()?.copyWith(
id: null,
date: DateTime.now(),
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
WeightForm(
weightProvider.getNewestEntry()?.copyWith(
id: null,
date: DateTime.now(),
),
),
),
),
);
},
),
],
);
},
),
],
),
),
),
);
},
),
],
)
else
NothingFound(
AppLocalizations.of(context).noWeightEntries,
AppLocalizations.of(context).newEntry,
WeightForm(),
),
],
),
],
),
),
);
},
),
],
)
else
NothingFound(
AppLocalizations.of(context).noWeightEntries,
AppLocalizations.of(context).newEntry,
WeightForm(),
),
],
),
],
),
);
},
);
}
}
+83
View File
@@ -0,0 +1,83 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/providers/health_sync.dart';
/// Mirrors the conversion logic in HealthSyncNotifier.syncOnAppOpen
double _convertWeight(double weightKg, {required bool isMetric}) {
return isMetric ? weightKg : weightKg * kgToLb;
}
void main() {
group('Health sync constants', () {
test('kgToLb conversion factor is correct', () {
// 1 kg = 2.20462 lb
expect(kgToLb, closeTo(2.20462, 0.00001));
});
test('Initial sync lookback is 30 days', () {
expect(healthSyncInitialDays, 30);
});
});
group('Weight unit conversion', () {
test('kg value is converted to lb correctly', () {
const weightKg = 85.0;
final weightLb = (weightKg * kgToLb * 100).roundToDouble() / 100;
expect(weightLb, closeTo(187.39, 0.01));
});
test('kg value stays as-is when metric', () {
const weightKg = 85.0;
final weight = _convertWeight(weightKg, isMetric: true);
expect(weight, 85.0);
});
test('kg value is converted when imperial', () {
const weightKg = 85.0;
final weight = _convertWeight(weightKg, isMetric: false);
expect(weight, closeTo(187.39, 0.01));
});
test('conversion rounds to 2 decimal places', () {
const weightKg = 85.12345;
final weight = weightKg * kgToLb;
final rounded = (weight * 100).roundToDouble() / 100;
// 85.12345 * 2.20462 = 187.66...
expect(rounded.toString().split('.').last.length, lessThanOrEqualTo(2));
});
});
group('HealthSyncState', () {
test('default state has sync disabled', () {
const state = HealthSyncState();
expect(state.isEnabled, false);
expect(state.isSyncing, false);
expect(state.lastSyncCount, 0);
});
test('copyWith updates individual fields', () {
const state = HealthSyncState();
final updated = state.copyWith(isEnabled: true, lastSyncCount: 5);
expect(updated.isEnabled, true);
expect(updated.isSyncing, false);
expect(updated.lastSyncCount, 5);
});
});
}