having issue in shared Preferences

This commit is contained in:
Ayush Sourav Jagaty
2025-01-05 12:20:05 +05:30
parent 3c3d245958
commit 78eb620f6c
8 changed files with 229 additions and 129 deletions

View File

@@ -1,4 +1,5 @@
{
"dart.lineLength": 100,
"diffEditor.ignoreTrimWhitespace": true,
"cmake.sourceDirectory": "/Users/ayush/flutter/linux",
}

View File

@@ -19,7 +19,6 @@
/// 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 = [];
print("total weight is $totalWeight");
// Weight is less than the bar
if (totalWeight < barWeight) {
return [];

View File

@@ -37,6 +37,7 @@
"@passwordTooShort": {
"description": "Error message when the user a password that is too short"
},
"selectAvailablePlates": "Select Available Plates",
"password": "Password",
"@password": {},
"confirmPassword": "Confirm password",

View File

@@ -18,6 +18,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/core/locator.dart';
import 'package:wger/providers/add_exercise.dart';
import 'package:wger/providers/base_provider.dart';
@@ -57,10 +58,8 @@ import 'providers/auth.dart';
void main() async {
//zx.setLogEnabled(kDebugMode);
// Needs to be called before runApp
WidgetsFlutterBinding.ensureInitialized();
// Locator to initialize exerciseDB
await ServiceLocator().configure();
// Application

View File

@@ -1,9 +1,12 @@
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/helpers/gym_mode.dart';
class PlateWeights extends ChangeNotifier{
String unitOfPlate = 'kg';
bool flag = false;
bool isMetric = true;
bool plateChoiceExists = false;
bool loadedFromSharedPref = false;
num totalWeight = 0;
num barWeight = 20;
num convertTolbs = 2.205;
@@ -14,39 +17,68 @@ class PlateWeights extends ChangeNotifier{
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
saveIntoSharedPrefs();
notifyListeners();
}
Future<void> saveIntoSharedPrefs() async{
final pref = await SharedPreferences.getInstance();
//converting List Weights to String
final String selectedPlates = jsonEncode(selectedWeights);
pref.setString('selectedPlates', selectedPlates);
notifyListeners();
}
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 = [];
}
}
print('loaded');
notifyListeners();
}
Future<void> toggleSelection(num x) async{
if(selectedWeights.contains(x)) {
selectedWeights.remove(x);
}else {
selectedWeights.add(x);
}
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
notifyListeners();
}
void unitChange() {
if(unitOfPlate=='lbs') {
if(isMetric==false) {
totalWeight = totalWeightInKg;
unitOfPlate = 'kg';
isMetric = true;
barWeight = barWeightInKg;
} else {
unitOfPlate = 'lbs';
isMetric = false;
totalWeight = totalWeightInKg*2.205;
barWeight = barWeightInKg*2.205;
}
notifyListeners();
}
void toggleSelection(num x) {
if(unitOfPlate == 'kg') {
if(selectedWeights.contains(x)) {
selectedWeights.remove(x);
} else {
selectedWeights.add(x);
}
} else {
if(selectedWeights.contains(x)) {
selectedWeights.remove(x);
} else {
selectedWeights.add(x);
}
}
notifyListeners();
}
void clear() {
void clear() async{
selectedWeights.clear();
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
notifyListeners();
}
@@ -63,8 +95,11 @@ class PlateWeights extends ChangeNotifier{
notifyListeners();
}
void resetPlates() {
void resetPlates() async{
selectedWeights = [];
final prefs = await SharedPreferences.getInstance();
prefs.setString('selectedPlates',jsonEncode(selectedWeights));
notifyListeners();
}
}
}

View File

@@ -19,6 +19,8 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:path/path.dart';
import 'package:wger/models/user/profile.dart';
import 'package:wger/providers/base_provider.dart';
@@ -35,7 +37,15 @@ class UserProvider with ChangeNotifier {
void clear() {
profile = null;
}
// change the unit of plates
void unitChange(){
if(profile?.weightUnitStr == 'kg'){
profile?.weightUnitStr = 'lb';
}else{
profile?.weightUnitStr = 'kg';
}
ChangeNotifier();
}
/// Fetch the current user's profile
Future<void> fetchAndSetProfile() async {
final userData = await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL));

View File

@@ -1,6 +1,9 @@
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';
class AddPlateWeights extends StatefulWidget {
const AddPlateWeights({super.key});
@@ -9,26 +12,65 @@ class AddPlateWeights extends StatefulWidget {
State<AddPlateWeights> createState() => _AddPlateWeightsState();
}
class _AddPlateWeightsState extends State<AddPlateWeights> {
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();
});
_controller = AnimationController(
vsync: this,
duration: 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
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
));
_controller.forward(); // Start the animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Consumer<PlateWeights> (
builder:(context,plateProvider,child)=> Scaffold (
bool unit = true;
return Consumer2<PlateWeights,UserProvider> (
builder:(context,plateProvider,userProvider,child)=> Scaffold (
appBar: AppBar (
title: const Text('Enter Custom Plate Weights'),
title: const Text('Select Available Plates'),
),
body: Column (
children: [
Row (
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Kg or lbs'),
const Text('Preferred Unit'),
DropdownButton (
onChanged: (newValue){
plateProvider.clear();
if((newValue!) != plateProvider.unitOfPlate) {
plateProvider.unitChange();
if(newValue=='kg') {
unit = true;
} else {
unit = false;
}
print(unit);
if(unit != userProvider.profile?.isMetric) {
userProvider.unitChange();
//plateProvider.unitChange();
_controller.reset();
_controller.forward();
}
},
items: ['kg','lbs'].map((unit){
@@ -43,46 +85,58 @@ class _AddPlateWeightsState extends State<AddPlateWeights> {
SingleChildScrollView (
scrollDirection: Axis.horizontal,
child: Row (
children: plateProvider.unitOfPlate == 'kg'
children: (userProvider.profile?.weightUnitStr == 'kg')
? plateProvider.kgWeights.map((number) {
return GestureDetector(
onTap: () => plateProvider.toggleSelection(number),
child: Container (
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
),
child: Text (
'$number kg', // Add unit to text
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
return SlideTransition(
position: _animation,
child: GestureDetector(
onTap: () => plateProvider.toggleSelection(number),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container (
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
),
child: Text (
'$number kg', // Add unit to text
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
);
}).toList()
: plateProvider.lbsWeights.map((number) {
return GestureDetector(
onTap: () => plateProvider.toggleSelection(number),
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
),
child: Text (
'$number lbs', // Add unit to text
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
return SlideTransition(
position: _animation,
child: GestureDetector(
onTap: () => plateProvider.toggleSelection(number),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration (
color: plateProvider.selectedWeights.contains(number)
? const Color.fromARGB(255, 82, 226, 236)
: const Color.fromARGB(255, 97, 105, 101),
borderRadius: BorderRadius.circular(10),
),
child: Text (
'$number lbs', // Add unit to text
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
@@ -95,9 +149,11 @@ class _AddPlateWeightsState extends State<AddPlateWeights> {
children: [
TextButton(
onPressed: (){
plateProvider.saveIntoSharedPrefs();
if(plateProvider.selectedWeights.isNotEmpty){
plateProvider.flag=true;
plateProvider.calculatePlates();}
plateProvider.plateChoiceExists=true;
plateProvider.calculatePlates();
}
Navigator.pop(context);
},
child: const Text('Done'),

View File

@@ -16,12 +16,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/exceptions/http_exception.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/gym_mode.dart';
@@ -262,15 +264,15 @@ class _LogPageState extends State<LogPage> {
late FocusNode focusNode;
@override
void initState() {
void initState(){
super.initState();
// WidgetsBinding.instance.addPostFrameCallback((_){
// Provider.of<PlateWeights>(context,listen: false).readPlates();
// });
focusNode = FocusNode();
if (widget._setting.reps != null) {
_repsController.text = widget._setting.reps.toString();
}
if (widget._setting.weight != null) {
_weightController.text = widget._setting.weight.toString();
}
@@ -555,71 +557,68 @@ class _LogPageState extends State<LogPage> {
}
Widget getPlates() {
print('get plates');
final plates = plateCalculator(num.parse(_weightController.text),BAR_WEIGHT,AVAILABLE_PLATES);
Map<num,int> groupedPlates;
groupedPlates = groupPlates(plates);
return Consumer<PlateWeights>(builder: (context,plateProvider, child) =>
SingleChildScrollView(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(onPressed: () {
plateProvider.flag=false;
plateProvider.setWeight(num.parse(_weightController.text));
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>const AddPlateWeights()));
},
child: const Text("Enter custom Denomination's")
),
const Padding(padding: EdgeInsets.all(10)),
],
),
SizedBox (
height: 35,
child: (plateProvider.flag?plateProvider.selectedWeights.isNotEmpty:plates.isNotEmpty)
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text ('Plates:-',style: TextStyle(),),
...(plateProvider.flag?plateProvider.grouped:groupedPlates).keys.map(
(key) => Row (
children: [
Text(plateProvider.flag?(plateProvider.grouped[key].toString()):(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)=>
SingleChildScrollView(
child: Column(
children: [
SizedBox (
height: 35,
child: (plateProvider.plateChoiceExists?plateProvider.selectedWeights.isNotEmpty:plates.isNotEmpty)
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: (){
plateProvider.plateChoiceExists=false;
plateProvider.setWeight(num.parse(_weightController.text));
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>const AddPlateWeights()));
},
icon: const Icon(Icons.settings),
),
const Text ('Plates:-',style: TextStyle(),),
...(plateProvider.plateChoiceExists?plateProvider.grouped:groupedPlates).keys.map(
(key) => Row (
children: [
Text(plateProvider.plateChoiceExists?(plateProvider.grouped[key].toString()):(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,),
),
),
),
),
),
const SizedBox(width: 10),
],
),
const SizedBox(width: 10),
],
),
],
)
: MutedText (
AppLocalizations.of(context).plateCalculatorNotDivisible,
),
],
)
: MutedText (
AppLocalizations.of(context).plateCalculatorNotDivisible,
),
),
],
),
],
),
),
),
);
}