From 99078df6e6810b7feafe2003bc0c41356c7c0aaf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 15 Nov 2020 21:19:52 +0100 Subject: [PATCH] Save exercises to cache --- lib/providers/exercises.dart | 50 +++++++++---- lib/screens/dashboard.dart | 136 +++++++++++++++++++++++++++++++---- 2 files changed, 159 insertions(+), 27 deletions(-) diff --git a/lib/providers/exercises.dart b/lib/providers/exercises.dart index c5819ade4..a7ca456c5 100644 --- a/lib/providers/exercises.dart +++ b/lib/providers/exercises.dart @@ -1,9 +1,11 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/models/exercises/category.dart'; +import 'package:wger/models/exercises/comment.dart'; import 'package:wger/models/exercises/equipment.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/exercises/muscle.dart'; @@ -25,6 +27,7 @@ class Exercises with ChangeNotifier { List _categories = []; List _muscles = []; List _equipment = []; + Auth _auth; Exercises(Auth auth, List entries) { @@ -45,6 +48,22 @@ class Exercises with ChangeNotifier { return _entries.firstWhere((exercise) => exercise.id == id); } + Future> fetchAndSetComments(int exerciseId) async { + List _comments = []; + + final response = await http.get(_urlExercisesComment + '?exercise=$exerciseId'); + final comments = json.decode(response.body) as Map; + try { + for (final comment in comments['results']) { + _comments.add(Comment.fromJson(comment)); + } + } catch (error) { + throw (error); + } + + return _comments; + } + Future fetchAndSetCategories() async { final response = await http.get(_urlCategories); final categories = json.decode(response.body) as Map; @@ -82,29 +101,36 @@ class Exercises with ChangeNotifier { } Future fetchAndSetExercises() async { - // TODO: Load exercises from cache + final List loadedExercises = []; + + // Load exercises from cache, if available final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('exerciseData')) { + //if (false) { final exerciseData = json.decode(prefs.getString('exerciseData')); + if (DateTime.parse(exerciseData['expiresIn']).isAfter(DateTime.now())) { + for (final exercise in exerciseData['exercises']) { + loadedExercises.add(Exercise.fromJson(exercise)); + } + _entries = loadedExercises; + print('Read from cache!'); + return; + } } + // Load categories, muscles and equipments... await fetchAndSetCategories(); await fetchAndSetMuscles(); await fetchAndSetEquipment(); - final response = await http.get( - _urlExercises, - headers: {'Authorization': 'Token ${_auth.token}'}, - ); + final response = await http.get(_urlExercises); final extractedData = json.decode(response.body) as Map; - final List loadedExercises = []; - if (loadedExercises == null) { - return; - } - + // ... and now put all together try { for (final entry in extractedData['results']) { + final List comments = await fetchAndSetComments(entry['id']); + entry['category'] = _categories.firstWhere((cat) => cat.id == entry['category']).toJson(); entry['muscles'] = entry['muscles'] .map((e) => _muscles.firstWhere((muscle) => muscle.id == e).toJson()) @@ -115,18 +141,18 @@ class Exercises with ChangeNotifier { entry['equipment'] = entry['equipment'] .map((e) => _equipment.firstWhere((equipment) => equipment.id == e).toJson()) .toList(); + entry['comments'] = comments.map((comment) => comment.toJson()).toList(); loadedExercises.add(Exercise.fromJson(entry)); } + // Save the result to the cache _entries = loadedExercises; - final exerciseData = { 'date': DateTime.now().toIso8601String(), 'expiresIn': DateTime.now().add(Duration(days: 7)).toIso8601String(), 'exercises': _entries.map((e) => e.toJson()).toList() }; prefs.setString('exerciseData', json.encode(exerciseData)); - notifyListeners(); } catch (error) { throw (error); diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 49fa96a24..44cbcf288 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -24,6 +24,107 @@ class _DashboardScreenState extends State { ); } + Widget getWorkoutCard() { + return Card( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: Icon(Icons.fitness_center), + title: Text('Something to do with workouts'), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Monday'), + Text('Tuesday'), + Text('Wednesday'), + Text('Thursday'), + Text('Friday'), + Text('Saturday'), + Text('Sunday'), + ], + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + child: const Text('Action one'), + onPressed: () {}, + ), + const SizedBox(width: 8), + TextButton( + child: const Text('Action two'), + onPressed: () {}, + ), + const SizedBox(width: 8), + ], + ), + ], + ), + ); + } + + Widget getNutritionCard() { + return Card( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: Icon(Icons.fitness_center), + title: Text('Nutrition'), + subtitle: Text('Nutrition overview, graphs, etc'), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + child: const Text('Action one'), + onPressed: () {}, + ), + const SizedBox(width: 8), + TextButton( + child: const Text('Action two'), + onPressed: () {}, + ), + const SizedBox(width: 8), + ], + ), + ], + ), + ); + } + + Widget getWeightCard() { + return Card( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: Icon(Icons.restaurant), + title: Text('Weight'), + subtitle: Text('Weight overview, graphs, etc'), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + child: const Text('Action one'), + onPressed: () {}, + ), + const SizedBox(width: 8), + TextButton( + child: const Text('Action two'), + onPressed: () {}, + ), + const SizedBox(width: 8), + ], + ), + ], + ), + ); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -31,21 +132,26 @@ class _DashboardScreenState extends State { drawer: AppDrawer(), body: Column( children: [ - Center( - child: Text("dashboard content here"), - ), - FlatButton( - child: Text('reload'), - onPressed: () { - Provider.of(context, listen: false).fetchAndSetExercises(); - }, - ), - FutureBuilder( - future: Provider.of(context, listen: false).fetchAndSetExercises(), - builder: (ctx, authResultSnapshot) => - authResultSnapshot.connectionState == ConnectionState.waiting - ? Center(child: CircularProgressIndicator()) - : Text("all exercises loaded"), + getWorkoutCard(), + getNutritionCard(), + getWeightCard(), + Expanded( + child: Align( + alignment: Alignment.bottomCenter, + child: FutureBuilder( + future: Provider.of(context, listen: false).fetchAndSetExercises(), + builder: (ctx, authResultSnapshot) => + authResultSnapshot.connectionState == ConnectionState.waiting + ? Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text('Initialising exercise database...'), + LinearProgressIndicator(), + ], + ) + : Text("all exercises loaded"), + ), + ), ), ], ),