toggleAttachment method

Future<void> toggleAttachment(
  1. Attachment attachment,
  2. bool active
)

Implementation

Future<void> toggleAttachment(Attachment attachment, bool active) async {
  final int index = attachments.indexOf(attachment);
  if (index < 0) return;
  final bool previousSelected = attachment.selected;
  final bool previousAllDisabled = allAttachmentsDisabled.value;

  attachments[index].selected = active;
  attachments.refresh();
  allAttachmentsDisabled.value = !attachments.any(
    (Attachment a) => a.selected,
  );
  update();

  const int maxRetries = 3;
  Attachment? updatedAttachment;
  for (int attempt = 0; attempt < maxRetries; attempt++) {
    try {
      updatedAttachment = await AttachmentService.patchAttachmentSelected(
        attachment.id,
        active,
      );
      if (updatedAttachment != null) break;
    } catch (_) {}
  }
  if (updatedAttachment == null && index < attachments.length) {
    attachments[index].selected = previousSelected;
    attachments.refresh();
    allAttachmentsDisabled.value = previousAllDisabled;
    update();
  }
}