From 16a6cd085d8f6a3088b5c65f87eeb6d992aa673d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 5 Jun 2026 14:39:49 +0200 Subject: [PATCH] Harden detail screen pages While not very probable, it can happen that a routine etc was deleted on the server at the same time that a user had opened its detail page. We also changed the argument for the nutrition screen to ID, for more consistency with the other ones. --- lib/providers/routines_notifier.dart | 7 +- lib/screens/log_meals_screen.dart | 2 +- lib/screens/measurement_entries_screen.dart | 14 +- lib/screens/nutritional_plan_screen.dart | 56 ++++---- lib/screens/routine_edit_screen.dart | 6 +- lib/screens/routine_logs_screen.dart | 6 +- lib/screens/routine_screen.dart | 6 +- lib/widgets/core/object_gone_redirect.dart | 45 ++++++ lib/widgets/dashboard/widgets/nutrition.dart | 2 +- lib/widgets/nutrition/forms.dart | 2 +- .../nutrition/nutritional_plans_list.dart | 2 +- .../nutritional_plan_screen_test.dart | 47 ++++++- test/routine/routine_screen_test.dart | 70 ++++++++++ .../core/object_gone_redirect_test.dart | 128 ++++++++++++++++++ 14 files changed, 337 insertions(+), 56 deletions(-) create mode 100644 lib/widgets/core/object_gone_redirect.dart create mode 100644 test/widgets/core/object_gone_redirect_test.dart diff --git a/lib/providers/routines_notifier.dart b/lib/providers/routines_notifier.dart index 702d8bf42..bbc9d7e60 100644 --- a/lib/providers/routines_notifier.dart +++ b/lib/providers/routines_notifier.dart @@ -71,8 +71,11 @@ class RoutinesState { return null; } - Routine findById(int id) { - return routines.firstWhere((routine) => routine.id == id); + /// The routine with [id], or null when it isn't in the current list. Null is + /// expected (not an error): the list is a live stream, so a routine deleted on + /// another device can vanish while a detail screen is still open. + Routine? findByIdOrNull(int id) { + return routines.firstWhereOrNull((routine) => routine.id == id); } /// Return all sessions from all routines diff --git a/lib/screens/log_meals_screen.dart b/lib/screens/log_meals_screen.dart index 45b8ae4f4..847195b53 100644 --- a/lib/screens/log_meals_screen.dart +++ b/lib/screens/log_meals_screen.dart @@ -83,7 +83,7 @@ class _LogMealsScreenState extends State { onPressed: () { Navigator.of(context).pushReplacementNamed( NutritionalPlanScreen.routeName, - arguments: nutritionalPlan, + arguments: nutritionalPlan.id, ); }, ), diff --git a/lib/screens/measurement_entries_screen.dart b/lib/screens/measurement_entries_screen.dart index 70701a537..6c463c217 100644 --- a/lib/screens/measurement_entries_screen.dart +++ b/lib/screens/measurement_entries_screen.dart @@ -24,6 +24,7 @@ import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/providers/measurement_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/core/error.dart'; +import 'package:wger/widgets/core/object_gone_redirect.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/measurements/entries.dart'; import 'package:wger/widgets/measurements/forms.dart'; @@ -72,19 +73,10 @@ class _MeasurementEntriesScreenState extends ConsumerState createState() => _NutritionalPlanScreenState(); -} - -class _NutritionalPlanScreenState extends ConsumerState { - late NutritionalPlan _argumentPlan; - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - _argumentPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; - } - - @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final planId = ModalRoute.of(context)!.settings.arguments as String; const appBarForeground = Colors.white; - // Resolve the freshest plan from state so meal/diary edits reflect - // immediately. Falls back to the route argument if state hasn't streamed - // yet (e.g. cold open, deep link). + + // Wait for the catalogue to stream in, then resolve the plan by id. A loaded + // state that no longer has it means the plan was deleted (here or on another + // device): leave, rather than render a phantom plan whose meal/diary writes + // would orphan against a missing plan. final state = ref.watch(nutritionProvider).value; - final NutritionalPlan _nutritionalPlan = - state?.findByIdOrNull(_argumentPlan.id) ?? _argumentPlan; + if (state == null) { + return const Scaffold(body: Center(child: BoxedProgressIndicator())); + } + final nutritionalPlan = state.findByIdOrNull(planId); + if (nutritionalPlan == null) { + return objectGoneRedirect(context); + } return Scaffold( //appBar: getAppBar(nutritionalPlan), floatingActionButton: Row( @@ -74,7 +69,7 @@ class _NutritionalPlanScreenState extends ConsumerState { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).logIngredient, - getIngredientLogForm(_nutritionalPlan), + getIngredientLogForm(nutritionalPlan), hasListView: true, ), ); @@ -91,7 +86,7 @@ class _NutritionalPlanScreenState extends ConsumerState { onPressed: () { Navigator.of(context).pushNamed( LogMealsScreen.routeName, - arguments: _nutritionalPlan, + arguments: nutritionalPlan, ); }, child: const SvgIcon( @@ -108,7 +103,7 @@ class _NutritionalPlanScreenState extends ConsumerState { pinned: true, iconTheme: const IconThemeData(color: appBarForeground), actions: [ - if (!_nutritionalPlan.onlyLogging) + if (!nutritionalPlan.onlyLogging) IconButton( icon: const SvgIcon( icon: SvgIconData('assets/icons/meal-add.svg'), @@ -119,7 +114,7 @@ class _NutritionalPlanScreenState extends ConsumerState { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).addMeal, - MealForm(_nutritionalPlan.id!), + MealForm(nutritionalPlan.id!), ), ); }, @@ -134,13 +129,13 @@ class _NutritionalPlanScreenState extends ConsumerState { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).edit, - PlanForm(_nutritionalPlan), + PlanForm(nutritionalPlan), hasListView: true, ), ); break; case NutritionalPlanOptions.delete: - ref.read(nutritionProvider.notifier).deletePlan(_nutritionalPlan.id!); + ref.read(nutritionProvider.notifier).deletePlan(nutritionalPlan.id!); Navigator.of(context).pop(); break; } @@ -169,15 +164,12 @@ class _NutritionalPlanScreenState extends ConsumerState { flexibleSpace: FlexibleSpaceBar( titlePadding: const EdgeInsets.fromLTRB(56, 0, 56, 16), title: Text( - _nutritionalPlan.getLabel(context), + nutritionalPlan.getLabel(context), style: Theme.of(context).textTheme.titleLarge?.copyWith(color: appBarForeground), ), ), ), - if (state == null) - const SliverToBoxAdapter(child: BoxedProgressIndicator()) - else - NutritionalPlanDetailWidget(_nutritionalPlan), + NutritionalPlanDetailWidget(nutritionalPlan), ], ), ); diff --git a/lib/screens/routine_edit_screen.dart b/lib/screens/routine_edit_screen.dart index 37f7d6952..e587f1908 100644 --- a/lib/screens/routine_edit_screen.dart +++ b/lib/screens/routine_edit_screen.dart @@ -23,6 +23,7 @@ import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/core/async_value_widget.dart'; import 'package:wger/widgets/core/error.dart'; +import 'package:wger/widgets/core/object_gone_redirect.dart'; import 'package:wger/widgets/routines/routine_edit.dart'; class RoutineEditScreen extends ConsumerWidget { @@ -42,7 +43,10 @@ class RoutineEditScreen extends ConsumerWidget { body: Center(child: StreamErrorIndicator(e, stacktrace: st)), ), data: (state) { - final routine = state.findById(routineId); + final routine = state.findByIdOrNull(routineId); + if (routine == null) { + return objectGoneRedirect(context); + } return Scaffold( appBar: EmptyAppBar(routine.name), body: WidescreenWrapper(child: RoutineEdit(routine)), diff --git a/lib/screens/routine_logs_screen.dart b/lib/screens/routine_logs_screen.dart index bfbdc1ba5..41798c37e 100644 --- a/lib/screens/routine_logs_screen.dart +++ b/lib/screens/routine_logs_screen.dart @@ -23,6 +23,7 @@ import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/core/async_value_widget.dart'; import 'package:wger/widgets/core/error.dart'; +import 'package:wger/widgets/core/object_gone_redirect.dart'; import 'package:wger/widgets/routines/logs/log_overview_routine.dart'; class WorkoutLogsScreen extends ConsumerWidget { @@ -42,7 +43,10 @@ class WorkoutLogsScreen extends ConsumerWidget { body: Center(child: StreamErrorIndicator(e, stacktrace: st)), ), data: (state) { - final routine = state.findById(routineId); + final routine = state.findByIdOrNull(routineId); + if (routine == null) { + return objectGoneRedirect(context); + } return Scaffold( appBar: EmptyAppBar(routine.name), body: WidescreenWrapper(child: WorkoutLogs(routine)), diff --git a/lib/screens/routine_screen.dart b/lib/screens/routine_screen.dart index 47ac521bc..50b5b43d2 100644 --- a/lib/screens/routine_screen.dart +++ b/lib/screens/routine_screen.dart @@ -22,6 +22,7 @@ import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/widgets/core/async_value_widget.dart'; import 'package:wger/widgets/core/error.dart'; +import 'package:wger/widgets/core/object_gone_redirect.dart'; import 'package:wger/widgets/routines/app_bar.dart'; import 'package:wger/widgets/routines/routine_detail.dart'; @@ -42,7 +43,10 @@ class RoutineScreen extends ConsumerWidget { body: Center(child: StreamErrorIndicator(e, stacktrace: st)), ), data: (state) { - final routine = state.findById(routineId); + final routine = state.findByIdOrNull(routineId); + if (routine == null) { + return objectGoneRedirect(context); + } return Scaffold( appBar: RoutineDetailAppBar(routine), body: WidescreenWrapper( diff --git a/lib/widgets/core/object_gone_redirect.dart b/lib/widgets/core/object_gone_redirect.dart new file mode 100644 index 000000000..bb0266943 --- /dev/null +++ b/lib/widgets/core/object_gone_redirect.dart @@ -0,0 +1,45 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 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 . + */ + +import 'package:flutter/material.dart'; + +/// Leaves a detail screen whose object was deleted and dropped from the live +/// stream while it was open. Returns a blank placeholder and pops on the next +/// microtask (navigation isn't allowed mid-build), but only when this is the +/// current route, so an open child route (form, dialog) is left alone. Pops +/// every screen beneath it about the same object too, matched by equal route +/// argument (e.g. a routine's logs view on its detail), landing on the list. +Widget objectGoneRedirect(BuildContext context) { + Future.microtask(() { + if (!context.mounted) { + return; + } + final route = ModalRoute.of(context); + if (route == null || !route.isCurrent) { + return; + } + final navigator = Navigator.of(context); + final goneArg = route.settings.arguments; + if (goneArg == null) { + navigator.pop(); + return; + } + navigator.popUntil((r) => r.settings.arguments != goneArg); + }); + return const SizedBox.shrink(); +} diff --git a/lib/widgets/dashboard/widgets/nutrition.dart b/lib/widgets/dashboard/widgets/nutrition.dart index 4a327a95d..a27d1bfc1 100644 --- a/lib/widgets/dashboard/widgets/nutrition.dart +++ b/lib/widgets/dashboard/widgets/nutrition.dart @@ -138,7 +138,7 @@ class DashboardNutritionWidget extends ConsumerWidget { onPressed: () { Navigator.of(context).pushNamed( NutritionalPlanScreen.routeName, - arguments: plan, + arguments: plan.id, ); }, ), diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index afcf8c900..530d99c32 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -743,7 +743,7 @@ class _PlanFormState extends ConsumerState { if (context.mounted) { Navigator.of(context).pushReplacementNamed( NutritionalPlanScreen.routeName, - arguments: saved, + arguments: saved.id, ); } } diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index 8a28c9151..be0ae1237 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -118,7 +118,7 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { onTap: () { Navigator.of(context).pushNamed( NutritionalPlanScreen.routeName, - arguments: currentPlan, + arguments: currentPlan.id, ); }, title: Text(currentPlan.getLabel(context)), diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index 45647fd87..fef91cd67 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -27,6 +28,7 @@ import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; +import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/providers/body_weight_repository.dart'; import 'package:wger/providers/ingredient_repository.dart'; import 'package:wger/providers/network_provider.dart'; @@ -69,13 +71,16 @@ void main() { jsonDecode(fixture('nutrition/ingredientinfo_10065.json')), ); - // Plans, meals and logs all stream in via Drift now. + // Plans, meals and logs all stream in via Drift now. The plan under view is + // present in the streamed list (you reach the detail screen from it) with its + // meals; a list that omits it means "deleted", which routes the screen away. + final plan = getNutritionalPlan(); when( mockNutritionRepo.watchAllDrift(), - ).thenAnswer((_) => Stream.value(const [])); + ).thenAnswer((_) => Stream.value([plan])); when( mockNutritionRepo.watchAllMealsHydrated(), - ).thenAnswer((_) => Stream.value(const [])); + ).thenAnswer((_) => Stream.value(plan.meals)); when( mockNutritionRepo.watchAllLogsHydrated(), ).thenAnswer((_) => Stream.value(getTestNutritionLogs())); @@ -113,7 +118,7 @@ void main() { home: TextButton( onPressed: () => key.currentState!.push( MaterialPageRoute( - settings: RouteSettings(arguments: plan), + settings: RouteSettings(arguments: plan.id), builder: (_) => const NutritionalPlanScreen(), ), ), @@ -251,4 +256,38 @@ void main() { expect(find.textContaining('17:00'), findsOneWidget); }); + + testWidgets('a plan deleted from the stream routes away instead of showing a phantom', ( + tester, + ) async { + tester.view.physicalSize = const Size(500, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + final plan = getNutritionalPlan(); + final plansController = StreamController>(); + addTearDown(plansController.close); + when(mockNutritionRepo.watchAllDrift()).thenAnswer((_) => plansController.stream); + when(mockNutritionRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan.meals)); + + await tester.pumpWidget(createNutritionalPlan(container: makeContainer())); + plansController.add([plan]); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(find.byType(NutritionalPlanScreen), findsOneWidget); + expect(find.text('Less fat, more protein'), findsOneWidget); + + // Plan deleted (here or on another device): the stream re-emits without it. + // The screen must route away, not render a phantom whose meal/diary writes + // would orphan against a missing plan. + plansController.add(const []); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.byType(NutritionalPlanScreen), findsNothing); + }); } diff --git a/test/routine/routine_screen_test.dart b/test/routine/routine_screen_test.dart index 1e3f1ad45..65a7d4d93 100644 --- a/test/routine/routine_screen_test.dart +++ b/test/routine/routine_screen_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -38,6 +39,14 @@ class _StubRoutinesRiverpod extends RoutinesRiverpod { Stream build() => Stream.value(RoutinesState(routines: _routines)); } +class _StreamRoutinesRiverpod extends RoutinesRiverpod { + _StreamRoutinesRiverpod(this._stream); + final Stream _stream; + + @override + Stream build() => _stream; +} + void main() { installFakeAuthEnvironment(); @@ -145,4 +154,65 @@ void main() { reason: 'Delete syncs through PowerSync and works offline', ); }); + + testWidgets('a routine deleted from the live stream pops instead of crashing', ( + WidgetTester tester, + ) async { + tester.view.physicalSize = const Size(500, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + // Single-subscription (not broadcast) so the first value is buffered until + // the lazily-built provider subscribes, rather than dropped. + final controller = StreamController(); + addTearDown(controller.close); + + final key = GlobalKey(); + final container = ProviderContainer.test( + overrides: [ + networkStatusProvider.overrideWithValue(true), + routinesRiverpodProvider.overrideWith(() => _StreamRoutinesRiverpod(controller.stream)), + ], + ); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: const RouteSettings(arguments: 1), + builder: (_) => const RoutineScreen(), + ), + ), + child: const SizedBox(), + ), + ), + ), + ); + + // Routine #1 present: open the detail screen. + controller.add(RoutinesState(routines: [getTestRoutine()])); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(find.text('3 day workout'), findsOneWidget); + + // Deleted on another device: the stream re-emits without it. The detail + // screen must not crash on the missing id, it pops back to the launcher. + controller.add(const RoutinesState(routines: [])); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('3 day workout'), findsNothing); + expect(find.byType(TextButton), findsOneWidget); + }); } diff --git a/test/widgets/core/object_gone_redirect_test.dart b/test/widgets/core/object_gone_redirect_test.dart new file mode 100644 index 000000000..f4def2cae --- /dev/null +++ b/test/widgets/core/object_gone_redirect_test.dart @@ -0,0 +1,128 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/widgets/core/object_gone_redirect.dart'; + +void main() { + /// Pushes a detail route whose body flips to [objectGoneRedirect] once [gone] + /// is true. Returns the navigator key for pushing further routes. + Future> pumpDetail( + WidgetTester tester, + ValueNotifier gone, + ) async { + final key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + home: const Scaffold(body: Text('list')), + ), + ); + key.currentState!.push( + MaterialPageRoute( + builder: (_) => ValueListenableBuilder( + valueListenable: gone, + builder: (context, isGone, _) => + isGone ? objectGoneRedirect(context) : const Scaffold(body: Text('detail')), + ), + ), + ); + await tester.pumpAndSettle(); + return key; + } + + testWidgets('pops the detail screen when it is the current route', (tester) async { + final gone = ValueNotifier(false); + addTearDown(gone.dispose); + await pumpDetail(tester, gone); + expect(find.text('detail'), findsOneWidget); + + gone.value = true; + await tester.pumpAndSettle(); + + expect(find.text('detail'), findsNothing); + expect(find.text('list'), findsOneWidget); + }); + + testWidgets('does not tear down a child route opened on top of the detail screen', ( + tester, + ) async { + final gone = ValueNotifier(false); + addTearDown(gone.dispose); + final key = await pumpDetail(tester, gone); + + // Open a child route (edit form, dialog, …) on top of the detail screen. + key.currentState!.push( + MaterialPageRoute(builder: (_) => const Scaffold(body: Text('child'))), + ); + await tester.pumpAndSettle(); + expect(find.text('child'), findsOneWidget); + + // The object is deleted while the child is open: the detail rebuilds + // underneath. The child must stay, since the detail is not the current route. + gone.value = true; + await tester.pumpAndSettle(); + + expect(find.text('child'), findsOneWidget); + }); + + testWidgets('pops the whole chain of screens about the same object', (tester) async { + final gone = ValueNotifier(false); + addTearDown(gone.dispose); + final key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + home: const Scaffold(body: Text('list')), + ), + ); + + // Two screens about object id 5 (e.g. routine detail, then its logs view), + // both pushed with the same id argument and both watching [gone]. + Widget goneOr(String label) => ValueListenableBuilder( + valueListenable: gone, + builder: (context, isGone, _) => + isGone ? objectGoneRedirect(context) : Scaffold(body: Text(label)), + ); + key.currentState!.push( + MaterialPageRoute( + settings: const RouteSettings(arguments: 5), + builder: (_) => goneOr('detail'), + ), + ); + await tester.pumpAndSettle(); + key.currentState!.push( + MaterialPageRoute( + settings: const RouteSettings(arguments: 5), + builder: (_) => goneOr('logs'), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('logs'), findsOneWidget); + + // Object deleted: both same-id screens drop, landing on the list, not on a + // blank intermediate detail screen. + gone.value = true; + await tester.pumpAndSettle(); + + expect(find.text('logs'), findsNothing); + expect(find.text('detail'), findsNothing); + expect(find.text('list'), findsOneWidget); + }); +}