sendMessage method
void
sendMessage(})
Implementation
void sendMessage(String text, {bool displayMessage = true, bool action = false, String? session_id = null, String? language, dynamic payload}) async {
_confettiController.play(); // Start confetti animation
String? previousText = ''; // Store previously sent text here, if available
String textToSend = text ?? previousText;
_scrollToBottom();
if (text.trim().isEmpty) return;
if (textToSend == null || textToSend.isEmpty) {
// print('No text available to send.');
return;
}
if (displayMessage) {
final userMessage = ResponseMessage(
MessageType.user,
DateTime.now(),
text: text,
);
setState(() {
_messages.add(userMessage);
_isloading = true; // Set loading to true
});
_controller.clear();
_scrollToBottom();
}
final loadingMessage = ResponseMessage(
MessageType.bot,
DateTime.now(),
customWidget: BubbleWidget(
widget: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_agentName ??'HAIVA ',
style: GoogleFonts.questrial(
color: ColorTheme.accent,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
Text(
" ${_loadingStates[_currentIndex]}",
style: GoogleFonts.questrial(
color: ColorTheme.primary,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
SizedBox(width: 8), // Spacing between text and loader
Container(
width: 15,
height: 10,
child: SpinKitThreeBounce(
color: ColorTheme.primary,
size: 10,
),
),
],
),
),
);
setState(() {
_messages.add(loadingMessage);
});
String? finalTextToSend = text ?? _prevMessage;
try {
Map<String, dynamic>? formData;
if (payload != null && payload is Map<String, dynamic>) {
formData = payload;
}
final responseMessage = await HaivaService().haivaMessage(
text,
widget.agentId,
isMarkdown: true,
isButtonClicked: action,
sessionId: _sessionId,
language:_currentLocaleId,
// payloadType: 'form',
payloadType: formData != null ? 'form' : 'text',
formData: payload is Map<String, dynamic> ? payload : null,
);
setState(() {
_sessionId = responseMessage.sessionId;
_messages.removeLast();
if(responseMessage.statusCode == 200){
setState(() {
_isOnline = true;
});
}
else{
setState(() {
_isOnline = false;
});
}
if (responseMessage.haivaMessage != null && responseMessage.haivaMessage!['welcomeMessage'] is List<dynamic>) {
List<dynamic> welcomeMessagesList = responseMessage.haivaMessage!['welcomeMessage'] as List<dynamic>;
welcomeMessages.clear(); // Clear previous messages
for (var item in welcomeMessagesList) {
if (item is Map<String, dynamic>) {
WelcomeMessageData messageData = WelcomeMessageData.fromJson(item);
welcomeMessages.add(messageData);
}
}
if (welcomeMessages.isNotEmpty) {
welcomemessagedata = welcomeMessages.first; // Set the first welcome message data
}
}
_messages.add(responseMessage);
_isloading = false;
_sampleQuestions = responseMessage.haivaMessage?['showCustomQuestions']?['sampleQuestions'];
});
} catch (e) {
// print("Error: $e");
setState(() {
_isloading = false; // Ensure loading state is reset on error
});
}
}