sendMessage method
Sends a message to the AI service and adds it to the current conversation.
If no conversation is currently selected, a new one will be created. The method handles:
- Adding the user message to the conversation
- Setting loading state
- Calling the AI service
- Adding the AI response
- Updating conversation title
- Error handling
Throws an exception if the AI service fails.
Implementation
Future<void> sendMessage(String content) async {
if (_currentConversation == null) {
createNewConversation();
}
final userMessage = ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
content: content,
isUser: true,
timestamp: DateTime.now(),
);
// Update conversation with user message
_currentConversation = _currentConversation!.addMessage(userMessage);
_updateConversationInList(_currentConversation!);
_isLoading = true;
_error = '';
notifyListeners();
try {
final aiResponse = await _aiService.sendMessage(content);
final aiMessage = ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
content: aiResponse,
isUser: false,
timestamp: DateTime.now(),
);
// Update conversation with AI message
_currentConversation = _currentConversation!.addMessage(aiMessage);
_updateConversationInList(_currentConversation!);
_updateConversationTitle();
} on Exception catch (e) {
_error = 'Failed to get AI response: $e';
} finally {
_isLoading = false;
notifyListeners();
}
}