diff --git a/integration_test/1_dashboard.dart b/integration_test/1_dashboard.dart index 6f2f2819b..44d2b464a 100644 --- a/integration_test/1_dashboard.dart +++ b/integration_test/1_dashboard.dart @@ -94,8 +94,10 @@ Widget createDashboardScreen({Locale? locale}) { galleryRepositoryProvider.overrideWithValue(mockGalleryRepo), ], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine(exercises: getScreenshotExercises())], + container.read(routinesRiverpodProvider.notifier).state = AsyncData( + RoutinesState( + routines: [getTestRoutine(exercises: getScreenshotExercises())], + ), ); // Seed the nutrition notifier with the screenshot plan so the dashboard can diff --git a/integration_test/2_workout.dart b/integration_test/2_workout.dart index 2536e4afa..8abcd407d 100644 --- a/integration_test/2_workout.dart +++ b/integration_test/2_workout.dart @@ -32,8 +32,10 @@ Widget createWorkoutDetailScreen({Locale? locale}) { final routine = getTestRoutine(exercises: getScreenshotExercises()); final container = riverpod.ProviderContainer.test(); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine(exercises: getScreenshotExercises())], + container.read(routinesRiverpodProvider.notifier).state = riverpod.AsyncData( + RoutinesState( + routines: [getTestRoutine(exercises: getScreenshotExercises())], + ), ); return MediaQuery( diff --git a/integration_test/3_gym_mode.dart b/integration_test/3_gym_mode.dart index aa3d6a568..493b872e1 100644 --- a/integration_test/3_gym_mode.dart +++ b/integration_test/3_gym_mode.dart @@ -1,7 +1,26 @@ +/* + * 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:clock/clock.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/exercise_state.dart'; import 'package:wger/providers/exercise_state_notifier.dart'; import 'package:wger/providers/gym_state.dart'; @@ -14,6 +33,14 @@ import 'package:wger/widgets/routines/gym_mode/summary.dart'; import '../test_data/exercises.dart'; import '../test_data/routines.dart'; +class _StubRoutinesRiverpod extends RoutinesRiverpod { + _StubRoutinesRiverpod(this._routines); + final List _routines; + + @override + Future build() async => RoutinesState(routines: _routines); +} + Widget createGymModeScreen({Locale? locale}) { locale ??= const Locale('en'); final key = GlobalKey(); @@ -24,8 +51,10 @@ Widget createGymModeScreen({Locale? locale}) { exerciseStateProvider.overrideWithValue(ExerciseState(exercises: getTestExercises())), ], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine(exercises: getScreenshotExercises())], + container.read(routinesRiverpodProvider.notifier).state = riverpod.AsyncData( + RoutinesState( + routines: [getTestRoutine(exercises: getScreenshotExercises())], + ), ); return MediaQuery( @@ -81,7 +110,9 @@ Widget createGymModeResultsScreen({String locale = 'en'}) { showTimerPages: true, ), ), - routinesRiverpodProvider.overrideWithValue(RoutinesState(routines: [routine])), + routinesRiverpodProvider.overrideWith( + () => _StubRoutinesRiverpod([routine]), + ), ], ), diff --git a/lib/providers/routines.dart b/lib/providers/routines.dart index 5e2ab7cfc..e5e5da31e 100644 --- a/lib/providers/routines.dart +++ b/lib/providers/routines.dart @@ -16,8 +16,6 @@ * along with this program. If not, see . */ -import 'dart:async'; - import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/database/powersync/database.dart'; @@ -94,36 +92,34 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { final _logger = Logger('RoutinesRiverpod'); @override - RoutinesState build() { + Future build() async { _logger.fine('Building Routines Riverpod notifier'); - // Kick off the initial sparse load. UI consumers `watch`ing this - // provider rebuild automatically once `state` is updated. Errors are - // logged but don't crash the build. - Future.microtask(() async { - try { - await fetchAllRoutinesSparse(); - } catch (e, s) { - _logger.warning('initial routine fetch failed', e, s); - } - }); - - return const RoutinesState(); + // Auto-fetch the sparse routine list on first read. Consumers that need + // a forced refresh can still call [fetchAllRoutinesSparse] explicitly. + final repo = ref.read(routinesRepositoryProvider); + final routines = await repo.fetchAllRoutinesSparseServer(); + return RoutinesState(routines: routines); } + /// Returns the current state value or a blank default. Callers that + /// mutate state should always compose on top of this. + RoutinesState _currentOrEmpty() => state.asData?.value ?? const RoutinesState(); + /* * Routines */ Future fetchAllRoutinesSparse() async { final repo = ref.read(routinesRepositoryProvider); final routines = await repo.fetchAllRoutinesSparseServer(); - state = state.copyWith(routines: routines); + state = AsyncData(_currentOrEmpty().copyWith(routines: routines)); } Future addRoutine(Routine routine) async { final repo = ref.read(routinesRepositoryProvider); final created = await repo.addRoutineServer(routine); - state = state.copyWith(routines: [created, ...state.routines]); + final current = _currentOrEmpty(); + state = AsyncData(current.copyWith(routines: [created, ...current.routines])); return created; } @@ -157,14 +153,15 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { setExercisesAndUnits(routine.dayData); // Update state - final updatedRoutines = [...state.routines]; + final current = _currentOrEmpty(); + final updatedRoutines = [...current.routines]; final index = updatedRoutines.indexWhere((r) => r.id == routineId); if (index != -1) { updatedRoutines[index] = routine; } else { updatedRoutines.add(routine); } - state = state.copyWith(routines: updatedRoutines); + state = AsyncData(current.copyWith(routines: updatedRoutines)); return routine; } @@ -173,19 +170,22 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { final repo = ref.read(routinesRepositoryProvider); await repo.deleteRoutineServer(routineId); - final routineIndex = state.routines.indexWhere((element) => element.id == routineId); - state.routines.removeAt(routineIndex); + final current = _currentOrEmpty(); + final updatedRoutines = [...current.routines] + ..removeWhere((element) => element.id == routineId); + state = AsyncData(current.copyWith(routines: updatedRoutines)); } Future editRoutine(Routine routine) async { final repo = ref.read(routinesRepositoryProvider); final updatedRoutine = await repo.editRoutineServer(routine); - final updatedRoutines = [...state.routines]; + final current = _currentOrEmpty(); + final updatedRoutines = [...current.routines]; final index = updatedRoutines.indexWhere((r) => r.id == routine.id); if (index != -1) { updatedRoutines[index] = updatedRoutine; - state = state.copyWith(routines: updatedRoutines); + state = AsyncData(current.copyWith(routines: updatedRoutines)); } } @@ -300,7 +300,7 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { } } -@riverpod +@Riverpod(keepAlive: true) RoutinesRepository routinesRepository(Ref ref) { final baseProvider = ref.watch(wgerBaseProvider); return RoutinesRepository(baseProvider); diff --git a/lib/providers/routines.g.dart b/lib/providers/routines.g.dart index c0b7c1a98..65fe7f3bd 100644 --- a/lib/providers/routines.g.dart +++ b/lib/providers/routines.g.dart @@ -90,7 +90,8 @@ String _$routineRepetitionUnitHash() => r'7754a0197c3fed27feea2c6d33d5e5a5e1deab @ProviderFor(RoutinesRiverpod) final routinesRiverpodProvider = RoutinesRiverpodProvider._(); -final class RoutinesRiverpodProvider extends $NotifierProvider { +final class RoutinesRiverpodProvider + extends $AsyncNotifierProvider { RoutinesRiverpodProvider._() : super( from: null, @@ -108,29 +109,21 @@ final class RoutinesRiverpodProvider extends $NotifierProvider RoutinesRiverpod(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(RoutinesState value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } } -String _$routinesRiverpodHash() => r'83e7e418dcd7adc36e8897598927c6a7b47a33c9'; +String _$routinesRiverpodHash() => r'c10fb6498ffd50152051a625089c53fc9fdd6be8'; -abstract class _$RoutinesRiverpod extends $Notifier { - RoutinesState build(); +abstract class _$RoutinesRiverpod extends $AsyncNotifier { + FutureOr build(); @$mustCallSuper @override void runBuild() { - final ref = this.ref as $Ref; + final ref = this.ref as $Ref, RoutinesState>; final element = ref.element as $ClassProviderElement< - AnyNotifier, - RoutinesState, + AnyNotifier, RoutinesState>, + AsyncValue, Object?, Object? >; diff --git a/lib/screens/routine_edit_screen.dart b/lib/screens/routine_edit_screen.dart index d77ea114f..9ef4331b1 100644 --- a/lib/screens/routine_edit_screen.dart +++ b/lib/screens/routine_edit_screen.dart @@ -31,11 +31,18 @@ class RoutineEditScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final routineId = ModalRoute.of(context)!.settings.arguments as int; - final routine = ref.read(routinesRiverpodProvider).findById(routineId); + final routinesState = ref.watch(routinesRiverpodProvider); - return Scaffold( - appBar: EmptyAppBar(routine.name), - body: WidescreenWrapper(child: RoutineEdit(routine)), + return routinesState.when( + data: (state) { + final routine = state.findById(routineId); + return Scaffold( + appBar: EmptyAppBar(routine.name), + body: WidescreenWrapper(child: RoutineEdit(routine)), + ); + }, + loading: () => const Scaffold(body: Center(child: CircularProgressIndicator())), + error: (e, st) => Scaffold(body: Center(child: Text('$e'))), ); } } diff --git a/lib/screens/routine_logs_screen.dart b/lib/screens/routine_logs_screen.dart index 6858955ab..0e20f570b 100644 --- a/lib/screens/routine_logs_screen.dart +++ b/lib/screens/routine_logs_screen.dart @@ -31,11 +31,18 @@ class WorkoutLogsScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final routineId = ModalRoute.of(context)!.settings.arguments as int; - final routine = ref.read(routinesRiverpodProvider).findById(routineId); + final routinesState = ref.watch(routinesRiverpodProvider); - return Scaffold( - appBar: EmptyAppBar(routine.name), - body: WidescreenWrapper(child: WorkoutLogs(routine)), + return routinesState.when( + data: (state) { + final routine = state.findById(routineId); + return Scaffold( + appBar: EmptyAppBar(routine.name), + body: WidescreenWrapper(child: WorkoutLogs(routine)), + ); + }, + loading: () => const Scaffold(body: Center(child: CircularProgressIndicator())), + error: (e, st) => Scaffold(body: Center(child: Text('$e'))), ); } } diff --git a/lib/screens/routine_screen.dart b/lib/screens/routine_screen.dart index 6e4ebe261..7cfecfb79 100644 --- a/lib/screens/routine_screen.dart +++ b/lib/screens/routine_screen.dart @@ -31,17 +31,22 @@ class RoutineScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final routineId = ModalRoute.of(context)!.settings.arguments as int; - final routineState = ref.read(routinesRiverpodProvider); + final routinesState = ref.watch(routinesRiverpodProvider); - final routine = routineState.findById(routineId); - - return Scaffold( - appBar: RoutineDetailAppBar(routine), - body: WidescreenWrapper( - child: SingleChildScrollView( - child: RoutineDetail(routine), - ), - ), + return routinesState.when( + data: (state) { + final routine = state.findById(routineId); + return Scaffold( + appBar: RoutineDetailAppBar(routine), + body: WidescreenWrapper( + child: SingleChildScrollView( + child: RoutineDetail(routine), + ), + ), + ); + }, + loading: () => const Scaffold(body: Center(child: CircularProgressIndicator())), + error: (e, st) => Scaffold(body: Center(child: Text('$e'))), ); } } diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index dd907f079..33ce4935e 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -26,6 +26,7 @@ import 'package:wger/helpers/json.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/models/measurements/measurement_category.dart'; +import 'package:wger/models/workouts/session.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/measurement_notifier.dart'; import 'package:wger/providers/nutrition_notifier.dart'; @@ -149,8 +150,8 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState[]) { final date = DateFormatLists.format(session.date); if (!newEvents.containsKey(date)) { newEvents[date] = []; @@ -249,9 +250,6 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState>>(weightEntryProvider, (prev, next) { loadEvents(); }); @@ -261,6 +259,9 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState @override Widget build(BuildContext context) { final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); - final routine = ref.watch(routinesRiverpodProvider).currentRoutine; + final routine = ref.watch(routinesRiverpodProvider).value?.currentRoutine; _hasContent = routine != null; return Card( diff --git a/lib/widgets/routines/routines_list.dart b/lib/widgets/routines/routines_list.dart index 22172dcd0..b4e79e3ba 100644 --- a/lib/widgets/routines/routines_list.dart +++ b/lib/widgets/routines/routines_list.dart @@ -40,17 +40,17 @@ class _RoutinesListState extends ConsumerState { final isOnline = ref.watch(networkStatusProvider); final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); final routineProvider = ref.read(routinesRiverpodProvider.notifier); - final routinesState = ref.read(routinesRiverpodProvider); + final routines = ref.watch(routinesRiverpodProvider).value?.routines ?? const []; return RefreshIndicator( onRefresh: isOnline ? () => routineProvider.fetchAllRoutinesSparse() : () async {}, - child: routinesState.routines.isEmpty + child: routines.isEmpty ? const TextPrompt() : ListView.builder( padding: const EdgeInsets.all(10.0), - itemCount: routinesState.routines.length, + itemCount: routines.length, itemBuilder: (context, index) { - final currentRoutine = routinesState.routines[index]; + final currentRoutine = routines[index]; return Card( child: ListTile( diff --git a/test/routine/forms/slot_form_test.dart b/test/routine/forms/slot_form_test.dart index b89b797ef..4672e6de8 100644 --- a/test/routine/forms/slot_form_test.dart +++ b/test/routine/forms/slot_form_test.dart @@ -153,8 +153,10 @@ void main() { routinesRepositoryProvider.overrideWithValue(mockRepo), ], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [routine], + container.read(routinesRiverpodProvider.notifier).state = AsyncData( + RoutinesState( + routines: [routine], + ), ); return UncontrolledProviderScope( diff --git a/test/routine/gym_mode/gym_mode_test.dart b/test/routine/gym_mode/gym_mode_test.dart index 542cb2d0f..2e28f5429 100644 --- a/test/routine/gym_mode/gym_mode_test.dart +++ b/test/routine/gym_mode/gym_mode_test.dart @@ -54,7 +54,7 @@ class _FakeRoutinesRiverpod extends RoutinesRiverpod { final Routine _routine; @override - RoutinesState build() => RoutinesState(routines: [_routine]); + Future build() async => RoutinesState(routines: [_routine]); @override Future fetchAndSetRoutineFull(int routineId) async => _routine; diff --git a/test/routine/routine_edit_screen_test.dart b/test/routine/routine_edit_screen_test.dart index ae1da1d52..ef586f662 100644 --- a/test/routine/routine_edit_screen_test.dart +++ b/test/routine/routine_edit_screen_test.dart @@ -20,19 +20,30 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/screens/routine_edit_screen.dart'; import '../../test_data/routines.dart'; +class _StubRoutinesRiverpod extends RoutinesRiverpod { + _StubRoutinesRiverpod(this._routines); + final List _routines; + + @override + Future build() async => RoutinesState(routines: _routines); +} + void main() { final key = GlobalKey(); testWidgets('RoutineEditScreen smoke test', (WidgetTester tester) async { - final container = ProviderContainer.test(); - - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine()], + final container = ProviderContainer.test( + overrides: [ + routinesRiverpodProvider.overrideWith( + () => _StubRoutinesRiverpod([getTestRoutine()]), + ), + ], ); await tester.pumpWidget( diff --git a/test/routine/routine_logs_screen_test.dart b/test/routine/routine_logs_screen_test.dart index 24c91f5d8..abf08d88f 100644 --- a/test/routine/routine_logs_screen_test.dart +++ b/test/routine/routine_logs_screen_test.dart @@ -38,6 +38,14 @@ import '../../test_data/routines.dart'; import '../test_data/trophies.dart'; import 'routine_logs_screen_test.mocks.dart'; +class _StubRoutinesRiverpod extends RoutinesRiverpod { + _StubRoutinesRiverpod(this._routines); + final List _routines; + + @override + Future build() async => RoutinesState(routines: _routines); +} + @GenerateMocks([TrophyRepository, WorkoutLogRepository]) void main() { late Routine routine; @@ -66,11 +74,12 @@ void main() { networkStatusProvider.overrideWithValue(isOnline), workoutLogRepositoryProvider.overrideWithValue(mockWorkoutLogRepository), trophyRepositoryProvider.overrideWithValue(mockRepository), + routinesRiverpodProvider.overrideWith( + () => _StubRoutinesRiverpod([routine]), + ), ], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState(routines: [routine]); - return UncontrolledProviderScope( container: container, child: MaterialApp( diff --git a/test/routine/routine_screen_test.dart b/test/routine/routine_screen_test.dart index 67f4f0a22..2dbcfeaf9 100644 --- a/test/routine/routine_screen_test.dart +++ b/test/routine/routine_screen_test.dart @@ -22,21 +22,32 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/screens/routine_screen.dart'; import '../../test_data/routines.dart'; +class _StubRoutinesRiverpod extends RoutinesRiverpod { + _StubRoutinesRiverpod(this._routines); + final List _routines; + + @override + Future build() async => RoutinesState(routines: _routines); +} + void main() { Widget renderWidget({locale = 'en'}) { final key = GlobalKey(); final container = ProviderContainer.test( - overrides: [networkStatusProvider.overrideWithValue(true)], - ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine()], + overrides: [ + networkStatusProvider.overrideWithValue(true), + routinesRiverpodProvider.overrideWith( + () => _StubRoutinesRiverpod([getTestRoutine()]), + ), + ], ); return UncontrolledProviderScope( diff --git a/test/routine/routines_provider_test.dart b/test/routine/routines_provider_test.dart index ec608b728..9480c43b2 100644 --- a/test/routine/routines_provider_test.dart +++ b/test/routine/routines_provider_test.dart @@ -64,8 +64,8 @@ void main() { // Assert verify(mockRepo.fetchAllRoutinesSparseServer()).called(1); final state = container.read(routinesRiverpodProvider); - expect(state.routines.length, 1); - expect(state.routines.first.id, testRoutine.id); + expect(state.value!.routines.length, 1); + expect(state.value!.routines.first.id, testRoutine.id); }); test('addRoutine calls repository and prepends created routine to state', () async { @@ -85,8 +85,8 @@ void main() { verify(mockRepo.addRoutineServer(toAdd)).called(1); expect(result, created); final state = container.read(routinesRiverpodProvider); - expect(state.routines.isNotEmpty, true); - expect(state.routines.first, created); + expect(state.value!.routines.isNotEmpty, true); + expect(state.value!.routines.first, created); }); test('editRoutine calls repository and replaces routine in state', () async { @@ -97,7 +97,9 @@ void main() { final container = ProviderContainer.test( overrides: [routinesRepositoryProvider.overrideWithValue(mockRepo)], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState(routines: [routine]); + container.read(routinesRiverpodProvider.notifier).state = AsyncData( + RoutinesState(routines: [routine]), + ); // Act final notifier = container.read(routinesRiverpodProvider.notifier); @@ -105,8 +107,8 @@ void main() { verify(mockRepo.editRoutineServer(routine)).called(1); final state = container.read(routinesRiverpodProvider); - expect(state.routines.length, 1); - expect(state.routines.first, routine); + expect(state.value!.routines.length, 1); + expect(state.value!.routines.first, routine); }); test('deleteRoutine calls repository and removes routine from state', () async { @@ -117,8 +119,10 @@ void main() { final container = ProviderContainer.test( overrides: [routinesRepositoryProvider.overrideWithValue(mockRepo)], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [getTestRoutine()], + container.read(routinesRiverpodProvider.notifier).state = AsyncData( + RoutinesState( + routines: [getTestRoutine()], + ), ); // Act @@ -128,7 +132,7 @@ void main() { // Assert verify(mockRepo.deleteRoutineServer(routineId)).called(1); final state = container.read(routinesRiverpodProvider); - expect(state.routines.length, 0); + expect(state.value!.routines.length, 0); }); }); diff --git a/test/routine/routines_screen_test.dart b/test/routine/routines_screen_test.dart index ab58a992a..71887bc8b 100644 --- a/test/routine/routines_screen_test.dart +++ b/test/routine/routines_screen_test.dart @@ -67,8 +67,10 @@ void main() { routinesRepositoryProvider.overrideWithValue(mockRoutinesRepository), ], ); - container.read(routinesRiverpodProvider.notifier).state = RoutinesState( - routines: [routine1, routine2], + container.read(routinesRiverpodProvider.notifier).state = AsyncData( + RoutinesState( + routines: [routine1, routine2], + ), ); return UncontrolledProviderScope(