deleteMessage method

Future<EmptyResponse> deleteMessage(
  1. Message message, {
  2. bool hard = false,
})

Deletes the message from the channel.

Implementation

Future<EmptyResponse> deleteMessage(
  Message message, {
  bool hard = false,
}) async {
  _checkInitialized();

  // Directly deleting the local messages which are not yet sent to server.
  if (message.remoteCreatedAt == null) {
    state!.deleteMessage(
      message.copyWith(
        type: 'deleted',
        localDeletedAt: DateTime.now(),
        state: MessageState.deleted(hard: hard),
      ),
      hardDelete: hard,
    );

    // Removing the attachments upload completer to stop the `sendMessage`
    // waiting for attachments to complete.
    _messageAttachmentsUploadCompleter
        .remove(message.id)
        ?.completeError(const StreamChatError('Message deleted'));

    // Returning empty response to mark the api call as success.
    return EmptyResponse();
  }

  // ignore: parameter_assignments
  message = message.copyWith(
    type: 'deleted',
    deletedAt: DateTime.now(),
    state: MessageState.deleting(hard: hard),
  );

  state?.deleteMessage(message, hardDelete: hard);

  try {
    // Wait for the previous delete call to finish. Otherwise, the order of
    // messages will not be maintained.
    final response = await _deleteMessageLock.synchronized(
      () => _client.deleteMessage(message.id, hard: hard),
    );

    final deletedMessage = message.copyWith(
      state: MessageState.deleted(hard: hard),
    );

    state?.deleteMessage(deletedMessage, hardDelete: hard);

    if (hard) {
      deletedMessage.attachments.forEach((attachment) {
        if (attachment.uploadState.isSuccess) {
          if (attachment.type == AttachmentType.image) {
            deleteImage(attachment.imageUrl!);
          } else if (attachment.type == AttachmentType.file) {
            deleteFile(attachment.assetUrl!);
          }
        }
      });
    }

    return response;
  } catch (e) {
    if (e is StreamChatNetworkError && e.isRetriable) {
      state!._retryQueue.add([
        message.copyWith(
          // Update the message state to failed.
          state: MessageState.deletingFailed(hard: hard),
        ),
      ]);
    }
    rethrow;
  }
}