moveCategory method

Future<void> moveCategory(
  1. PrintCategory category,
  2. int direction
)

Moves category one place up (-1) or down (+1) and stores the new positions of every category.

Implementation

Future<void> moveCategory(PrintCategory category, int direction) async {
  final ordered = categories;
  final index = ordered.indexWhere((entry) => entry.id == category.id);
  final target = index + direction;
  if (index < 0 || target < 0 || target >= ordered.length) return;
  final moved = ordered.removeAt(index);
  ordered.insert(target, moved);
  for (var position = 0; position < ordered.length; position++) {
    if (ordered[position].position != position) {
      await saveCategory(ordered[position].copyWith(position: position));
    }
  }
}