Fetch plan details when visiting the detail page

See #14
This commit is contained in:
Roland Geider
2021-05-13 13:19:07 +02:00
parent b8e0136540
commit b90d0a0008
6 changed files with 188 additions and 108 deletions

View File

@@ -61,6 +61,7 @@ class WorkoutPlan {
WorkoutPlan.empty() {
creationDate = DateTime.now();
name = '';
description = '';
}
// Boilerplate

View File

@@ -124,28 +124,62 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier {
* Workouts
*/
Future<void> fetchAndSetAllPlans() async {
/// Fetches and sets all workout plans fully, i.e. with all corresponding child
/// attributes
Future<void> fetchAndSetAllPlansFull() async {
final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'}));
for (final entry in data['results']) {
await fetchAndSetWorkoutPlan(entry['id']);
await fetchAndSetWorkoutPlanFull(entry['id']);
}
notifyListeners();
}
Future<void> fetchAndSetWorkoutPlan(int workoutId) async {
/// Fetches all workout plan sparsely, i.e. only with the data on the plan
/// object itself and no child attributes
Future<void> fetchAndSetAllPlansSparse() async {
final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'}));
for (final entry in data['results']) {
await fetchAndSetPlanSparse(entry['id']);
}
notifyListeners();
}
/// Fetches a workout plan sparsely, i.e. only with the data on the plan
/// object itself and no child attributes
Future<WorkoutPlan> fetchAndSetPlanSparse(int planId) async {
final fullPlanData = await fetch(
makeUrl(_workoutPlansUrlPath, id: planId),
);
final plan = WorkoutPlan.fromJson(fullPlanData);
_workoutPlans.add(plan);
_workoutPlans.sort((a, b) => b.creationDate.compareTo(a.creationDate));
notifyListeners();
return plan;
}
/// Fetches a workout plan fully, i.e. with all corresponding child attributes
Future<WorkoutPlan> fetchAndSetWorkoutPlanFull(int workoutId) async {
// Load a list of all settings so that we can search through it late
//
// This is a bit ugly, but makes saves sending lots of requests later on
final allSsettingsData = await fetch(
final allSettingsData = await fetch(
makeUrl(_settingsUrlPath, query: {'limit': '1000'}),
);
WorkoutPlan plan;
try {
plan = findById(workoutId);
} on StateError catch (e) {
plan = await fetchAndSetPlanSparse(workoutId);
}
// Plan
final fullPlanData = await fetch(
makeUrl(_workoutPlansUrlPath, id: workoutId, objectMethod: 'canonical_representation'),
);
final plan = WorkoutPlan.fromJson(fullPlanData['obj']);
// Days
List<Day> days = [];
@@ -161,7 +195,7 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier {
// Settings
List<Setting> settings = [];
final settingData = allSsettingsData['results'].where((s) => s['set'] == workoutSet.id);
final settingData = allSettingsData['results'].where((s) => s['set'] == workoutSet.id);
for (final settingEntry in settingData) {
final workoutSetting = Setting.fromJson(settingEntry);
@@ -202,9 +236,8 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier {
}
// ... and done
_workoutPlans.add(plan);
_workoutPlans.sort((a, b) => b.creationDate.compareTo(a.creationDate));
notifyListeners();
return plan;
}
Future<WorkoutPlan> addWorkout(WorkoutPlan workout) async {

View File

@@ -60,29 +60,36 @@ class _DashboardScreenState extends State<DashboardScreen> {
if (!Provider.of<AuthProvider>(context, listen: false).dataInit) {
Provider.of<AuthProvider>(context, listen: false).setServerVersion();
final workoutPlansProvider = Provider.of<WorkoutPlansProvider>(context, listen: false);
final nutritionPlansProvider = Provider.of<NutritionPlansProvider>(context, listen: false);
final exercisesProvider = Provider.of<ExercisesProvider>(context, listen: false);
final galleryProvider = Provider.of<GalleryProvider>(context, listen: false);
final weightProvider = Provider.of<BodyWeightProvider>(context, listen: false);
// Base data
await Future.wait([
Provider.of<WorkoutPlansProvider>(context, listen: false).fetchAndSetUnits(),
Provider.of<NutritionPlansProvider>(context, listen: false).fetchIngredientsFromCache(),
Provider.of<ExercisesProvider>(context, listen: false).fetchAndSetExercises(),
workoutPlansProvider.fetchAndSetUnits(),
nutritionPlansProvider.fetchIngredientsFromCache(),
exercisesProvider.fetchAndSetExercises(),
]);
// Plans, weight and gallery
await Future.wait([
Provider.of<GalleryProvider>(context, listen: false).fetchAndSetGallery(),
Provider.of<NutritionPlansProvider>(context, listen: false).fetchAndSetAllPlans(),
Provider.of<WorkoutPlansProvider>(context, listen: false).fetchAndSetAllPlans(),
Provider.of<BodyWeightProvider>(context, listen: false).fetchAndSetEntries(),
galleryProvider.fetchAndSetGallery(),
nutritionPlansProvider.fetchAndSetAllPlans(),
workoutPlansProvider.fetchAndSetAllPlansSparse(),
weightProvider.fetchAndSetEntries(),
]);
// Nutrition logs
await Provider.of<NutritionPlansProvider>(context, listen: false).fetchAndSetAllLogs();
await nutritionPlansProvider.fetchAndSetAllLogs();
// Current workout plan
if (Provider.of<WorkoutPlansProvider>(context, listen: false).activePlan != null) {
Provider.of<WorkoutPlansProvider>(context, listen: false).setCurrentPlan(
Provider.of<WorkoutPlansProvider>(context, listen: false).activePlan!.id!,
);
if (workoutPlansProvider.activePlan != null) {
final planId = workoutPlansProvider.activePlan!.id!;
await workoutPlansProvider.fetchAndSetWorkoutPlanFull(planId);
workoutPlansProvider.setCurrentPlan(planId);
}
}

View File

@@ -53,6 +53,11 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
});
}
Future<WorkoutPlan> _loadFullWorkout(BuildContext context, int planId) async {
return await Provider.of<WorkoutPlansProvider>(context, listen: false)
.fetchAndSetWorkoutPlanFull(planId);
}
Widget getBody(WorkoutPlan plan) {
switch (_mode) {
case WorkoutScreenMode.workout:
@@ -69,75 +74,91 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
final workoutPlan = ModalRoute.of(context)!.settings.arguments as WorkoutPlan;
return Scaffold(
//appBar: getAppBar(workoutPlan),
body: Consumer<WorkoutPlansProvider>(
builder: (context, value, child) => CustomScrollView(
slivers: <Widget>[
SliverAppBar(
expandedHeight: 250,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(workoutPlan.name),
background: Image(
image: AssetImage('assets/images/backgrounds/workout_plans.jpg'),
fit: BoxFit.cover,
),
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
expandedHeight: 250,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(workoutPlan.name),
background: Image(
image: AssetImage('assets/images/backgrounds/workout_plans.jpg'),
fit: BoxFit.cover,
),
actions: [
PopupMenuButton<WorkoutOptions>(
icon: Icon(Icons.more_vert),
onSelected: (value) {
// Edit
if (value == WorkoutOptions.edit) {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.edit,
WorkoutForm(workoutPlan),
),
);
// Delete
} else if (value == WorkoutOptions.delete) {
Provider.of<WorkoutPlansProvider>(context, listen: false)
.deleteWorkout(workoutPlan.id!);
Navigator.of(context).pop();
// Toggle Mode
} else if (value == WorkoutOptions.toggleMode) {
if (_mode == WorkoutScreenMode.workout) {
_changeMode(WorkoutScreenMode.log);
} else {
_changeMode(WorkoutScreenMode.workout);
}
}
},
itemBuilder: (BuildContext context) {
return [
PopupMenuItem<WorkoutOptions>(
child: _mode == WorkoutScreenMode.log
? Text(AppLocalizations.of(context)!.labelWorkoutPlan)
: Text(AppLocalizations.of(context)!.labelWorkoutLogs),
value: WorkoutOptions.toggleMode,
),
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.edit,
child: Text(AppLocalizations.of(context)!.edit),
),
const PopupMenuDivider(),
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.delete,
child: Text(AppLocalizations.of(context)!.delete),
),
];
},
),
],
),
getBody(workoutPlan),
],
),
actions: [
PopupMenuButton<WorkoutOptions>(
icon: Icon(Icons.more_vert),
onSelected: (value) {
// Edit
if (value == WorkoutOptions.edit) {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.edit,
WorkoutForm(workoutPlan),
),
);
// Delete
} else if (value == WorkoutOptions.delete) {
Provider.of<WorkoutPlansProvider>(context, listen: false)
.deleteWorkout(workoutPlan.id!);
Navigator.of(context).pop();
// Toggle Mode
} else if (value == WorkoutOptions.toggleMode) {
if (_mode == WorkoutScreenMode.workout) {
_changeMode(WorkoutScreenMode.log);
} else {
_changeMode(WorkoutScreenMode.workout);
}
}
},
itemBuilder: (BuildContext context) {
return [
PopupMenuItem<WorkoutOptions>(
child: _mode == WorkoutScreenMode.log
? Text(AppLocalizations.of(context)!.labelWorkoutPlan)
: Text(AppLocalizations.of(context)!.labelWorkoutLogs),
value: WorkoutOptions.toggleMode,
),
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.edit,
child: Text(AppLocalizations.of(context)!.edit),
),
const PopupMenuDivider(),
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.delete,
child: Text(AppLocalizations.of(context)!.delete),
),
];
},
),
],
),
FutureBuilder(
future: _loadFullWorkout(context, workoutPlan.id!),
builder: (context, AsyncSnapshot<WorkoutPlan> snapshot) =>
snapshot.connectionState == ConnectionState.waiting
? SliverList(
delegate: SliverChildListDelegate(
[
Container(
height: 200,
child: Center(
child: CircularProgressIndicator(),
),
)
],
),
)
: Consumer<WorkoutPlansProvider>(
builder: (context, value, child) => getBody(workoutPlan),
),
)
],
),
);
}

