diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 4078c972..ffdc9541 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -403,6 +403,22 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier { return set; } + Future editSet(Set workoutSet) async { + await patch(workoutSet.toJson(), makeUrl(_setsUrlPath, id: workoutSet.id)); + notifyListeners(); + } + + // Sets the order field for the given list of sets, starting from startIndex. + // Better than calling editSet for each set after reordering as it will notify + // for every element, rebuilding for each notification. + Future reorderSets(List sets, int startIndex) async { + for (int i = startIndex; i < sets.length; i++) { + sets[i].order = i; + await patch(sets[i].toJson(), makeUrl(_setsUrlPath, id: sets[i].id)); + } + notifyListeners(); + } + Future fetchComputedSettings(Set workoutSet) async { final data = await fetch(makeUrl( _setsUrlPath, diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 90dc749c..58a26baa 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -145,6 +145,7 @@ class _WorkoutDayWidgetState extends State { @override Widget build(BuildContext context) { + _sets.sort((a, b) => a.order!.compareTo(b.order!)); return Padding( padding: const EdgeInsets.only(left: 8, right: 8, bottom: 12), child: Card( @@ -209,17 +210,22 @@ class _WorkoutDayWidgetState extends State { ReorderableListView( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, - onReorder: (oldIndex, newIndex) { + onReorder: (_oldIndex, _newIndex) async { + int _startIndex = 0; + if (_oldIndex < _newIndex) { + _newIndex -= 1; + _startIndex = _oldIndex; + } else { + _startIndex = _newIndex; + } setState(() { - if (oldIndex < newIndex) { - newIndex -= 1; - } - final Set _set = _sets.removeAt(oldIndex); - _sets.insert(newIndex, _set); + final Set _set = _sets.removeAt(_oldIndex); + _sets.insert(_newIndex, _set); }); + Provider.of(context, listen: false).reorderSets(_sets, _startIndex); }, children: [ - for (final _set in _sets) + for (final _set in widget._day.sets) getSetRow(_set), ], ),