sendUserMessage method Null safety

UserMessage sendUserMessage(
  1. UserMessageParams params,
  2. {OnUserMessageCallback? onCompleted}
)

Sends UserMessage on this channel with params.

It returns UserMessage with MessageSendingStatus.pending and onCompleted will be invoked once the message has been sent completely. Channel event ChannelEventHandler.onMessageReceived will be invoked on all other members' end.

Implementation

UserMessage sendUserMessage(
  UserMessageParams params, {
  OnUserMessageCallback? onCompleted,
}) {
  if (params.message.isEmpty) {
    throw InvalidParameterError();
  }

  final cmd = Command.buildUserMessage(
    channelUrl,
    params,
    Uuid().v1(),
  );
  final pending = BaseMessage.msgFromJson<UserMessage>(
    cmd.payload,
    channelType: channelType,
    type: cmd.cmd,
  )!;

  if (!_sdk.state.hasActiveUser) {
    final error = ConnectionRequiredError();
    pending
      ..errorCode = error.code
      ..sendingStatus = MessageSendingStatus.failed;
    if (onCompleted != null) onCompleted(pending, error);
    return pending;
  }

  pending.sendingStatus = MessageSendingStatus.pending;
  pending.sender = Sender.fromUser(_sdk.state.currentUser, this);

  _sdk.cmdManager.sendCommand(cmd).then((result) {
    if (result == null) return;
    final msg = BaseMessage.msgFromJson<UserMessage>(
      result.payload,
      type: result.cmd,
    );
    if (onCompleted != null && msg != null) onCompleted(msg, null);
  }).catchError((e) {
    pending
      ..errorCode = e?.code ?? ErrorCode.unknownError
      ..sendingStatus = MessageSendingStatus.failed;
    if (onCompleted != null) onCompleted(pending, e);
  });

  return pending;
}