Make the measurements a tab of their own, led by the weight

This commit is contained in:
Roland Geider
2026-08-07 21:46:23 +02:00
parent 795437777e
commit d6de435c6b
13 changed files with 200 additions and 92 deletions

View File

@@ -23,7 +23,7 @@ import 'package:wger/core/dashboard.dart';
import 'package:wger/core/material.dart';
import 'package:wger/features/gallery/screens/gallery_screen.dart';
import 'package:wger/features/health/providers/health_sync.dart';
import 'package:wger/features/measurements/screens/weight_screen.dart';
import 'package:wger/features/measurements/screens/measurement_categories_screen.dart';
import 'package:wger/features/nutrition/screens/nutritional_plans_screen.dart';
import 'package:wger/features/routines/screens/routine_list_screen.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
@@ -74,7 +74,7 @@ class _HomeTabsScreenState extends ConsumerState<HomeTabsScreen>
const DashboardScreen(),
const RoutineListScreen(),
const NutritionalPlansScreen(),
const WeightScreen(),
const MeasurementCategoriesScreen(),
const GalleryScreen(),
];
@@ -95,7 +95,7 @@ class _HomeTabsScreenState extends ConsumerState<HomeTabsScreen>
),
NavigationDestination(
icon: const FaIcon(FontAwesomeIcons.weightScale, size: 20),
label: AppLocalizations.of(context).weight,
label: AppLocalizations.of(context).labelBottomNavBody,
),
NavigationDestination(
icon: const Icon(Icons.photo_library),

View File

@@ -33,7 +33,7 @@ class MeasurementCategoriesScreen extends StatelessWidget {
final i18n = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).measurements),
title: Text(i18n.labelBottomNavBody),
actions: [
IconButton(
icon: const Icon(Icons.sort),

View File

@@ -82,28 +82,14 @@ class _WeightScreenState extends ConsumerState<WeightScreen> {
child: SingleChildScrollView(
child: category == null || profile == null
? const BoxedProgressIndicator()
: Column(
children: [
EntriesList(
category,
range: _range,
onRangeChanged: (range) => setState(() => _range = range),
title: i18n.weight,
displayUnit: weightDisplayUnit(profile.isMetric),
displayUnitLabel: weightUnit(profile.isMetric, context),
editFormBuilder: (entry) => WeightForm(category, entry),
),
TextButton(
onPressed: () => Navigator.pushNamed(context, '/measurement-categories'),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(i18n.measurements),
const Icon(Icons.chevron_right),
],
),
),
],
: EntriesList(
category,
range: _range,
onRangeChanged: (range) => setState(() => _range = range),
title: i18n.weight,
displayUnit: weightDisplayUnit(profile.isMetric),
displayUnitLabel: weightUnit(profile.isMetric, context),
editFormBuilder: (entry) => WeightForm(category, entry),
),
),
),

View File

@@ -19,10 +19,17 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/widgets/async_value_widget.dart';
import 'package:wger/features/account/providers/user_profile_notifier.dart';
import 'package:wger/features/measurements/charts/range.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/unit_conversion.dart';
import 'package:wger/features/measurements/providers/body_weight_provider.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
import 'package:wger/features/measurements/screens/weight_screen.dart';
import 'package:wger/features/measurements/widgets/chart_range_selector.dart';
import 'package:wger/features/measurements/widgets/charts.dart';
import 'package:wger/features/measurements/widgets/weight_form.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'categories_card.dart';
@@ -47,11 +54,17 @@ class _CategoriesListState extends ConsumerState<CategoriesList> {
loggerName: 'CategoriesList',
data: (categoriesList) {
// Children of multi-value groups are rendered inside their parent's
// card, not as own list items. Body weight has its own screens.
// card, not as own list items. Body weight leads the list below
// instead of taking its position among the others.
final topLevel = categoriesList
.where((c) => c.parentId == null && !c.isOfficialBodyWeight)
.toList();
final cards = [
?_weightCard(),
for (final category in topLevel) CategoriesCard(category, range: _range),
];
return Column(
children: [
const SizedBox(height: 10),
@@ -62,8 +75,8 @@ class _CategoriesListState extends ConsumerState<CategoriesList> {
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: topLevel.length,
itemBuilder: (context, index) => CategoriesCard(topLevel[index], range: _range),
itemCount: cards.length,
itemBuilder: (context, index) => cards[index],
),
),
],
@@ -71,4 +84,27 @@ class _CategoriesListState extends ConsumerState<CategoriesList> {
},
);
}
/// The body weight card, null while what it needs is still syncing.
///
/// Presented like the weight screen it leads to rather than like the
/// category it is stored as: the values are shown in the profile unit
/// (entries can be stored in kg or lb) and entered with the quick steppers.
Widget? _weightCard() {
final category = ref.watch(bodyWeightCategoryOnlyProvider).value;
final profile = ref.watch(userProfileProvider).value;
if (category == null || profile == null) {
return null;
}
return CategoriesCard(
category,
range: _range,
title: AppLocalizations.of(context).weight,
displayUnit: weightDisplayUnit(profile.isMetric),
displayUnitLabel: weightUnit(profile.isMetric, context),
newEntryForm: WeightForm(category),
onShowDetails: () => Navigator.pushNamed(context, WeightScreen.routeName),
);
}
}

