mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-03 18:43:42 +01:00
feat: add automatic weight sync from Apple Health and Google Health Connect
Import body weight data from Apple Health (iOS) and Google Health Connect (Android) into wger when the app is opened. Uses the Flutter `health` package for cross-platform access. Feature is opt-in via a settings toggle. Key changes: - Add HealthSyncNotifier (Riverpod) for sync orchestration - Add HealthSyncSettingsTile in settings page - Add health package dependency and platform permissions - Fix WeightEntry.copyWith parameter type (int? -> num?) - Fix BodyWeightProvider.findByDate() to use calendar-date comparison - Raise Android minSdkVersion to 26 (Health Connect requirement) - Change MainActivity to extend FlutterFragmentActivity Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -39,7 +39,7 @@ android {
|
||||
defaultConfig {
|
||||
// Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId "de.wger.flutter"
|
||||
minSdkVersion flutter.minSdkVersion
|
||||
minSdkVersion 26
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
|
||||
@@ -9,11 +9,19 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- Health Connect permissions for weight sync -->
|
||||
<uses-permission android:name="android.permission.health.READ_WEIGHT"/>
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="https" />
|
||||
</intent>
|
||||
<!-- Health Connect -->
|
||||
<package android:name="com.google.android.apps.healthdata" />
|
||||
<intent>
|
||||
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<supports-screens
|
||||
@@ -48,8 +56,24 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
|
||||
<!-- Health Connect permissions rationale -->
|
||||
<intent-filter>
|
||||
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Required for Health Connect on Google Play -->
|
||||
<activity-alias
|
||||
android:name="ViewPermissionUsageActivity"
|
||||
android:exported="true"
|
||||
android:targetActivity=".MainActivity"
|
||||
android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
|
||||
<category android:name="android.intent.category.HEALTH_PERMISSIONS" />
|
||||
</intent-filter>
|
||||
</activity-alias>
|
||||
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package de.wger.flutter
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.android.FlutterFragmentActivity
|
||||
|
||||
class MainActivity: FlutterActivity() {
|
||||
class MainActivity: FlutterFragmentActivity() {
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
<true/>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Workout photos</string>
|
||||
<key>NSHealthShareUsageDescription</key>
|
||||
<string>wger uses your health data to automatically sync weight measurements from your smart scale</string>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
|
||||
@@ -4,5 +4,11 @@
|
||||
<dict>
|
||||
<key>aps-environment</key>
|
||||
<string>development</string>
|
||||
<key>com.apple.developer.healthkit</key>
|
||||
<true/>
|
||||
<key>com.apple.developer.healthkit.access</key>
|
||||
<array>
|
||||
<string>health-records</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -68,4 +68,30 @@ class PreferenceHelper {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Health sync
|
||||
static const _healthSyncEnabledKey = 'healthSyncEnabled';
|
||||
static const _lastHealthSyncTimestampKey = 'lastHealthSyncTimestamp';
|
||||
|
||||
Future<void> setHealthSyncEnabled(bool value) async {
|
||||
await PreferenceHelper.asyncPref.setBool(_healthSyncEnabledKey, value);
|
||||
}
|
||||
|
||||
Future<bool> getHealthSyncEnabled() async {
|
||||
final value = await PreferenceHelper.asyncPref.getBool(_healthSyncEnabledKey);
|
||||
return value ?? false;
|
||||
}
|
||||
|
||||
Future<void> setLastHealthSyncTimestamp(String value) async {
|
||||
await PreferenceHelper.asyncPref.setString(_lastHealthSyncTimestampKey, value);
|
||||
}
|
||||
|
||||
Future<String?> getLastHealthSyncTimestamp() async {
|
||||
return PreferenceHelper.asyncPref.getString(_lastHealthSyncTimestampKey);
|
||||
}
|
||||
|
||||
Future<void> clearHealthSyncPreferences() async {
|
||||
await PreferenceHelper.asyncPref.remove(_healthSyncEnabledKey);
|
||||
await PreferenceHelper.asyncPref.remove(_lastHealthSyncTimestampKey);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class WeightEntry {
|
||||
}
|
||||
}
|
||||
|
||||
WeightEntry copyWith({int? id, int? weight, DateTime? date}) => WeightEntry(
|
||||
WeightEntry copyWith({int? id, num? weight, DateTime? date}) => WeightEntry(
|
||||
id: id,
|
||||
weight: weight ?? this.weight,
|
||||
date: date ?? this.date,
|
||||
|
||||
@@ -15,8 +15,9 @@ WeightEntry _$WeightEntryFromJson(Map<String, dynamic> json) {
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$WeightEntryToJson(WeightEntry instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'weight': numToString(instance.weight),
|
||||
'date': dateToUtcIso8601(instance.date),
|
||||
};
|
||||
Map<String, dynamic> _$WeightEntryToJson(WeightEntry instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'weight': numToString(instance.weight),
|
||||
'date': dateToUtcIso8601(instance.date),
|
||||
};
|
||||
|
||||
@@ -58,7 +58,12 @@ class BodyWeightProvider with ChangeNotifier {
|
||||
|
||||
WeightEntry? findByDate(DateTime date) {
|
||||
try {
|
||||
return _entries.firstWhere((plan) => plan.date == date);
|
||||
return _entries.firstWhere(
|
||||
(entry) =>
|
||||
entry.date.year == date.year &&
|
||||
entry.date.month == date.month &&
|
||||
entry.date.day == date.day,
|
||||
);
|
||||
} on StateError {
|
||||
return null;
|
||||
}
|
||||
|
||||
224
lib/providers/health_sync.dart
Normal file
224
lib/providers/health_sync.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* 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 'dart:io';
|
||||
|
||||
import 'package:health/health.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:wger/helpers/shared_preferences.dart';
|
||||
import 'package:wger/models/body_weight/weight_entry.dart';
|
||||
import 'package:wger/providers/base_provider.dart';
|
||||
import 'package:wger/providers/wger_base_riverpod.dart';
|
||||
|
||||
part 'health_sync.g.dart';
|
||||
|
||||
class HealthSyncState {
|
||||
final bool isEnabled;
|
||||
final bool isSyncing;
|
||||
final int lastSyncCount;
|
||||
|
||||
const HealthSyncState({
|
||||
this.isEnabled = false,
|
||||
this.isSyncing = false,
|
||||
this.lastSyncCount = 0,
|
||||
});
|
||||
|
||||
HealthSyncState copyWith({
|
||||
bool? isEnabled,
|
||||
bool? isSyncing,
|
||||
int? lastSyncCount,
|
||||
}) {
|
||||
return HealthSyncState(
|
||||
isEnabled: isEnabled ?? this.isEnabled,
|
||||
isSyncing: isSyncing ?? this.isSyncing,
|
||||
lastSyncCount: lastSyncCount ?? this.lastSyncCount,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Initial sync lookback period
|
||||
const int healthSyncInitialDays = 30;
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class HealthSyncNotifier extends _$HealthSyncNotifier {
|
||||
final _logger = Logger('HealthSyncNotifier');
|
||||
late final Health _health;
|
||||
late final WgerBaseProvider _baseProvider;
|
||||
|
||||
static const _weightEntryUrl = 'weightentry';
|
||||
|
||||
@override
|
||||
HealthSyncState build() {
|
||||
_health = Health();
|
||||
_baseProvider = ref.read(wgerBaseProvider);
|
||||
|
||||
// Load persisted sync preference on startup
|
||||
_loadPersistedState();
|
||||
|
||||
return const HealthSyncState();
|
||||
}
|
||||
|
||||
Future<void> _loadPersistedState() async {
|
||||
final enabled = await PreferenceHelper.instance.getHealthSyncEnabled();
|
||||
if (enabled) {
|
||||
state = state.copyWith(isEnabled: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the health platform is available on this device
|
||||
Future<bool> isAvailable() async {
|
||||
if (Platform.isAndroid) {
|
||||
await _health.configure();
|
||||
final status = await _health.getHealthConnectSdkStatus();
|
||||
return status == HealthConnectSdkStatus.sdkAvailable;
|
||||
}
|
||||
// iOS always has HealthKit available
|
||||
return Platform.isIOS;
|
||||
}
|
||||
|
||||
/// Enable health sync: request permissions, save preference, trigger initial sync
|
||||
Future<int> enableSync() async {
|
||||
_logger.info('Enabling health sync');
|
||||
|
||||
await _health.configure();
|
||||
|
||||
final authorized = await _health.requestAuthorization(
|
||||
[HealthDataType.WEIGHT],
|
||||
permissions: [HealthDataAccess.READ],
|
||||
);
|
||||
|
||||
if (!authorized) {
|
||||
_logger.warning('Health permissions not granted');
|
||||
return 0;
|
||||
}
|
||||
|
||||
await PreferenceHelper.instance.setHealthSyncEnabled(true);
|
||||
state = state.copyWith(isEnabled: true);
|
||||
|
||||
return syncOnAppOpen();
|
||||
}
|
||||
|
||||
/// Disable health sync: clear preferences
|
||||
Future<void> disableSync() async {
|
||||
_logger.info('Disabling health sync');
|
||||
await PreferenceHelper.instance.clearHealthSyncPreferences();
|
||||
state = const HealthSyncState();
|
||||
}
|
||||
|
||||
/// Main sync method: read weight data from health platform, post new entries to backend
|
||||
Future<int> syncOnAppOpen({List<WeightEntry>? existingEntries}) async {
|
||||
final prefs = PreferenceHelper.instance;
|
||||
final enabled = await prefs.getHealthSyncEnabled();
|
||||
if (!enabled) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (state.isSyncing) {
|
||||
return 0;
|
||||
}
|
||||
state = state.copyWith(isEnabled: true, isSyncing: true);
|
||||
|
||||
try {
|
||||
await _health.configure();
|
||||
|
||||
// Determine the start time for the query
|
||||
final lastSyncStr = await prefs.getLastHealthSyncTimestamp();
|
||||
final DateTime startTime;
|
||||
if (lastSyncStr != null) {
|
||||
startTime = DateTime.parse(lastSyncStr);
|
||||
} else {
|
||||
startTime = DateTime.now().subtract(const Duration(days: healthSyncInitialDays));
|
||||
}
|
||||
final endTime = DateTime.now();
|
||||
|
||||
_logger.info('Syncing weight data from $startTime to $endTime');
|
||||
|
||||
// Read weight data from health platform
|
||||
List<HealthDataPoint> dataPoints = await _health.getHealthDataFromTypes(
|
||||
types: [HealthDataType.WEIGHT],
|
||||
startTime: startTime,
|
||||
endTime: endTime,
|
||||
);
|
||||
dataPoints = _health.removeDuplicates(dataPoints);
|
||||
|
||||
if (dataPoints.isEmpty) {
|
||||
_logger.info('No new weight data from health platform');
|
||||
state = state.copyWith(isSyncing: false, lastSyncCount: 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
_logger.info('Found ${dataPoints.length} weight data points');
|
||||
|
||||
int syncedCount = 0;
|
||||
DateTime? latestSynced;
|
||||
|
||||
for (final point in dataPoints) {
|
||||
try {
|
||||
final value = (point.value as NumericHealthValue).numericValue;
|
||||
final weightKg = (value * 100).roundToDouble() / 100; // Round to 2 decimal places
|
||||
final timestamp = point.dateFrom;
|
||||
|
||||
// Fallback dedup: skip if an entry with the same timestamp exists locally
|
||||
if (existingEntries != null) {
|
||||
final duplicate = existingEntries.any(
|
||||
(e) =>
|
||||
e.date.year == timestamp.year &&
|
||||
e.date.month == timestamp.month &&
|
||||
e.date.day == timestamp.day &&
|
||||
e.date.hour == timestamp.hour &&
|
||||
e.date.minute == timestamp.minute,
|
||||
);
|
||||
if (duplicate) {
|
||||
_logger.fine('Skipping duplicate entry for $timestamp');
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// POST to backend with original timestamp
|
||||
final entry = WeightEntry(weight: weightKg, date: timestamp);
|
||||
await _baseProvider.post(
|
||||
entry.toJson(),
|
||||
_baseProvider.makeUrl(_weightEntryUrl),
|
||||
);
|
||||
|
||||
syncedCount++;
|
||||
if (latestSynced == null || timestamp.isAfter(latestSynced)) {
|
||||
latestSynced = timestamp;
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.warning('Failed to sync weight entry: $e');
|
||||
// Best-effort: continue with next entry
|
||||
}
|
||||
}
|
||||
|
||||
// Update last sync timestamp to the latest successfully synced reading
|
||||
if (latestSynced != null) {
|
||||
await prefs.setLastHealthSyncTimestamp(latestSynced.toIso8601String());
|
||||
}
|
||||
|
||||
_logger.info('Synced $syncedCount weight entries');
|
||||
state = state.copyWith(isSyncing: false, lastSyncCount: syncedCount);
|
||||
return syncedCount;
|
||||
} catch (e) {
|
||||
_logger.warning('Health sync failed: $e');
|
||||
state = state.copyWith(isSyncing: false, lastSyncCount: 0);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
63
lib/providers/health_sync.g.dart
Normal file
63
lib/providers/health_sync.g.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'health_sync.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(HealthSyncNotifier)
|
||||
final healthSyncProvider = HealthSyncNotifierProvider._();
|
||||
|
||||
final class HealthSyncNotifierProvider
|
||||
extends $NotifierProvider<HealthSyncNotifier, HealthSyncState> {
|
||||
HealthSyncNotifierProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'healthSyncProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$healthSyncNotifierHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
HealthSyncNotifier create() => HealthSyncNotifier();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(HealthSyncState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<HealthSyncState>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$healthSyncNotifierHash() =>
|
||||
r'7a0929b0b1660729da0f0fc3a9a1a70af71cf894';
|
||||
|
||||
abstract class _$HealthSyncNotifier extends $Notifier<HealthSyncState> {
|
||||
HealthSyncState build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<HealthSyncState, HealthSyncState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<HealthSyncState, HealthSyncState>,
|
||||
HealthSyncState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import 'package:wger/providers/auth.dart';
|
||||
import 'package:wger/providers/body_weight.dart';
|
||||
import 'package:wger/providers/exercises.dart';
|
||||
import 'package:wger/providers/gallery.dart';
|
||||
import 'package:wger/providers/health_sync.dart';
|
||||
import 'package:wger/providers/measurement.dart';
|
||||
import 'package:wger/providers/nutrition.dart';
|
||||
import 'package:wger/providers/routines.dart';
|
||||
@@ -147,6 +148,15 @@ class _HomeTabsScreenState extends ConsumerState<HomeTabsScreen>
|
||||
}
|
||||
|
||||
authProvider.dataInit = true;
|
||||
|
||||
// Trigger health sync after weight entries are loaded (non-blocking)
|
||||
final weightProviderForSync = context.read<BodyWeightProvider>();
|
||||
final healthNotifier = ref.read(healthSyncProvider.notifier);
|
||||
healthNotifier.syncOnAppOpen(existingEntries: weightProviderForSync.items).then((syncCount) {
|
||||
if (syncCount > 0) {
|
||||
weightProviderForSync.fetchAndSetEntries();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -21,6 +21,7 @@ import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/screens/settings_plates_screen.dart';
|
||||
|
||||
import './settings/exercise_cache.dart';
|
||||
import './settings/health_sync.dart';
|
||||
import './settings/ingredient_cache.dart';
|
||||
import './settings/theme.dart';
|
||||
|
||||
@@ -42,6 +43,8 @@ class SettingsPage extends StatelessWidget {
|
||||
),
|
||||
const SettingsExerciseCache(),
|
||||
const SettingsIngredientCache(),
|
||||
ListTile(title: Text('Health', style: Theme.of(context).textTheme.headlineSmall)),
|
||||
const HealthSyncSettingsTile(),
|
||||
ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)),
|
||||
const SettingsTheme(),
|
||||
ListTile(
|
||||
|
||||
77
lib/widgets/core/settings/health_sync.dart
Normal file
77
lib/widgets/core/settings/health_sync.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:wger/providers/health_sync.dart';
|
||||
|
||||
class HealthSyncSettingsTile extends ConsumerStatefulWidget {
|
||||
const HealthSyncSettingsTile({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<HealthSyncSettingsTile> createState() => _HealthSyncSettingsTileState();
|
||||
}
|
||||
|
||||
class _HealthSyncSettingsTileState extends ConsumerState<HealthSyncSettingsTile> {
|
||||
bool? _isAvailable;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_checkAvailability();
|
||||
}
|
||||
|
||||
Future<void> _checkAvailability() async {
|
||||
final notifier = ref.read(healthSyncProvider.notifier);
|
||||
final available = await notifier.isAvailable();
|
||||
if (mounted) {
|
||||
setState(() => _isAvailable = available);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Hide entirely if platform check hasn't completed or is unavailable
|
||||
if (_isAvailable == null || _isAvailable == false) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final syncState = ref.watch(healthSyncProvider);
|
||||
|
||||
return SwitchListTile(
|
||||
title: const Text('Health sync'),
|
||||
subtitle: const Text('Import weight from Apple Health or Health Connect'),
|
||||
value: syncState.isEnabled,
|
||||
onChanged: syncState.isSyncing
|
||||
? null
|
||||
: (enabled) async {
|
||||
final notifier = ref.read(healthSyncProvider.notifier);
|
||||
if (enabled) {
|
||||
final count = await notifier.enableSync();
|
||||
if (context.mounted && count > 0) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Synced $count weight entries from Health')),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
await notifier.disableSync();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
40
pubspec.lock
40
pubspec.lock
@@ -153,6 +153,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.2"
|
||||
carp_serializable:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: carp_serializable
|
||||
sha256: f039f8ea22e9437aef13fe7e9743c3761c76d401288dcb702eadd273c3e4dcef
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
change:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -297,6 +305,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.3"
|
||||
device_info_plus:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: device_info_plus
|
||||
sha256: "4df8babf73058181227e18b08e6ea3520cf5fc5d796888d33b7cb0f33f984b7c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "12.3.0"
|
||||
device_info_plus_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: device_info_plus_platform_interface
|
||||
sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.3"
|
||||
drift:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -615,6 +639,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
health:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: health
|
||||
sha256: "2d9e119f3a1d281139f93149b41032b9f80b759960875bc784c5a25dd3c17524"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "13.3.1"
|
||||
hooks:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -1649,6 +1681,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.15.0"
|
||||
win32_registry:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: win32_registry
|
||||
sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -50,6 +50,7 @@ dependencies:
|
||||
font_awesome_flutter: ^11.0.0
|
||||
freezed_annotation: ^3.0.0
|
||||
get_it: ^8.3.0
|
||||
health: ^13.3.1
|
||||
http: ^1.6.0
|
||||
image_picker: ^1.2.1
|
||||
intl: ^0.20.0
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
@@ -57,17 +58,21 @@ void main() {
|
||||
});
|
||||
|
||||
Widget createSettingsScreen({locale = 'en'}) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<NutritionPlansProvider>(create: (context) => mockNutritionProvider),
|
||||
ChangeNotifierProvider<ExercisesProvider>(create: (context) => mockExerciseProvider),
|
||||
ChangeNotifierProvider<UserProvider>(create: (context) => mockUserProvider),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: Locale(locale),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const SettingsPage(),
|
||||
return ProviderScope(
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<NutritionPlansProvider>(
|
||||
create: (context) => mockNutritionProvider,
|
||||
),
|
||||
ChangeNotifierProvider<ExercisesProvider>(create: (context) => mockExerciseProvider),
|
||||
ChangeNotifierProvider<UserProvider>(create: (context) => mockUserProvider),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: Locale(locale),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const SettingsPage(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,5 +59,19 @@ void main() {
|
||||
expect(weightModel.weight, 80);
|
||||
expect(weightModel.date, DateTime.utc(2020, 10, 01));
|
||||
});
|
||||
|
||||
test('copyWith preserves decimal weight values', () {
|
||||
final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01));
|
||||
final copied = entry.copyWith(weight: 81.3);
|
||||
|
||||
expect(copied.weight, 81.3);
|
||||
});
|
||||
|
||||
test('copyWith with null weight keeps original value', () {
|
||||
final entry = WeightEntry(id: 1, weight: 80.5, date: DateTime.utc(2020, 10, 01));
|
||||
final copied = entry.copyWith();
|
||||
|
||||
expect(copied.weight, 80.5);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -88,6 +88,23 @@ void main() {
|
||||
expect(weightEntryNew.weight, 80);
|
||||
});
|
||||
|
||||
test('findByDate matches by calendar date regardless of time', () {
|
||||
final provider = BodyWeightProvider(mockBaseProvider);
|
||||
provider.items = [
|
||||
WeightEntry(id: 1, weight: 80, date: DateTime(2021, 3, 15, 7, 15)),
|
||||
WeightEntry(id: 2, weight: 81, date: DateTime(2021, 3, 16, 20, 0)),
|
||||
];
|
||||
|
||||
// Same calendar date, different time
|
||||
final found = provider.findByDate(DateTime(2021, 3, 15, 22, 30));
|
||||
expect(found, isNotNull);
|
||||
expect(found!.id, 1);
|
||||
|
||||
// No entry for this date
|
||||
final notFound = provider.findByDate(DateTime(2021, 3, 17));
|
||||
expect(notFound, isNull);
|
||||
});
|
||||
|
||||
test('Test deleting an existing weight entry', () async {
|
||||
// Arrange
|
||||
final uri = Uri(
|
||||
|
||||
Reference in New Issue
Block a user