View File

@@ -33,16 +33,20 @@ import 'workout_form_test.mocks.dart';
@GenerateMocks([WorkoutPlansProvider])
void main() {
var mockWorkoutPlans = MockWorkoutPlansProvider();
final plan1 = WorkoutPlan(
final existingPlan = WorkoutPlan(
id: 1,
creationDate: DateTime(2021, 1, 1),
name: 'test 1',
description: 'description 1',
);
final plan2 = WorkoutPlan(creationDate: DateTime(2021, 1, 2), name: '');
final newPlan = WorkoutPlan.empty();
setUp(() {
mockWorkoutPlans = MockWorkoutPlansProvider();
when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(existingPlan));
when(mockWorkoutPlans.fetchAndSetWorkoutPlanFull(any))
.thenAnswer((_) => Future.value(existingPlan));
});
Widget createHomeScreen(WorkoutPlan workoutPlan, {locale = 'en'}) {
@@ -66,7 +70,7 @@ void main() {
}
testWidgets('Test the widgets on the workout form', (WidgetTester tester) async {
await tester.pumpWidget(createHomeScreen(plan1));
await tester.pumpWidget(createHomeScreen(existingPlan));
await tester.pumpAndSettle();
expect(find.byType(TextFormField), findsNWidgets(2));
@@ -74,10 +78,7 @@ void main() {
});
testWidgets('Test editing an existing workout', (WidgetTester tester) async {
when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1));
when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2));
await tester.pumpWidget(createHomeScreen(plan1));
await tester.pumpWidget(createHomeScreen(existingPlan));
await tester.pumpAndSettle();
expect(
@@ -107,14 +108,19 @@ void main() {
});
testWidgets('Test creating a new workout - only name', (WidgetTester tester) async {
when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1));
when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2));
final editWorkout = WorkoutPlan(
id: 2,
creationDate: newPlan.creationDate,
name: 'New cool workout',
);
await tester.pumpWidget(createHomeScreen(plan2));
when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout));
await tester.pumpWidget(createHomeScreen(newPlan));
await tester.pumpAndSettle();
expect(find.text(('')), findsNWidgets(2), reason: 'New workout has no name or description');
await tester.enterText(find.byKey(Key('field-name')), 'New cool workout');
await tester.enterText(find.byKey(Key('field-name')), editWorkout.name);
await tester.tap(find.byKey(Key(SUBMIT_BUTTON_KEY_NAME)));
verifyNever(mockWorkoutPlans.editWorkout(any));
@@ -125,16 +131,17 @@ void main() {
expect(find.text(('New cool workout')), findsOneWidget, reason: 'Workout plan detail page');
});
testWidgets('Test creating a new workout - description', (WidgetTester tester) async {
when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1));
when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2));
testWidgets('Test creating a new workout - name and description', (WidgetTester tester) async {
final editWorkout = WorkoutPlan(
id: 2, creationDate: newPlan.creationDate, name: 'My workout', description: 'Get yuuuge');
when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout));
await tester.pumpWidget(createHomeScreen(plan2));
await tester.pumpWidget(createHomeScreen(newPlan));
await tester.pumpAndSettle();
expect(find.text(('')), findsNWidgets(2), reason: 'New workout has no name or description');
await tester.enterText(find.byKey(Key('field-name')), 'My workout');
await tester.enterText(find.byKey(Key('field-description')), 'Get yuuuge');
await tester.enterText(find.byKey(Key('field-name')), editWorkout.name);
await tester.enterText(find.byKey(Key('field-description')), editWorkout.description);
await tester.tap(find.byKey(Key(SUBMIT_BUTTON_KEY_NAME)));
verifyNever(mockWorkoutPlans.editWorkout(any));

