sendMessage method

void sendMessage(
  1. String content
)

Implementation

void sendMessage(String content) async {
  if (content.trim().isEmpty) return;

  // Add user message
  final userMessage = ChatMessage.user(content: content);
  _messages.add(userMessage);
  _error = null;
  notifyListeners();

  // Add typing indicator
  _isTyping = true;
  notifyListeners();

  // Add placeholder for assistant message
  final assistantMessage = ChatMessage.assistant(content: '', isStreaming: true);
  _messages.add(assistantMessage);
  notifyListeners();

  try {
    // Start streaming response
    final stream = _aiService.sendMessageStream(
      message: content,
      conversationHistory: _messages.where((m) => m.role != MessageRole.error).toList(),
    );

    _streamSubscription = stream.listen(
      (chunk) {
        // Update the last message with new chunk
        final lastIndex = _messages.length - 1;
        final updatedMessage = _messages[lastIndex].copyWith(
          content: _messages[lastIndex].content + chunk,
        );
        _messages[lastIndex] = updatedMessage;
        notifyListeners();
      },
      onError: (error) {
        _handleError(error.toString());
      },
      onDone: () {
        // Mark streaming as complete
        final lastIndex = _messages.length - 1;
        _messages[lastIndex] = _messages[lastIndex].copyWith(isStreaming: false);
        _isTyping = false;
        _streamSubscription = null;
        notifyListeners();
      },
    );
  } catch (e) {
    _handleError(e.toString());
  }
}