View File

@@ -40,10 +40,35 @@ class CategoriesCard extends ConsumerWidget {
final double? elevation;
final ChartRange range;
/// Name the card is titled with, `category.displayName` by default. Body
/// weight is titled like the screen it leads to.
final String? title;
/// Unit the values are converted to, `category.unit` by default. Body weight
/// is shown in the profile unit, since its entries can be stored in either.
final String? displayUnit;
/// Label for [displayUnit], the unit itself by default. The two differ where
/// the unit is translated (kg reads كغم in Arabic).
final String? displayUnitLabel;
/// Form the add action opens, [MeasurementEntryForm] by default. Body weight
/// has one of its own, with quick steppers and a unit dropdown.
final Widget? newEntryForm;
/// What the detail link opens, the entries screen of the category by
/// default. Body weight has a screen of its own.
final VoidCallback? onShowDetails;
const CategoriesCard(
this.currentCategory, {
this.elevation,
this.range = ChartRange.last3Months,
this.title,
this.displayUnit,
this.displayUnitLabel,
this.newEntryForm,
this.onShowDetails,
});
@override
@@ -61,7 +86,7 @@ class CategoriesCard extends ConsumerWidget {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Text(
currentCategory.displayName(context),
title ?? currentCategory.displayName(context),
style: Theme.of(context).textTheme.titleLarge,
textAlign: TextAlign.center,
maxLines: 2,
@@ -70,7 +95,7 @@ class CategoriesCard extends ConsumerWidget {
),
MeasurementChartArea<List<MeasurementChartEntry>>(
identity: currentCategory.id!,
watch: (ref) => chartPointsFor(ref, currentCategory, range),
watch: (ref) => chartPointsFor(ref, currentCategory, range, targetUnit: displayUnit),
builder: _chart,
// The card is one of many on the overview; a failing query takes
// its chart, not the way into the category
@@ -87,14 +112,16 @@ class CategoriesCard extends ConsumerWidget {
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed:
onShowDetails ??
() {
Navigator.pushNamed(
context,
MeasurementEntriesScreen.routeName,
arguments: currentCategory.id,
);
},
child: Text(AppLocalizations.of(context).goToDetailPage),
onPressed: () {
Navigator.pushNamed(
context,
MeasurementEntriesScreen.routeName,
arguments: currentCategory.id,
);
},
),
IconButton(
onPressed: () async {
@@ -103,7 +130,7 @@ class CategoriesCard extends ConsumerWidget {
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newEntry,
MeasurementEntryForm(currentCategory.id!),
newEntryForm ?? MeasurementEntryForm(currentCategory.id!),
),
);
},
@@ -125,6 +152,8 @@ class CategoriesCard extends ConsumerWidget {
List<Widget> _chart(BuildContext context, List<MeasurementChartEntry> allPoints) {
final settings = currentCategory.chartSettings;
final (:entries, :average) = chartSeriesFor(allPoints, range, settings);
final unit = displayUnit ?? currentCategory.unit;
final unitLabel = displayUnitLabel ?? unit;
return [
Container(
@@ -134,14 +163,14 @@ class CategoriesCard extends ConsumerWidget {
currentCategory.metricType,
entries,
average,
currentCategory.unit,
unitLabel,
chartType: currentCategory.chartType,
settings: settings,
distribution: MeasurementDistributionChart(
category: currentCategory,
range: range,
unitLabel: currentCategory.unit,
targetUnit: currentCategory.unit,
unitLabel: unitLabel,
targetUnit: unit,
),
),
),
@@ -149,7 +178,7 @@ class CategoriesCard extends ConsumerWidget {
MeasurementOverallChangeWidget(
average.first,
average.last,
currentCategory.unit,
unitLabel,
),
];
}

View File

@@ -1184,5 +1184,6 @@
"healthSyncFailed": "Der letzte Abgleich konnte nicht abgeschlossen werden",
"healthConnectInstall": "Health Connect installieren",
"healthConnectUpdate": "Health Connect aktualisieren",
"healthConnectRequired": "Health Connect wird benötigt, um Körpermesswerte zu importieren"
"healthConnectRequired": "Health Connect wird benötigt, um Körpermesswerte zu importieren",
"labelBottomNavBody": "Körper"
}

View File

@@ -174,6 +174,10 @@
"@labelBottomNavNutrition": {
"description": "Label used in bottom navigation, use a short word"
},
"labelBottomNavBody": "Body",
"@labelBottomNavBody": {
"description": "Label used in bottom navigation and as the title of the screen holding the body weight and the other measurements, use a short word"
},
"labelWorkoutLogs": "Training logs",
"@labelWorkoutLogs": {
"description": "(Workout) logs"

View File

@@ -1223,5 +1223,6 @@
"healthSyncFailed": "No se ha podido completar la última sincronización",
"healthConnectInstall": "Instalar Health Connect",
"healthConnectUpdate": "Actualizar Health Connect",
"healthConnectRequired": "Health Connect es necesario para importar medidas corporales"
"healthConnectRequired": "Health Connect es necesario para importar medidas corporales",
"labelBottomNavBody": "Cuerpo"
}

View File

@@ -1194,5 +1194,6 @@
"healthSyncFailed": "La dernière synchronisation n'a pas pu être terminée",
"healthConnectInstall": "Installer Health Connect",
"healthConnectUpdate": "Mettre à jour Health Connect",
"healthConnectRequired": "Health Connect est nécessaire pour importer les mensurations"
"healthConnectRequired": "Health Connect est nécessaire pour importer les mensurations",
"labelBottomNavBody": "Corps"
}

View File

@@ -646,6 +646,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String get labelBottomNavBody =>
(super.noSuchMethod(
Invocation.getter(#labelBottomNavBody),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#labelBottomNavBody),
),
)
as String);
@override
String get labelWorkoutLogs =>
(super.noSuchMethod(
@@ -2346,6 +2357,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String get metricLeanBodyMass =>
(super.noSuchMethod(
Invocation.getter(#metricLeanBodyMass),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#metricLeanBodyMass),
),
)
as String);
@override
String get metricBodyFat =>
(super.noSuchMethod(
@@ -2423,6 +2445,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String get metricBloodOxygen =>
(super.noSuchMethod(
Invocation.getter(#metricBloodOxygen),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#metricBloodOxygen),
),
)
as String);
@override
String get metricSteps =>
(super.noSuchMethod(
@@ -5347,50 +5380,6 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String chartAllTimeTitle(String? name) =>
(super.noSuchMethod(
Invocation.method(#chartAllTimeTitle, [name]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chartAllTimeTitle, [name]),
),
)
as String);
@override
String chart30DaysTitle(String? name) =>
(super.noSuchMethod(
Invocation.method(#chart30DaysTitle, [name]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chart30DaysTitle, [name]),
),
)
as String);
@override
String chartLastYearTitle(String? name) =>
(super.noSuchMethod(
Invocation.method(#chartLastYearTitle, [name]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chartLastYearTitle, [name]),
),
)
as String);
@override
String chartLast3MonthsTitle(String? name) =>
(super.noSuchMethod(
Invocation.method(#chartLast3MonthsTitle, [name]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#chartLast3MonthsTitle, [name]),
),
)
as String);
@override
String chartRangeMonths(int? count) =>
(super.noSuchMethod(

View File

@@ -62,7 +62,7 @@ void main() {
await tester.pumpWidget(createMeasurementScreen());
await tester.pumpAndSettle();
expect(find.text('Measurements'), findsOneWidget);
expect(find.text('Body'), findsOneWidget);
expect(find.text('Body fat'), findsOneWidget);
expect(find.text('Biceps'), findsOneWidget);
expect(find.text('Blood pressure'), findsOneWidget);

View File

@@ -20,6 +20,8 @@ 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';
import 'package:wger/features/account/providers/user_profile_repository.dart';
import 'package:wger/features/measurements/models/measurement_category.dart';
import 'package:wger/features/measurements/models/measurement_entry.dart';
import 'package:wger/features/measurements/providers/measurement_notifier.dart';
@@ -28,7 +30,9 @@ import 'package:wger/features/measurements/widgets/categories.dart';
import 'package:wger/features/measurements/widgets/categories_card.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import '../../../../test_data/body_weight.dart';
import '../../../../test_data/measurements.dart';
import '../../../../test_data/profile.dart';
import '../../../helpers/measurement_chart_buckets.dart';
import '../../../helpers/measurement_repository_stubs.dart';
import 'categories_test.mocks.dart';
@@ -38,9 +42,15 @@ Widget _wrap(
List<MeasurementCategory> categories = const [],
Map<String, List<MeasurementEntry>> entries = const {},
}) {
// The weight card needs the display unit, so it only appears once the
// profile is there
final mockProfileRepo = MockUserProfileRepository();
when(mockProfileRepo.watchDrift()).thenAnswer((_) => Stream.value(tUserProfile1));
return ProviderScope(
overrides: [
measurementRepositoryProvider.overrideWithValue(mockRepo),
userProfileRepositoryProvider.overrideWithValue(mockProfileRepo),
// The cards read their chart points from the aggregated queries
measurementChartBucketsProvider.overrideWith(chartBucketsFrom(entries)),
measurementGroupBucketsProvider.overrideWith(groupBucketsFrom(categories, entries)),
@@ -53,7 +63,7 @@ Widget _wrap(
);
}
@GenerateMocks([MeasurementRepository])
@GenerateMocks([MeasurementRepository, UserProfileRepository])
void main() {
late MockMeasurementRepository mockRepo;
@@ -97,6 +107,29 @@ void main() {
expect(find.text('Diastolic'), findsOneWidget);
});
testWidgets('body weight leads the list, wherever it is sorted', (tester) async {
// The card is the way into the weight screen, so it stays on top rather
// than taking the position the category order gives it
final categories = [...getMeasurementCategories(), getBodyWeightCategory()];
final entries = {...getMeasurementEntries(), ...bodyWeightEntries()};
stubMeasurementReads(mockRepo, categories, entries);
// Tall enough for all three cards; the list builds only what it shows
tester.view.physicalSize = const Size(800, 2200);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(_wrap(mockRepo, categories: categories, entries: entries));
await tester.pumpAndSettle();
// Once, at the top: the official category is left out of the list below
expect(find.byType(CategoriesCard), findsNWidgets(3));
expect(find.text('Weight'), findsOneWidget);
expect(
tester.getTopLeft(find.text('Weight')).dy,
lessThan(tester.getTopLeft(find.text('Body fat')).dy),
);
});
testWidgets('empty list renders no CategoriesCard', (tester) async {
stubMeasurementReads(mockRepo, []);

View File

@@ -6,6 +6,8 @@
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:wger/features/account/models/user_profile.dart' as _i8;
import 'package:wger/features/account/providers/user_profile_repository.dart' as _i7;
import 'package:wger/features/measurements/models/measurement_bucket.dart' as _i6;
import 'package:wger/features/measurements/models/measurement_category.dart' as _i4;
import 'package:wger/features/measurements/models/measurement_entry.dart' as _i5;
@@ -279,3 +281,29 @@ class MockMeasurementRepository extends _i1.Mock implements _i2.MeasurementRepos
)
as _i3.Future<void>);
}
/// A class which mocks [UserProfileRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockUserProfileRepository extends _i1.Mock implements _i7.UserProfileRepository {
MockUserProfileRepository() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<_i8.UserProfile?> watchDrift() =>
(super.noSuchMethod(
Invocation.method(#watchDrift, []),
returnValue: _i3.Stream<_i8.UserProfile?>.empty(),
)
as _i3.Stream<_i8.UserProfile?>);
@override
_i3.Future<void> editLocalDrift(_i8.UserProfile? profile) =>
(super.noSuchMethod(
Invocation.method(#editLocalDrift, [profile]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}