View File

@@ -113,16 +113,27 @@ class MockWorkoutPlansProvider extends _i1.Mock
super.noSuchMethod(Invocation.method(#resetCurrentPlan, []),
returnValueForMissingStub: null);
@override
_i14.Future<void> fetchAndSetAllPlans() =>
(super.noSuchMethod(Invocation.method(#fetchAndSetAllPlans, []),
_i14.Future<void> fetchAndSetAllPlansFull() =>
(super.noSuchMethod(Invocation.method(#fetchAndSetAllPlansFull, []),
returnValue: Future<void>.value(null),
returnValueForMissingStub: Future.value()) as _i14.Future<void>);
@override
_i14.Future<void> fetchAndSetWorkoutPlan(int? workoutId) => (super
.noSuchMethod(Invocation.method(#fetchAndSetWorkoutPlan, [workoutId]),
_i14.Future<void> fetchAndSetAllPlansSparse() =>
(super.noSuchMethod(Invocation.method(#fetchAndSetAllPlansSparse, []),
returnValue: Future<void>.value(null),
returnValueForMissingStub: Future.value()) as _i14.Future<void>);
@override
_i14.Future<_i6.WorkoutPlan> fetchAndSetPlanSparse(int? planId) =>
(super.noSuchMethod(Invocation.method(#fetchAndSetPlanSparse, [planId]),
returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan()))
as _i14.Future<_i6.WorkoutPlan>);
@override
_i14.Future<_i6.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) =>
(super.noSuchMethod(
Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]),
returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan()))
as _i14.Future<_i6.WorkoutPlan>);
@override
_i14.Future<_i6.WorkoutPlan> addWorkout(_i6.WorkoutPlan? workout) =>
(super.noSuchMethod(Invocation.method(#addWorkout, [workout]),
returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan()))