Compare commits

..
31 Commits
Author SHA1 Message Date
brandon.presley 3983366408 Merge branch 'master' of gitea.presley.nz:brandon.presley/fmassive 2023-12-01 23:37:05 +13:00
brandon.presley 3ba7458056 Add timer to start_plan 2023-12-02 12:36:26 +13:00
brandon.presley a3d7e651f4 Add generated code 2023-12-01 17:50:32 +13:00
brandon.presley 8678e935df Ensure days + exercises are selected for new plan 2023-11-30 13:10:28 +13:00
brandon.presley 9aed2b3ac1 Add edit button to plan_tile 2023-11-30 13:07:14 +13:00
brandon.presley 6908623ba2 Remove edit button from start_plan
This just messes up our navigation stack too much
and makes it confusing when you go backwards.
2023-11-30 13:07:06 +13:00
brandon.presley a9486727b2 Ran dart fix --apply 2023-11-30 13:02:50 +13:00
brandon.presley e4ba71ad4b Require trailing commas and auto-fix 2023-11-30 13:02:29 +13:00
brandon.presley 202ec599d6 Factor out plan_tile 2023-11-30 13:02:20 +13:00
brandon.presley fbffc0cf4a Refactor slightly edit_plan 2023-11-30 13:01:42 +13:00
brandon.presley 19f9dd9b3b Remove circular progress indicators
Our app is so fast these will look like bugs to flicker
in front of the user.
2023-11-30 10:37:50 +13:00
brandon.presley b6a73c398e Add start plan page 2023-11-30 10:28:40 +13:00
brandon.presley c5a209d41e Change settings button name from Import to Import sets 2023-11-30 10:27:23 +13:00
brandon.presley 852d28afcf Include time in set_tile 2023-11-30 10:27:01 +13:00
brandon.presley dac65c8390 Fix editing plan 2023-11-29 16:58:40 +13:00
brandon.presley 98991a3d02 Replace database import with CSV import 2023-11-29 16:57:19 +13:00
brandon.presley 36b8ce37ad Set created date at last possible moment 2023-11-29 16:33:01 +13:00
brandon.presley 7642c6faf2 Ran dart fix 2023-11-29 13:01:11 +13:00
brandon.presley b617724f0a Simplify main.dart 2023-11-28 20:08:29 +13:00
brandon.presley 4a83465d82 Make whole plan edit scrollable 2023-11-28 20:04:20 +13:00
brandon.presley a383ebfe34 Clear sound value when importing database
The file will no longer exist.
2023-11-28 14:54:36 +13:00
brandon.presley e0302e63e2 Re organize set tiles 2023-11-28 14:54:18 +13:00
brandon.presley af3fd69688 Convert noSound -> no_sound 2023-11-28 14:54:02 +13:00
brandon.presley 738a48438e Add constants.dart 2023-11-28 14:53:49 +13:00
brandon.presley 2849cec682 Add launch.json 2023-11-28 14:53:43 +13:00
brandon.presley 2544a3de9f Highlight current plan 2023-11-28 14:53:37 +13:00
brandon.presley 4aa6926f5c Long press on plan list to delete a plan 2023-11-11 15:24:57 +13:00
brandon.presley cbb2e2c4b0 Add confirmation dialog to deleting a plan 2023-11-11 15:18:23 +13:00
brandon.presley 4097a79205 Move migration logic in settings_page into databasse 2023-11-11 15:12:37 +13:00
brandon.presley 0eaac20e7e Expect exercises on plans to be non nullable 2023-11-11 14:53:38 +13:00
brandon.presley ea745c1cec Make CRUD work for Plans 2023-11-10 23:43:06 +13:00
25 changed files with 691 additions and 267 deletions
+25
View File
@@ -0,0 +1,25 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "fmassive",
"request": "launch",
"type": "dart"
},
{
"name": "fmassive (profile mode)",
"request": "launch",
"type": "dart",
"flutterMode": "profile"
},
{
"name": "fmassive (release mode)",
"request": "launch",
"type": "dart",
"flutterMode": "release"
}
]
}
+1
View File
@@ -4,3 +4,4 @@ linter:
rules:
curly_braces_in_flow_control_structures: false
avoid_print: false
require_trailing_commas: true
+9
View File
@@ -0,0 +1,9 @@
const List<String> weekdayNames = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
+4 -26
View File
@@ -1,6 +1,6 @@
import 'dart:io';
import 'package:fmassive/gym_set.dart';
import 'package:fmassive/gym_sets.dart';
import 'package:fmassive/main.dart';
import 'package:fmassive/plans.dart';
import 'package:moor/ffi.dart';
@@ -17,39 +17,17 @@ class MyDatabase extends _$MyDatabase {
MyDatabase() : super(_openConnection());
@override
int get schemaVersion => 2;
int get schemaVersion => 1;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (Migrator m) async {
print('Creating...');
await m.createAll();
var data = await (db.select(db.settings)..limit(1)).get();
if (data.isEmpty) await db.into(db.settings).insert(defaultSettings);
},
onUpgrade: (Migrator m, int from, int to) async {
if (from == 1) {
await m.addColumn(settings, settings.darkColor);
await db.customStatement('''
UPDATE settings SET dark_color = darkColor
''');
await m.addColumn(settings, settings.lightColor);
await db.customStatement('''
UPDATE settings SET light_color = lightColor
''');
await m.addColumn(settings, settings.showDate);
await db.customStatement('''
UPDATE settings SET show_date = showDate
''');
await m.addColumn(settings, settings.showSets);
await db.customStatement('''
UPDATE settings SET show_sets = showSets
''');
await m.addColumn(settings, settings.showUnit);
await db.customStatement('''
UPDATE settings SET show_unit = showUnit
''');
}
},
onUpgrade: (Migrator m, int from, int to) async {},
);
}
+32 -32
View File
@@ -1248,8 +1248,8 @@ class $GymSetsTable extends GymSets with TableInfo<$GymSetsTable, GymSet> {
class Plan extends DataClass implements Insertable<Plan> {
final int id;
final String days;
final String workouts;
Plan({required this.id, required this.days, required this.workouts});
final String exercises;
Plan({required this.id, required this.days, required this.exercises});
factory Plan.fromData(Map<String, dynamic> data, GeneratedDatabase db,
{String? prefix}) {
final effectivePrefix = prefix ?? '';
@@ -1258,8 +1258,8 @@ class Plan extends DataClass implements Insertable<Plan> {
.mapFromDatabaseResponse(data['${effectivePrefix}id'])!,
days: const StringType()
.mapFromDatabaseResponse(data['${effectivePrefix}days'])!,
workouts: const StringType()
.mapFromDatabaseResponse(data['${effectivePrefix}workouts'])!,
exercises: const StringType()
.mapFromDatabaseResponse(data['${effectivePrefix}exercises'])!,
);
}
@override
@@ -1267,7 +1267,7 @@ class Plan extends DataClass implements Insertable<Plan> {
final map = <String, Expression>{};
map['id'] = Variable<int>(id);
map['days'] = Variable<String>(days);
map['workouts'] = Variable<String>(workouts);
map['exercises'] = Variable<String>(exercises);
return map;
}
@@ -1275,7 +1275,7 @@ class Plan extends DataClass implements Insertable<Plan> {
return PlansCompanion(
id: Value(id),
days: Value(days),
workouts: Value(workouts),
exercises: Value(exercises),
);
}
@@ -1285,7 +1285,7 @@ class Plan extends DataClass implements Insertable<Plan> {
return Plan(
id: serializer.fromJson<int>(json['id']),
days: serializer.fromJson<String>(json['days']),
workouts: serializer.fromJson<String>(json['workouts']),
exercises: serializer.fromJson<String>(json['exercises']),
);
}
@override
@@ -1294,69 +1294,69 @@ class Plan extends DataClass implements Insertable<Plan> {
return <String, dynamic>{
'id': serializer.toJson<int>(id),
'days': serializer.toJson<String>(days),
'workouts': serializer.toJson<String>(workouts),
'exercises': serializer.toJson<String>(exercises),
};
}
Plan copyWith({int? id, String? days, String? workouts}) => Plan(
Plan copyWith({int? id, String? days, String? exercises}) => Plan(
id: id ?? this.id,
days: days ?? this.days,
workouts: workouts ?? this.workouts,
exercises: exercises ?? this.exercises,
);
@override
String toString() {
return (StringBuffer('Plan(')
..write('id: $id, ')
..write('days: $days, ')
..write('workouts: $workouts')
..write('exercises: $exercises')
..write(')'))
.toString();
}
@override
int get hashCode => Object.hash(id, days, workouts);
int get hashCode => Object.hash(id, days, exercises);
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is Plan &&
other.id == this.id &&
other.days == this.days &&
other.workouts == this.workouts);
other.exercises == this.exercises);
}
class PlansCompanion extends UpdateCompanion<Plan> {
final Value<int> id;
final Value<String> days;
final Value<String> workouts;
final Value<String> exercises;
const PlansCompanion({
this.id = const Value.absent(),
this.days = const Value.absent(),
this.workouts = const Value.absent(),
this.exercises = const Value.absent(),
});
PlansCompanion.insert({
this.id = const Value.absent(),
required String days,
required String workouts,
required String exercises,
}) : days = Value(days),
workouts = Value(workouts);
exercises = Value(exercises);
static Insertable<Plan> custom({
Expression<int>? id,
Expression<String>? days,
Expression<String>? workouts,
Expression<String>? exercises,
}) {
return RawValuesInsertable({
if (id != null) 'id': id,
if (days != null) 'days': days,
if (workouts != null) 'workouts': workouts,
if (exercises != null) 'exercises': exercises,
});
}
PlansCompanion copyWith(
{Value<int>? id, Value<String>? days, Value<String>? workouts}) {
{Value<int>? id, Value<String>? days, Value<String>? exercises}) {
return PlansCompanion(
id: id ?? this.id,
days: days ?? this.days,
workouts: workouts ?? this.workouts,
exercises: exercises ?? this.exercises,
);
}
@@ -1369,8 +1369,8 @@ class PlansCompanion extends UpdateCompanion<Plan> {
if (days.present) {
map['days'] = Variable<String>(days.value);
}
if (workouts.present) {
map['workouts'] = Variable<String>(workouts.value);
if (exercises.present) {
map['exercises'] = Variable<String>(exercises.value);
}
return map;
}
@@ -1380,7 +1380,7 @@ class PlansCompanion extends UpdateCompanion<Plan> {
return (StringBuffer('PlansCompanion(')
..write('id: $id, ')
..write('days: $days, ')
..write('workouts: $workouts')
..write('exercises: $exercises')
..write(')'))
.toString();
}
@@ -1403,13 +1403,13 @@ class $PlansTable extends Plans with TableInfo<$PlansTable, Plan> {
late final GeneratedColumn<String?> days = GeneratedColumn<String?>(
'days', aliasedName, false,
type: const StringType(), requiredDuringInsert: true);
final VerificationMeta _workoutsMeta = const VerificationMeta('workouts');
final VerificationMeta _exercisesMeta = const VerificationMeta('exercises');
@override
late final GeneratedColumn<String?> workouts = GeneratedColumn<String?>(
'workouts', aliasedName, false,
late final GeneratedColumn<String?> exercises = GeneratedColumn<String?>(
'exercises', aliasedName, false,
type: const StringType(), requiredDuringInsert: true);
@override
List<GeneratedColumn> get $columns => [id, days, workouts];
List<GeneratedColumn> get $columns => [id, days, exercises];
@override
String get aliasedName => _alias ?? 'plans';
@override
@@ -1428,11 +1428,11 @@ class $PlansTable extends Plans with TableInfo<$PlansTable, Plan> {
} else if (isInserting) {
context.missing(_daysMeta);
}
if (data.containsKey('workouts')) {
context.handle(_workoutsMeta,
workouts.isAcceptableOrUnknown(data['workouts']!, _workoutsMeta));
if (data.containsKey('exercises')) {
context.handle(_exercisesMeta,
exercises.isAcceptableOrUnknown(data['exercises']!, _exercisesMeta));
} else if (isInserting) {
context.missing(_workoutsMeta);
context.missing(_exercisesMeta);
}
return context;
}
-53
View File
@@ -1,53 +0,0 @@
import 'package:flutter/material.dart';
class Days extends StatefulWidget {
final ValueChanged<String> onChanged;
const Days({required this.onChanged, super.key});
@override
createState() => _DaysState();
}
class _DaysState extends State<Days> {
final List<bool> _selections = List.generate(7, (_) => false);
final List<String> _days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
String _getSelectedDaysString() {
List<String> selectedDays = [];
for (int i = 0; i < _selections.length; i++) {
if (_selections[i]) {
selectedDays.add(_days[i]);
}
}
return selectedDays.join(",");
}
void _updateSelections(int index) {
setState(() {
_selections[index] = !_selections[index];
widget.onChanged(_getSelectedDaysString());
});
}
@override
Widget build(BuildContext context) {
return Column(
children: List.generate(7, (index) {
return SwitchListTile(
title: Text(_days[index]),
value: _selections[index],
onChanged: (value) => _updateSelections(index),
);
}),
);
}
}
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import 'package:fmassive/main.dart';
import 'package:moor/moor.dart';
class DeleteAllSets extends StatelessWidget {
const DeleteAllSets({
super.key,
required this.mounted,
});
final bool mounted;
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: const Text("Delete all sets"),
onPressed: () async {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text("Delete all sets"),
content: const Text(
"This will irreversibly destroy all your gym set data. Are you sure?",),
actions: <Widget>[
ElevatedButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
ElevatedButton(
child: const Text('Delete'),
onPressed: () async {
await db.gymSets.delete().go();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Deleted all sets')),);
final navigator = Navigator.of(context);
navigator.pop();
},
),
],
);
},);
},
),
);
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ class _DynamicColorSchemeState extends State<DynamicColorScheme> {
context,
colorScheme.copyWith(
primary: color,
));
),);
},
);
}
+148 -61
View File
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as material;
import 'package:fmassive/constants.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/days.dart';
import 'package:fmassive/main.dart';
import 'package:moor_flutter/moor_flutter.dart';
@@ -15,91 +15,178 @@ class EditPlanPage extends StatefulWidget {
}
class _EditPlanPageState extends State<EditPlanPage> {
final TextEditingController _daysController = TextEditingController();
final TextEditingController _workoutsController = TextEditingController();
late PlansCompanion plan;
final daysNode = FocusNode();
final workoutsNode = FocusNode();
List<String?> names = [];
List<bool>? daySelections;
List<bool>? exerciseSelections;
Future<List<String?>> getDistinctNames() async {
final names = await (db.gymSets.selectOnly(distinct: true)
..addColumns([db.gymSets.name]))
.get();
return names.map((name) => name.read(db.gymSets.name)).toList();
}
@override
void initState() {
super.initState();
plan = widget.plan;
_daysController.text = plan.days.value;
_workoutsController.text = plan.workouts.value;
if (plan.id.present)
workoutsNode.requestFocus();
else
daysNode.requestFocus();
final dayList = widget.plan.days.value.split(',');
daySelections = weekdayNames.map((day) => dayList.contains(day)).toList();
getDistinctNames().then((value) {
setState(() {
names = value;
final exercises = widget.plan.exercises.value.split(',');
exerciseSelections =
names.map((name) => exercises.contains(name)).toList();
});
});
}
@override
dispose() {
daysNode.dispose();
workoutsNode.dispose();
super.dispose();
}
Future<bool?> _showConfirmationDialog(BuildContext context) {
return showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Confirm Delete'),
content: const Text('Are you sure you want to delete this plan?'),
actions: <Widget>[
ElevatedButton(
child: const Text('Yes'),
onPressed: () {
Navigator.pop(context, true); // showDialog() returns true
},
),
ElevatedButton(
child: const Text('No'),
onPressed: () {
Navigator.pop(context, false); // showDialog() returns false
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
List<Widget> actions = [];
if (widget.plan.id.present)
actions.add(IconButton(
actions.add(
IconButton(
onPressed: () async {
bool? confirm = await _showConfirmationDialog(context);
if (!confirm!) return;
await db.plans.deleteOne(widget.plan);
if (!mounted) return;
Navigator.pop(context);
},
icon: const Icon(Icons.delete)));
icon: const Icon(Icons.delete),
),
);
return SafeArea(
child: Scaffold(
appBar: AppBar(title: const Text('Edit Plan'), actions: actions),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: material.Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Days(onChanged: (days) {
setState(() {
days = days;
});
}),
TextFormField(
controller: _workoutsController,
focusNode: workoutsNode,
onTap: () {
_workoutsController.selection = TextSelection(
baseOffset: 0,
extentOffset: _workoutsController.text.length);
},
decoration: const InputDecoration(labelText: 'Workouts'),
onChanged: (value) {
setState(() {
plan = plan.copyWith(workouts: Value(value));
});
},
),
],
child: Scaffold(
appBar: AppBar(title: const Text('Edit Plan'), actions: actions),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: material.Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: getChildren,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final days = [];
for (int i = 0; i < daySelections!.length; i++) {
if (daySelections![i]) days.add(weekdayNames[i]);
}
if (days.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Select days first')),
);
return;
}
final exercises = [];
for (int i = 0; i < exerciseSelections!.length; i++) {
if (exerciseSelections![i]) exercises.add(names[i]);
}
if (exercises.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Select exercises first')),
);
return;
}
var newPlan = widget.plan.copyWith(
days: Value(days.join(',')),
exercises: Value(exercises.join(',')),
);
if (widget.plan.id.present)
await db.update(db.plans).replace(newPlan);
else {
final id = await db.into(db.plans).insert(newPlan);
newPlan = newPlan.copyWith(id: Value(id));
}
if (!mounted) return;
Navigator.pop(context);
},
child: const Icon(Icons.check),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
if (_daysController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please enter days')));
daysNode.requestFocus();
return;
}
if (plan.id.present)
await db.update(db.plans).replace(plan);
else
await db.into(db.plans).insert(plan);
if (!mounted) return;
Navigator.pop(context);
);
}
List<Widget> get getChildren {
final List<Widget> children = [
Text('Days', style: Theme.of(context).textTheme.headlineSmall),
];
final days = List.generate(7, (index) {
return SwitchListTile(
title: Text(weekdayNames[index]),
value: daySelections![index],
onChanged: (value) {
setState(() {
daySelections![index] = value;
});
},
child: const Icon(Icons.check),
);
});
final exercises = List.generate(names.length, (index) {
return SwitchListTile(
title: Text(names[index] ?? ''),
value: exerciseSelections![index],
onChanged: (value) {
setState(() {
exerciseSelections![index] = value;
});
},
);
});
children.addAll(days);
children.add(
Text('Exercises', style: Theme.of(context).textTheme.headlineSmall),
);
children.addAll(exercises);
return [
Expanded(
child: ListView(
children: children,
),
),
));
];
}
}
+11 -9
View File
@@ -34,7 +34,7 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
if (gymSet.id.present) {
repsNode.requestFocus();
_repsController.selection = TextSelection(
baseOffset: 0, extentOffset: _repsController.text.length);
baseOffset: 0, extentOffset: _repsController.text.length,);
} else
nameNode.requestFocus();
}
@@ -56,7 +56,7 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
if (!mounted) return;
Navigator.pop(context);
},
icon: const Icon(Icons.delete)));
icon: const Icon(Icons.delete),),);
return SafeArea(
child: Scaffold(
@@ -72,7 +72,7 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
decoration: const InputDecoration(labelText: 'Name'),
onTap: () {
_nameController.selection = TextSelection(
baseOffset: 0, extentOffset: _nameController.text.length);
baseOffset: 0, extentOffset: _nameController.text.length,);
},
onChanged: (value) {
setState(() {
@@ -85,7 +85,7 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
focusNode: repsNode,
onTap: () {
_repsController.selection = TextSelection(
baseOffset: 0, extentOffset: _repsController.text.length);
baseOffset: 0, extentOffset: _repsController.text.length,);
},
decoration: const InputDecoration(labelText: 'Reps'),
keyboardType: TextInputType.number,
@@ -102,12 +102,12 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
keyboardType: TextInputType.number,
onTap: () {
_weightController.selection = TextSelection(
baseOffset: 0, extentOffset: _weightController.text.length);
baseOffset: 0, extentOffset: _weightController.text.length,);
},
onChanged: (value) {
setState(() {
gymSet = gymSet.copyWith(
weight: Value(double.tryParse(value) ?? 0));
weight: Value(double.tryParse(value) ?? 0),);
});
},
),
@@ -118,7 +118,7 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
onPressed: () async {
if (_nameController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please enter a name')));
const SnackBar(content: Text('Please enter a name')),);
nameNode.requestFocus();
return;
}
@@ -126,7 +126,9 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
await db.update(db.gymSets).replace(gymSet);
else {
await Permission.notification.request();
await db.into(db.gymSets).insert(gymSet);
final newSet = gymSet.copyWith(
created: Value(DateTime.now().toIso8601String()),);
await db.into(db.gymSets).insert(newSet);
const platform = MethodChannel('com.massive/android');
platform.invokeMethod('timer', [3000]);
}
@@ -135,6 +137,6 @@ class _EditGymSetPageState extends State<EditGymSetPage> {
},
child: const Icon(Icons.check),
),
));
),);
}
}
+1 -1
View File
@@ -101,6 +101,6 @@ class _HomePage extends State<HomePage> {
],
),
body: getBody(),
));
),);
}
}
+2 -11
View File
@@ -1,6 +1,5 @@
import 'package:flutter/material.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/edit_set.dart';
import 'package:fmassive/home_page.dart';
MyDatabase db = MyDatabase();
@@ -16,20 +15,12 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
const edit = EditGymSetPage(gymSet: GymSetsCompanion());
final Map<String, WidgetBuilder> routes = {
'/home': (context) => const HomePage(),
'/edit-set': (context) => edit,
};
return MaterialApp(
title: 'Gym App',
title: 'Massive',
themeMode: ThemeMode.system,
home: const HomePage(),
darkTheme: ThemeData.dark(),
theme: ThemeData.light(),
initialRoute: '/home',
routes: routes,
navigatorKey: navigatorKey,
);
}
+25
View File
@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import 'package:fmassive/constants.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/plan_tile.dart';
class PlanList extends StatelessWidget {
const PlanList({
super.key,
required this.plans,
});
final List<Plan> plans;
@override
Widget build(BuildContext context) {
final weekday = weekdayNames[DateTime.now().weekday - 1];
return ListView.builder(
itemCount: plans.length,
itemBuilder: (context, index) {
return PlanTile(plan: plans[index], weekday: weekday);
},
);
}
}
+68
View File
@@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/edit_plan.dart';
import 'package:fmassive/main.dart';
import 'package:fmassive/start_plan.dart';
import 'package:moor_flutter/moor_flutter.dart';
class PlanTile extends StatelessWidget {
PlanTile({
super.key,
required this.plan,
required this.weekday,
});
final Plan plan;
final String weekday;
final tapPosition = GlobalKey();
@override
Widget build(BuildContext context) {
return MenuAnchor(
menuChildren: [
MenuItemButton(
child: const Text("Edit"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
EditPlanPage(plan: plan.toCompanion(false)),
),
);
},
),
MenuItemButton(
onPressed: () async {
await db.plans.deleteOne(plan);
},
child: const Text("Delete"),
),
],
builder: (context, controller, child) {
return ListTile(
title: Text(
plan.days.replaceAll(',', ', '),
style: TextStyle(
fontWeight: plan.days.contains(weekday) ? FontWeight.bold : null,
decoration:
plan.days.contains(weekday) ? TextDecoration.underline : null,
),
),
subtitle: Text(plan.exercises),
onLongPress: () {
controller.open();
},
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StartPlan(plan: plan.toCompanion(false)),
),
);
},
);
},
);
}
}
+1 -1
View File
@@ -3,5 +3,5 @@ import 'package:moor/moor.dart';
class Plans extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get days => text()();
TextColumn get workouts => text()();
TextColumn get exercises => text()();
}
+18 -25
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/edit_plan.dart';
import 'package:fmassive/main.dart';
import 'package:fmassive/plan_list.dart';
import 'package:moor/moor.dart';
class PlansPage extends StatelessWidget {
@@ -20,7 +21,7 @@ class PlansPage extends StatelessWidget {
}
class _PlansPage extends StatefulWidget {
const _PlansPage({super.key, required this.search});
const _PlansPage({required this.search});
final String search;
@@ -65,39 +66,31 @@ class _PlansPageState extends State<_PlansPage> {
builder: (context, snapshot) {
final plans = snapshot.data;
if (plans == null)
return const Center(child: CircularProgressIndicator());
if (snapshot.hasError)
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Error: ${snapshot.error}',
style: Theme.of(context).textTheme.headlineSmall,
),),
);
return ListView.builder(
itemCount: plans.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(plans[index].days.replaceAll(',', ', ')),
subtitle:
Text(plans[index].workouts.replaceAll(',', ', ')),
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditPlanPage(
plan: plans[index].toCompanion(false)),
),
);
});
},
);
}),
if (plans == null) return Container();
return PlanList(plans: plans);
},),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const EditPlanPage(
plan:
PlansCompanion(days: Value(''), workouts: Value(''))),
plan: PlansCompanion(
days: Value(''), exercises: Value(''),),),
),
);
},
child: const Icon(Icons.add)));
child: const Icon(Icons.add),),);
}
}
+5 -10
View File
@@ -69,10 +69,6 @@ class _SetList extends State<SetList> {
pagingController: pagingController,
gymSet: gymSet,
),
firstPageProgressIndicatorBuilder: (_) =>
const Center(child: CircularProgressIndicator()),
newPageProgressIndicatorBuilder: (_) =>
const Center(child: CircularProgressIndicator()),
),
),
floatingActionButton: FloatingActionButton(
@@ -80,13 +76,12 @@ class _SetList extends State<SetList> {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditGymSetPage(
builder: (context) => const EditGymSetPage(
gymSet: GymSetsCompanion(
name: const Value(''),
reps: const Value(0),
weight: const Value(0),
image: const Value(''),
created: Value(DateTime.now().toString()),
name: Value(''),
reps: Value(0),
weight: Value(0),
image: Value(''),
),
),
),
+4 -5
View File
@@ -20,10 +20,9 @@ class SetTile extends StatelessWidget {
Widget build(BuildContext context) {
return ListTile(
title: Text(gymSet.name),
subtitle: Text("${gymSet.reps} x ${gymSet.weight}kg"),
trailing: Text(
DateFormat("yyyy-MM-dd").format(DateTime.parse(gymSet.created)),
),
subtitle: Text(DateFormat("yyyy-MM-dd HH:mm")
.format(DateTime.parse(gymSet.created)),),
trailing: Text("${gymSet.reps} x ${gymSet.weight}kg"),
onTap: () async {
await Navigator.push(
context,
@@ -41,7 +40,7 @@ class SetTile extends StatelessWidget {
return AlertDialog(
title: const Text('Delete set'),
content: Text(
'Are you sure you want to delete ${gymSet.name} ${gymSet.reps}x${gymSet.weight}${gymSet.unit}?'),
'Are you sure you want to delete ${gymSet.name} ${gymSet.reps}x${gymSet.weight}${gymSet.unit}?',),
actions: <Widget>[
ElevatedButton(
child: const Text('Cancel'),
+48 -31
View File
@@ -1,14 +1,15 @@
import 'dart:convert';
import 'dart:io';
import 'package:csv/csv.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as material;
import 'package:fmassive/database.dart';
import 'package:fmassive/delete_all_sets.dart';
import 'package:fmassive/main.dart';
import 'package:fmassive/sound_picker.dart';
import 'package:moor/moor.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key, required this.search});
@@ -26,7 +27,7 @@ class SettingsPage extends StatelessWidget {
}
class _SettingsPage extends StatefulWidget {
const _SettingsPage({super.key, required this.search});
const _SettingsPage({required this.search});
final String search;
@@ -52,8 +53,7 @@ class _SettingsPageState extends State<_SettingsPage> {
final settings = snapshot.data;
print('build: $settings');
if (settings == null)
return const Center(child: CircularProgressIndicator());
if (settings == null) return Container();
final filteredItems = [
{'title': 'Alarm', 'value': settings.alarm},
@@ -63,11 +63,12 @@ class _SettingsPageState extends State<_SettingsPage> {
{'title': 'Show Unit', 'value': settings.showUnit},
{'title': 'Steps', 'value': settings.steps},
{'title': 'Sound', 'value': settings.sound},
{'title': 'Import', 'value': settings.sound},
{'title': 'Import sets', 'value': null},
{'title': 'Delete all sets', 'value': null},
]
.where((item) => (item['title'] as String)
.toLowerCase()
.contains(widget.search.toLowerCase()))
.contains(widget.search.toLowerCase()),)
.toList();
return material.Column(
@@ -78,31 +79,47 @@ class _SettingsPageState extends State<_SettingsPage> {
itemBuilder: (context, index) {
final item = filteredItems[index];
if (item['title'] == 'Import')
if (item['title'] == 'Delete all sets')
return DeleteAllSets(mounted: mounted);
if (item['title'] == 'Import sets')
return Center(
child: ElevatedButton(
onPressed: () async {
final result =
await FilePicker.platform.pickFiles(
type: FileType.any,
);
if (result == null) return;
child: const Text("Import sets"),
onPressed: () async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['csv'],);
if (result == null) return;
final file = File(result.files.single.path!);
final path = await getDatabasesPath();
final to = join(path, 'massive.db');
await db.close();
await file.copy(to);
print('Migrating...');
db = MyDatabase();
final migrator = db.createMigrator();
await migrator.createAll();
await db.customInsert('''
INSERT INTO gym_sets(id, name, reps, weight, created, unit, hidden, image, sets, minutes, seconds, steps)
SELECT id, name, reps, weight, created, unit, hidden, image, sets, minutes, seconds, steps FROM sets''');
print('Migrated.');
},
child: const Text("Import")));
final file = File(result.files.single.path!);
final input = file.openRead();
final fields = await input
.transform(utf8.decoder)
.transform(const CsvToListConverter(eol: "\n"))
.skip(1)
.toList();
final gymSets = fields.map((row) => GymSetsCompanion(
id: Value(int.tryParse(row[0]) ?? 0),
name: Value(row[1]),
reps: Value(int.tryParse(row[2]) ?? 0),
weight: Value(double.tryParse(row[3]) ?? 0),
created: Value(row[4]),
unit: Value(row[5]),
hidden: Value(row[6] == 'true'),
image: Value(row[7]),
sets: Value(int.tryParse(row[8]) ?? 0),
minutes: Value(int.tryParse(row[9]) ?? 0),
seconds: Value(int.tryParse(row[10]) ?? 0),
steps: Value(row[11]),
),);
await db.batch(
(batch) => batch.insertAll(db.gymSets, gymSets),);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Imported sets')),);
},
),);
if (item['title'] == 'Sound') {
return Center(
@@ -129,7 +146,7 @@ class _SettingsPageState extends State<_SettingsPage> {
break;
case 'Vibrate':
db.update(db.settings).write(
SettingsCompanion(vibrate: Value(value)));
SettingsCompanion(vibrate: Value(value)),);
break;
case 'Notify':
db
@@ -143,7 +160,7 @@ class _SettingsPageState extends State<_SettingsPage> {
break;
case 'Show Unit':
db.update(db.settings).write(
SettingsCompanion(showUnit: Value(value)));
SettingsCompanion(showUnit: Value(value)),);
break;
case 'Steps':
db
+1 -1
View File
@@ -37,7 +37,7 @@ class _SoundPickerState extends State<SoundPicker> {
},
child: Text(widget.path != null
? "Sound: ${basename(widget.path!)}"
: 'Alarm sound'),
: 'Alarm sound',),
);
}
}
+222
View File
@@ -0,0 +1,222 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as material;
import 'package:flutter/services.dart';
import 'package:fmassive/database.dart';
import 'package:fmassive/main.dart';
import 'package:moor_flutter/moor_flutter.dart';
class StartPlan extends StatefulWidget {
final PlansCompanion plan;
const StartPlan({required this.plan, super.key});
@override
createState() => _StartPlanState();
}
class _StartPlanState extends State<StartPlan> {
late List<String> exercises;
List<int> counts = [];
List<int> totals = [];
int selectedExercise = 0;
final repsController = TextEditingController();
final repsNode = FocusNode();
final weightController = TextEditingController();
final weightNode = FocusNode();
int current = 0;
int minutes = 3;
int seconds = 30;
Timer? timer;
void startTimer() {
setState(() {
current = minutes * 60 * 1000 + seconds * 1000;
});
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
print("StartPlan: current=$current");
if (current == 0)
setState(() {
timer.cancel();
});
else
setState(() {
current -= 1000;
});
});
}
Future<void> getTotals() async {
final query = await (db.selectOnly(db.gymSets)
..addColumns([db.gymSets.name, db.gymSets.sets])
..where(db.gymSets.name.isIn(exercises))
..groupBy([db.gymSets.name, db.gymSets.sets]))
.map(
(row) =>
MapEntry(row.read(db.gymSets.name), row.read(db.gymSets.sets)),
)
.get();
final map = Map.fromIterables(
query.map((entry) => entry.key),
query.map((entry) => entry.value),
);
setState(() {
totals = [];
for (var exercise in exercises) {
totals.add(map[exercise] ?? 0);
}
});
print("totals=$totals");
}
Future<void> getCounts() async {
var countExp = db.gymSets.name.count();
final today = DateTime.now().toIso8601String().split('T')[0];
final query = await (db.selectOnly(db.gymSets)
..addColumns([countExp, db.gymSets.name])
..where(db.gymSets.created.contains(today))
..groupBy([db.gymSets.name]))
.map((row) => MapEntry(row.read(db.gymSets.name), row.read(countExp)))
.get();
final map = Map.fromIterables(
query.map((entry) => entry.key),
query.map((entry) => entry.value),
);
setState(() {
counts = [];
for (var exercise in exercises) {
counts.add(map[exercise] ?? 0);
}
});
print("counts=$counts");
}
Future<void> focus(int index) async {
final name = exercises[index];
final sets = await (db.gymSets.select()
..where((gymSet) => gymSet.name.contains(name))
..orderBy([
(u) => OrderingTerm(expression: u.created, mode: OrderingMode.desc),
])
..limit(1))
.get();
final firstSet = sets.first;
setState(() {
repsController.text = firstSet.reps.toString();
repsController.selection = TextSelection(
baseOffset: 0,
extentOffset: firstSet.reps.toString().length,
);
weightController.text = firstSet.weight.toString();
minutes = firstSet.minutes;
seconds = firstSet.seconds;
});
}
@override
void initState() {
super.initState();
exercises = widget.plan.exercises.value.split(',');
repsNode.requestFocus();
getCounts();
getTotals();
focus(selectedExercise);
}
@override
dispose() {
super.dispose();
timer?.cancel();
}
@override
Widget build(BuildContext context) {
if (totals.isEmpty || counts.isEmpty) return Container();
return SafeArea(
child: Scaffold(
appBar: AppBar(title: const Text('Start plan')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: material.Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ListView.builder(
itemBuilder: ((context, index) {
return ListTile(
title: Text(exercises[index]),
subtitle: Text("${counts[index]}/${totals[index]}"),
onTap: () {
setState(() {
selectedExercise = index;
focus(index);
});
},
leading: Radio<int>(
value: index,
groupValue: selectedExercise,
onChanged: (value) {
print("onChanged $value");
if (value == null) return;
setState(() {
selectedExercise = value;
focus(index);
});
},
),
);
}),
itemCount: exercises.length,
),
),
TextFormField(
decoration: const InputDecoration(labelText: 'Reps'),
controller: repsController,
focusNode: repsNode,
onTap: () {
repsController.selection = TextSelection(
baseOffset: 0,
extentOffset: repsController.text.length,
);
},
),
TextFormField(
decoration: const InputDecoration(labelText: 'Weight'),
controller: weightController,
focusNode: weightNode,
onTap: () {
weightController.selection = TextSelection(
baseOffset: 0,
extentOffset: weightController.text.length,
);
},
),
LinearProgressIndicator(
value: current / (minutes * 60 * 1000 + seconds * 1000),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final gymSet = GymSetsCompanion(
created: Value(DateTime.now().toIso8601String()),
name: Value(exercises[selectedExercise]),
reps: Value(int.tryParse(repsController.text) ?? 0),
weight: Value(double.tryParse(weightController.text) ?? 0),
);
await db.into(db.gymSets).insert(gymSet);
const platform = MethodChannel('com.massive/android');
platform
.invokeMethod('timer', [minutes * 60 * 1000 + seconds * 1000]);
startTimer();
await getCounts();
},
child: const Icon(Icons.check),
),
),
);
}
}
+8
View File
@@ -241,6 +241,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.3"
csv:
dependency: "direct main"
description:
name: csv
sha256: "63ed2871dd6471193dffc52c0e6c76fb86269c00244d244297abbb355c84a86e"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
cupertino_icons:
dependency: "direct main"
description:
+1
View File
@@ -47,6 +47,7 @@ dependencies:
intl: ^0.18.0
permission_handler: ^11.0.1
infinite_scroll_pagination: ^4.0.0
csv: ^5.1.1
dev_dependencies:
flutter_test:
+5
View File
@@ -31,6 +31,11 @@ bool FlutterWindow::OnCreate() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}