fmassive/lib/edit_plan.dart

140 lines
3.7 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as material;
import 'package:fmassive/database.dart';
import 'package:fmassive/days.dart';
import 'package:fmassive/exercises.dart';
import 'package:fmassive/main.dart';
import 'package:moor_flutter/moor_flutter.dart';
class EditPlanPage extends StatefulWidget {
final PlansCompanion plan;
const EditPlanPage({required this.plan, super.key});
@override
createState() => _EditPlanPageState();
}
class _EditPlanPageState extends State<EditPlanPage> {
late PlansCompanion plan;
List<String?> names = [];
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();
getDistinctNames().then((value) {
setState(() {
names = value;
});
});
plan = widget.plan;
}
@override
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(
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)));
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: getChildren,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
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);
},
child: const Icon(Icons.check),
),
));
}
List<Widget> get getChildren {
return [
Expanded(
child: Days(
onChanged: (days) {
setState(() {
plan = plan.copyWith(days: Value(days));
});
},
days: plan.days.value,
),
),
names.isNotEmpty
? Expanded(
child: Exercises(
onChanged: (exercises) {
setState(() {
plan = plan.copyWith(exercises: Value(exercises));
});
},
exercises: plan.exercises.value,
names: names,
),
)
: const CircularProgressIndicator(),
];
}
}