Some refactoring

This commit is contained in:
Roland Geider
2025-05-22 16:27:50 +02:00
parent 9934209b7c
commit ac13381bcf
13 changed files with 293 additions and 202 deletions

View File

@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
class PlateConfiguration extends ChangeNotifier {
//olympic standard weights
List<double> _plateWeights = [1.25, 2.5, 5, 10, 15, 20, 25];
List<double> _plateWeights = [1.25, 2.5, 5, 10, 15, 20, 25];
List<double> get plateWeights => _plateWeights;
@@ -10,4 +10,4 @@ class PlateConfiguration extends ChangeNotifier {
_plateWeights = weights;
notifyListeners();
}
}
}

View File

@@ -18,12 +18,17 @@
/// Calculates the number of plates needed to reach a specific weight
List<num> plateCalculator(num totalWeight, num barWeight, List<num> plates) {
final List<num> ans = [];
final List<num> result = [];
// Weight is less than the bar
if (totalWeight < barWeight) {
return [];
}
if (plates.isEmpty) {
return [];
}
// Remove the bar and divide by two to get weight on each side
totalWeight = (totalWeight - barWeight) / 2;
@@ -36,11 +41,11 @@ List<num> plateCalculator(num totalWeight, num barWeight, List<num> plates) {
for (final plate in plates.reversed) {
while (totalWeight >= plate) {
totalWeight -= plate;
ans.add(plate);
result.add(plate);
}
}
return ans;
return result;
}
/// Groups a list of plates as calculated by [plateCalculator]

View File

@@ -21,7 +21,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod;
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/core/locator.dart';
import 'package:wger/exceptions/http_exception.dart';
import 'package:wger/helpers/errors.dart';
@@ -34,8 +33,8 @@ import 'package:wger/providers/exercises.dart';
import 'package:wger/providers/gallery.dart';
import 'package:wger/providers/measurement.dart';
import 'package:wger/providers/nutrition.dart';
import 'package:wger/providers/routines.dart';
import 'package:wger/providers/plate_weights.dart';
import 'package:wger/providers/routines.dart';
import 'package:wger/providers/user.dart';
import 'package:wger/screens/add_exercise_screen.dart';
import 'package:wger/screens/auth_screen.dart';
@@ -103,7 +102,8 @@ void main() async {
return;
}
showGeneralErrorDialog(details.exception, stack);
// showGeneralErrorDialog(details.exception, stack);
throw details.exception;
};
// Catch errors that happen outside of the Flutter framework (e.g., in async operations)
@@ -115,7 +115,8 @@ void main() async {
if (error is WgerHttpException) {
showHttpExceptionErrorDialog(error);
} else {
showGeneralErrorDialog(error, stack);
// showGeneralErrorDialog(error, stack);
throw error;
}
// Return true to indicate that the error has been handled.
@@ -150,7 +151,7 @@ class MainApp extends StatelessWidget {
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context)=> PlateWeights()),
ChangeNotifierProvider(create: (context) => PlateWeights()),
ChangeNotifierProvider(create: (ctx) => AuthProvider()),
ChangeNotifierProxyProvider<AuthProvider, ExercisesProvider>(
create: (context) => ExercisesProvider(

View File

@@ -1,105 +1,147 @@
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/helpers/gym_mode.dart';
class PlateWeights extends ChangeNotifier{
const DEFAULT_KG_PLATES = [2.5, 5, 10, 15, 20, 25];
const PREFS_KEY_PLATES = 'selectedPlates';
class PlateWeights extends ChangeNotifier {
final plateColorMapKg = {
25: Colors.red,
20: Colors.blue,
15: Colors.yellow,
10: Colors.green,
5: Colors.white,
2.5: Colors.red,
2: Colors.blue,
1.25: Colors.yellow,
1: Colors.green,
0.5: Colors.white,
};
final plateColorMapLb = {
55: Colors.red,
45: Colors.blue,
35: Colors.yellow,
25: Colors.green,
10: Colors.white,
5: Colors.blue,
1.25: Colors.white,
};
bool isMetric = true;
bool plateChoiceExists = false;
bool loadedFromSharedPref = false;
num totalWeight = 0;
num barWeight = 20;
num convertTolbs = 2.205;
num convertToLbs = 2.205;
num totalWeightInKg = 0;
num barWeightInKg = 20;
List<num> selectedWeights = [];
List<num> kgWeights = [1.25, 2.5, 5, 10, 15, 20, 25];
List<num> selectedPlates = [...DEFAULT_KG_PLATES];
List<num> kgWeights = [0.5, 1, 1.25, 2, 2.5, 5, 10, 15, 20, 25];
List<num> lbsWeights = [2.5, 5, 10, 25, 35, 45];
List<num> customPlates = [];
late Map<num,int> grouped;
List<num> get data => selectedWeights;
set data(List<num> newData){
selectedWeights = newData;
//saving data to shared preference
List<num> get data => selectedPlates;
set data(List<num> newData) {
selectedPlates = newData;
saveIntoSharedPrefs();
notifyListeners();
}
Future<void> saveIntoSharedPrefs() async{
Color getColor(num plate) {
if (isMetric) {
return plateColorMapKg[plate] ?? Colors.white;
}
return plateColorMapLb[plate] ?? Colors.white;
}
Future<void> saveIntoSharedPrefs() async {
final pref = await SharedPreferences.getInstance();
//converting List Weights to String
final String selectedPlates = jsonEncode(selectedWeights);
pref.setString('selectedPlates', selectedPlates);
pref.setString(PREFS_KEY_PLATES, jsonEncode(selectedPlates));
notifyListeners();
}
void readPlates() async{
void readPlates() async {
final pref = await SharedPreferences.getInstance();
final platePrefData = pref.getString('selectedPlates');
if(platePrefData != null){
try{
final plateData = json.decode(platePrefData);
if(plateData is List){
selectedWeights = plateData.cast<num>();
}else{
throw const FormatException('Not a List');
}
}catch(e){
selectedWeights = [];
final platePrefData = pref.getString(PREFS_KEY_PLATES);
if (platePrefData != null) {
try {
final plateData = json.decode(platePrefData);
if (plateData is List) {
selectedPlates = plateData.cast<num>();
} else {
throw const FormatException('Not a List');
}
} catch (e) {
selectedPlates = [];
}
}
print('loaded');
notifyListeners();
}
Future<void> toggleSelection(num x) async{
if(selectedWeights.contains(x)) {
selectedWeights.remove(x);
}else {
selectedWeights.add(x);
Future<void> toggleSelection(num x) async {
if (selectedPlates.contains(x)) {
selectedPlates.remove(x);
} else {
selectedPlates.add(x);
}
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
await saveIntoSharedPrefs();
notifyListeners();
}
void unitChange() {
if(isMetric==false) {
if (isMetric == false) {
totalWeight = totalWeightInKg;
isMetric = true;
barWeight = barWeightInKg;
} else {
isMetric = false;
totalWeight = totalWeightInKg*2.205;
barWeight = barWeightInKg*2.205;
totalWeight = totalWeightInKg * 2.205;
barWeight = barWeightInKg * 2.205;
}
notifyListeners();
}
void clear() async{
selectedWeights.clear();
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
void clear() async {
selectedPlates.clear();
await saveIntoSharedPrefs();
notifyListeners();
}
void setWeight(num x) {
totalWeight = x;
totalWeightInKg=x;
totalWeightInKg = x;
notifyListeners();
}
void calculatePlates() {
selectedWeights.sort();
customPlates = plateCalculator(totalWeight,barWeight,selectedWeights);
grouped = groupPlates(customPlates);
notifyListeners();
List<num> get platesList {
return plateCalculator(totalWeight, barWeight, selectedPlates);
}
void resetPlates() async{
selectedWeights = [];
bool get hasPlates {
return platesList.isNotEmpty;
}
Map<num, int> get calculatePlates {
selectedPlates.sort();
return groupPlates(platesList);
}
void resetPlates() async {
selectedPlates = [...DEFAULT_KG_PLATES];
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
prefs.setString('selectedPlates', jsonEncode(selectedPlates));
notifyListeners();
}
}
void selectAllPlates() async {
selectedPlates = [...kgWeights];
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates', jsonEncode(selectedPlates));
notifyListeners();
}
}

View File

@@ -22,7 +22,6 @@ import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/shared_preferences.dart';
import 'package:path/path.dart';
import 'package:wger/models/user/profile.dart';
import 'package:wger/providers/base_provider.dart';
@@ -47,10 +46,10 @@ class UserProvider with ChangeNotifier {
}
// change the unit of plates
void unitChange(){
if(profile?.weightUnitStr == 'kg'){
void unitChange() {
if (profile?.weightUnitStr == 'kg') {
profile?.weightUnitStr = 'lb';
}else{
} else {
profile?.weightUnitStr = 'kg';
}
ChangeNotifier();

View File

@@ -1,6 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:provider/provider.dart';
import 'package:wger/providers/plate_weights.dart';
import 'package:wger/providers/user.dart';
@@ -12,23 +10,23 @@ class AddPlateWeights extends StatefulWidget {
State<AddPlateWeights> createState() => _AddPlateWeightsState();
}
class _AddPlateWeightsState extends State<AddPlateWeights> with SingleTickerProviderStateMixin{
late AnimationController _controller;
class _AddPlateWeightsState extends State<AddPlateWeights> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _animation;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
Provider.of<PlateWeights>(context,listen: false).readPlates();
WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<PlateWeights>(context, listen: false).readPlates();
});
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
duration: const Duration(seconds: 1),
);
_animation = Tween<Offset>(
begin: const Offset(-1.0, 0.0), // Start off-screen
end: const Offset(0.0, 0.0), // End at original position
end: Offset.zero, // End at original position
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
@@ -45,47 +43,45 @@ late AnimationController _controller;
@override
Widget build(BuildContext context) {
bool unit = true;
return Consumer2<PlateWeights,UserProvider> (
builder:(context,plateProvider,userProvider,child)=> Scaffold (
appBar: AppBar (
title: const Text('Select Available Plates'),
),
body: Column (
bool isMetric = true;
return Consumer2<PlateWeights, UserProvider>(
builder: (context, plateProvider, userProvider, child) => Scaffold(
appBar: AppBar(title: const Text('Select Available Plates')),
body: Column(
children: [
Row (
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Preferred Unit'),
DropdownButton (
onChanged: (newValue){
plateProvider.clear();
if(newValue=='kg') {
unit = true;
DropdownButton(
onChanged: (newValue) {
//plateProvider.clear();
if (newValue == 'kg') {
isMetric = true;
} else {
unit = false;
isMetric = false;
}
print(unit);
if(unit != userProvider.profile?.isMetric) {
if (isMetric != userProvider.profile?.isMetric) {
userProvider.unitChange();
//plateProvider.unitChange();
_controller.reset();
_controller.forward();
}
},
items: ['kg','lbs'].map((unit){
return DropdownMenuItem<String> (
}
},
items: ['kg', 'lbs'].map((unit) {
return DropdownMenuItem<String>(
value: unit,
child: Text(unit),
);
}).toList(),
),
],
],
),
SingleChildScrollView (
scrollDirection: Axis.horizontal,
child: Row (
children: (userProvider.profile?.weightUnitStr == 'kg')
Wrap(
alignment: WrapAlignment.center,
runAlignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: (userProvider.profile == null || userProvider.profile!.isMetric)
? plateProvider.kgWeights.map((number) {
return SlideTransition(
position: _animation,
@@ -93,19 +89,24 @@ late AnimationController _controller;
onTap: () => plateProvider.toggleSelection(number),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container (
child: Container(
height: 50,
width: 50,
alignment: Alignment.center,
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
decoration: BoxDecoration(
color: plateProvider.selectedPlates.contains(number)
? plateProvider.getColor(number)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 2),
),
child: Text (
'$number kg', // Add unit to text
child: Text(
number.toString(),
// '$number ${plateProvider.selectedPlates.contains(number) ? "\n✓" : ""}',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
@@ -124,13 +125,13 @@ late AnimationController _controller;
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
decoration: BoxDecoration(
color: plateProvider.selectedPlates.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
),
child: Text (
child: Text(
'$number lbs', // Add unit to text
style: const TextStyle(
color: Colors.white,
@@ -141,34 +142,35 @@ late AnimationController _controller;
),
),
);
}).toList(),
),
}).toList(),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: (){
onPressed: () {
plateProvider.saveIntoSharedPrefs();
if(plateProvider.selectedWeights.isNotEmpty){
plateProvider.plateChoiceExists=true;
plateProvider.calculatePlates();
}
Navigator.pop(context);
Navigator.pop(context);
},
child: const Text('Done'),
),
ElevatedButton(
onPressed: (){
onPressed: () {
plateProvider.selectAllPlates();
},
child: const Text('Select all'),
),
ElevatedButton(
onPressed: () {
plateProvider.resetPlates();
},
child: const Text('Reset',style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold))
},
child: const Text('Reset'),
),
],
),
]
],
),
),
);
}
}
}

View File

@@ -18,16 +18,18 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart' as provider;
import 'package:provider/provider.dart';
import 'package:wger/exceptions/http_exception.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/gym_mode.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/workouts/log.dart';
import 'package:wger/models/workouts/routine.dart';
import 'package:wger/models/workouts/set_config_data.dart';
import 'package:wger/models/workouts/slot_data.dart';
import 'package:wger/providers/plate_weights.dart';
import 'package:wger/providers/routines.dart';
import 'package:wger/screens/add_plate_weights.dart';
import 'package:wger/widgets/core/core.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
import 'package:wger/widgets/routines/forms/reps_unit.dart';
@@ -43,8 +45,7 @@ class LogPage extends StatefulWidget {
final Routine _workoutPlan;
final double _ratioCompleted;
final Map<Exercise, int> _exercisePages;
late Log _log;
final int _iteration;
final Log _log;
LogPage(
this._controller,
@@ -54,12 +55,10 @@ class LogPage extends StatefulWidget {
this._workoutPlan,
this._ratioCompleted,
this._exercisePages,
this._iteration,
) {
_log = Log.fromSetConfigData(_configData);
_log.routineId = _workoutPlan.id!;
_log.iteration = _iteration;
}
int? iteration,
) : _log = Log.fromSetConfigData(_configData)
..routineId = _workoutPlan.id!
..iteration = iteration;
@override
_LogPageState createState() => _LogPageState();
@@ -164,6 +163,9 @@ class _LogPageState extends State<LogPage> {
setState(() {
widget._log.weight = newValue;
_weightController.text = newValue.toString();
context.read<PlateWeights>().setWeight(
_weightController.text == '' ? 0 : double.parse(_weightController.text),
);
});
}
} on FormatException {}
@@ -182,6 +184,9 @@ class _LogPageState extends State<LogPage> {
num.parse(value);
setState(() {
widget._log.weight = num.parse(value);
context.read<PlateWeights>().setWeight(
_weightController.text == '' ? 0 : double.parse(_weightController.text),
);
});
} on FormatException {}
},
@@ -208,6 +213,9 @@ class _LogPageState extends State<LogPage> {
setState(() {
widget._log.weight = newValue;
_weightController.text = newValue.toString();
context.read<PlateWeights>().setWeight(
_weightController.text == '' ? 0 : double.parse(_weightController.text),
);
});
} on FormatException {}
},
@@ -366,64 +374,71 @@ class _LogPageState extends State<LogPage> {
}
Widget getPlates() {
final plates = plateCalculator(
double.parse(_weightController.text == '' ? '0' : _weightController.text),
BAR_WEIGHT,
AVAILABLE_PLATES,
);
final groupedPlates = groupPlates(plates);
return Column(
children: [
Text(
AppLocalizations.of(context).plateCalculator,
style: Theme.of(context).textTheme.titleLarge,
),
SizedBox(
height: 35,
child: plates.isNotEmpty
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...groupedPlates.keys.map(
(key) => Row(
children: [
Text(groupedPlates[key].toString()),
const Text('×'),
Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: SizedBox(
height: 35,
width: 35,
child: Align(
alignment: Alignment.center,
child: Text(
key.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold,
return Consumer<PlateWeights>(
builder: (context, plateProvider, child) => Column(
children: [
Text(
AppLocalizations.of(context).plateCalculator,
style: Theme.of(context).textTheme.titleLarge,
),
IconButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const AddPlateWeights()));
},
icon: const Icon(Icons.settings),
),
SizedBox(
height: 35,
child: plateProvider.hasPlates
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...plateProvider.calculatePlates.entries.map(
(entry) => Row(
children: [
Text(entry.value.toString()),
const Text('×'),
Container(
decoration: BoxDecoration(
color: plateProvider.getColor(entry.key),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 1),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: SizedBox(
height: 35,
width: 35,
child: Align(
alignment: Alignment.center,
child: Text(
entry.key.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
),
),
),
),
const SizedBox(width: 10),
],
const SizedBox(width: 10),
],
),
),
],
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: MutedText(
AppLocalizations.of(context).plateCalculatorNotDivisible,
textAlign: TextAlign.center,
),
],
)
: MutedText(
AppLocalizations.of(context).plateCalculatorNotDivisible,
),
),
const SizedBox(height: 3),
],
),
),
const SizedBox(height: 3),
],
),
);
}