sendMessage method

void sendMessage(
  1. String text,
  2. String session_id, {
  3. bool displayMessage = true,
  4. Map<String, dynamic>? payload,
})

Implementation

void sendMessage(String text, String session_id, {bool displayMessage = true, Map<String, dynamic>? payload}) async {
  if (text.trim().isEmpty) return;

  if (displayMessage) {
    final userMessage = ResponseMessage(
      MessageType.user,
      DateTime.now(),
      text: text,
    );

    setState(() {
      _messages.add(userMessage);
    });

    _controller.clear();
    _scrollToBottom();

    final loadingMessage = ResponseMessage(
      MessageType.bot,
      DateTime.now(),
      customWidget: Container(
        width: 40,
        child: SpinKitThreeBounce(
          color: Colors.blue,
          size: 15,
        ),
      ),
    );

    setState(() {
      _messages.add(loadingMessage);
    });
  }

  if (_useAgentMessage) {
    final responseMessage = await ChatService().agentMessage(
        text,
        session_id,
        widget.agentId,
        isMarkdown: true);

    setState(() {
      if (displayMessage) {
        _messages.removeLast();
      }
      _messages.add(responseMessage);
    });
  } else {
    final responseMessages = await ChatService().sendMessage(text, session_id, payload: payload);
    final mappedMessages = responseMessages.map((response) {
      return ResponseMessage(
        response.type,
        DateTime.now(),
        responseType: response.responseType,
        text: response.text,
        wholeResponsePayload: response.wholeResponsePayload,
      );
    }).toList();

    setState(() {
      if (displayMessage) {
        _messages.removeLast();
      }
      _messages.addAll(mappedMessages);
    });
  }

  _scrollToBottom();
}