sendMessage static method

Future<TextMessage?> sendMessage(
  1. TextMessage message, {
  2. MessageSentListener? listener,
  3. dynamic onSuccess(
    1. TextMessage message
    )?,
  4. dynamic onError(
    1. CometChatException excep
    )?,
})

To send a text message to a single user or group. returns the TextMessage with message id

receiver The UID or GUID of the recipient

messageText The text to be sent

receiverType The type of the receiver to whom the message is to be sent i.e user or group

Migration Note: Migrated from platform channels to native Dart implementation. Behavior and signature remain identical for backward compatibility.

Android Reference: MessagesRequest.sendMessage(TextMessage message)

The method could throw PlatformException with error codes specifying the cause Offline (opt-in, additive): pass listener to receive the three-phase send — onMessagePending (queued locally) → onMessageSent (server-acked) / onError. See _offlineSend for the exact backward-compatibility rules.

Implementation

static Future<TextMessage?> sendMessage(
  TextMessage message, {
  MessageSentListener? listener,
  Function(TextMessage message)? onSuccess,
  Function(CometChatException excep)? onError,
}) async {
  // BC: a listener-less send NEVER enters the outbox (see _offlineAdoptingSend).
  // An offline-adopting send returns the acked message (or throws offline).
  final offlineAcked = await _offlineAdoptingSend(message, listener);
  if (offlineAcked != null) return offlineAcked as TextMessage?;
  try {
    // Get SDK instance
    final sdk = SdkRegistry.getInstance();

    // Call native Dart message repository
    final sentMessage = await sdk.messages.sendTextMessage(message);

    // A7: an own threaded send auto-subscribes the sender (BEH-FLAG-08).
    // Queued, not awaited: the callback never waits on the cache.
    unawaited(OfflineRuntime.instance.onOwnDirectSendSucceeded(sentMessage));

    // Call success callback (listener wins — never both).
    if (listener != null) {
      listener.onMessageSent(sentMessage);
    } else if (onSuccess != null) {
      onSuccess(sentMessage);
    }
    return sentMessage;
  } on SdkException catch (sdkEx) {
    // Convert SdkException to CometChatException
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    if (listener != null) {
      listener.onError(cometChatEx);
    } else {
      _errorCallbackHandler(cometChatEx, null, null, onError);
    }
  } catch (e) {
    if (listener != null) {
      listener.onError(
        CometChatException('ERROR', e.toString(), e.toString()),
      );
    } else {
      _errorCallbackHandler(null, null, e, onError);
    }
  }
  return null;
}