Skip to main content

Documentation Index

Fetch the complete documentation index at: https://cometchat-22654f5b-docs-android-v6-beta2.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

FieldValue
Key ClassesMessageListener, MessagesRequest, MessagesRequestBuilder
Key MethodsaddMessageListener(), removeMessageListener(), fetchPrevious(), fetchNext(), getLastDeliveredMessageId(), getUnreadMessageCount()
Listener EventsonTextMessageReceived, onMediaMessageReceived, onCustomMessageReceived, onTypingStarted, onTypingEnded, onMessagesDelivered, onMessagesRead, onMessageEdited, onMessageDeleted, onInteractiveMessageReceived, onMessageReactionAdded, onMessageReactionRemoved
PrerequisitesSDK initialized, user logged in
Receiving messages with CometChat has two parts:
  1. Adding a listener to receive Real-time Messages when your app is running
  2. Calling a method to retrieve Missed Messages when your app was not running
Available via: SDK | REST API | UI Kits

Real-time Messages

In other words, as a recipient, how do I receive messages when my app is running? For every activity or fragment you wish to receive messages in, you need to register the MessageListener using the addMessageListener() method. We suggest adding the listener in the init method of the Stateful class or at the initialization of class where you wish to receive these events in.
class Class_Name  with MessageListener {

//CometChat.addMessageListener("listenerId", this);
  @override
void onTextMessageReceived(TextMessage textMessage) {
  debugPrint("Text message received successfully: $textMessage");
}

@override
void onMediaMessageReceived(MediaMessage mediaMessage) {
	debugPrint("Media message received successfully: $mediaMessage"); 
}

@override
void onCustomMessageReceived(CustomMessage customMessage) {
  debugPrint("Custom message received successfully: $customMessage");  
}

@override
onInteractiveMessageReceived(InteractiveMessage message) {
  
}


}
ParameterDescription
listenerIDAn ID that uniquely identifies that listener. We recommend using the activity or fragment name

MessageListener Events

The MessageListener mixin provides the following event callbacks. All events are verified against the Flutter SDK source.
EventParameter TypeDescription
onTextMessageReceivedTextMessageTriggered when a text message is received
onMediaMessageReceivedMediaMessageTriggered when a media message (image, video, audio, file) is received
onCustomMessageReceivedCustomMessageTriggered when a custom message is received
onTypingStartedTypingIndicatorTriggered when a user starts typing
onTypingEndedTypingIndicatorTriggered when a user stops typing
onMessagesDeliveredMessageReceiptTriggered when messages are delivered to the recipient
onMessagesReadMessageReceiptTriggered when messages are read by the recipient
onMessagesDeliveredToAllMessageReceiptTriggered when messages are delivered to all group members
onMessagesReadByAllMessageReceiptTriggered when messages are read by all group members
onMessageEditedBaseMessageTriggered when a message is edited
onMessageDeletedBaseMessageTriggered when a message is deleted
onTransientMessageReceivedTransientMessageTriggered when a transient (non-persistent) message is received
onInteractiveMessageReceivedInteractiveMessageTriggered when an interactive message is received
onInteractionGoalCompletedInteractionReceiptTriggered when an interaction goal is completed
onMessageReactionAddedReactionEventTriggered when a reaction is added to a message
onMessageReactionRemovedReactionEventTriggered when a reaction is removed from a message
onMessageModeratedBaseMessageTriggered when a message is moderated
onAIAssistantMessageReceivedAIAssistantMessageTriggered when an AI assistant message is received
onAIToolResultReceivedAIToolResultMessageTriggered when an AI tool result is received
onAIToolArgumentsReceivedAIToolArgumentMessageTriggered when AI tool arguments are received
We recommend you remove the listener once the activity or fragment is not in use. Typically, this can be added in the dispose() method.
Always remove message listeners when they’re no longer needed (e.g., in the dispose() method of your StatefulWidget). Failing to remove listeners can cause memory leaks and duplicate event handling.
private String listenerID = "UNIQUE_LISTENER_ID";

CometChat.removeMessageListener(listenerID);
As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices.

Missed Messages

In other words, as a recipient, how do I receive messages that I missed when my app was not running? For most use cases, you will need to add functionality to load missed messages. If you’re building an on-demand or live streaming app, you may choose to skip this and fetch the message history (say, last 100 messages) instead. Using the same MessagesRequest class and the filters provided by the MessagesRequestBuilder class, you can fetch the message that we sent to the logged-in user but were not delivered to them as they were offline. For this, you will require the ID of the last message received. You can either maintain it at your end or use the getLastDeliveredMessageId() method provided by the CometChat class. This ID needs to be passed to the setMessageId() method of the builder class. Now using the fetchNext() method, you can fetch all the messages that were sent to the user when they were offline. Calling the fetchNext() method on the same object repeatedly allows you to fetch all the offline messages for the logged in user in a paginated manner

For a Particular One-on-one Conversation

int limit = 30;
int lastMessageId = -1;
String UID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..uid = UID
      ..limit = limit
      ..messageId = lastMessageId
    ).build();

messageRequest.fetchNext(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID501
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"cometchat-uid-1_user_cometchat-uid-2"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringUID of the receiver"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"user"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."

For a Particular Group Conversation

int limit = 30;
int lastMessageId = -1;
String GUID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..guid = GUID
      ..limit = limit
      ..messageId = lastMessageId
    ).build();

messageRequest.fetchNext(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID502
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver group objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"group_cometchat-uid-1"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringGUID of the receiver group"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"group"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."

Unread Messages

In other words, as a logged-in user, how do I fetch the messages I’ve not read? Using the MessagesRequest class described above, you can fetch the unread messages for the logged-in user. In order to achieve this, you need to set the unread variable in the builder to true so that only the unread messages are fetched.

For a Particular One-on-one Conversation

int limit = 30;
int lastMessageId = -1;
String GUID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..guid = GUID
      ..limit = limit
      ..messageId = lastMessageId
  			..unread = true
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID503
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"cometchat-uid-1_user_cometchat-uid-2"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringUID of the receiver"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered1745554730
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"user"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."

For a Particular Group Conversation

int limit = 30;
int lastMessageId = -1;
String GUID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..guid = GUID
      ..limit = limit
      ..messageId = lastMessageId
      ..unread = true
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID504
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"group_cometchat-uid-1"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringGUID of the receiver group"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered1745554730
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"group"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."
Base MessageThe list of messages received is in the form of objects of BaseMessage class. A BaseMessage can either be an object of the TextMessage, MediaMessage, CustomMessage, Action or Call class. You can use the is operator to check the type of object.

Message History

In other words, as a logged-in user, how do I fetch the message history for a user or a group conversation?

For a Particular One-on-one Conversation

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation between the logged in user and any particular user. For this use case, it is mandatory to set the UID parameter of the builder. This UID is the unique id of the user for which the conversation needs to be fetched.
int limit = 30;
int lastMessageId = -1;
String UID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..uid = UID
      ..limit = limit
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID505
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"cometchat-uid-1_user_cometchat-uid-2"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringUID of the receiver"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"user"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."
Calling the fetchPrevious() method on the same object repeatedly allows you to fetch all the previous messages in a paginated way.

For a Particular Group Conversation

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation for any group provided you have joined the group. For this use case, it is mandatory to set the GUID parameter of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched.
int limit = 30;
String GUID = "cometchat-uid-1";

MessagesRequest messageRequest = (MessagesRequestBuilder()
      ..guid = GUID
      ..limit = limit
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      }); 
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID506
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"group_cometchat-uid-1"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringGUID of the receiver group"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"group"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."
Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation.

Search Messages

In other words, as a logged-in user, how do I search a message? In order to do this, you can use the searchKeyword method. This method accepts string as input. When set, the SDK will fetch messages which match the searchKeyword.
By default, the searchKey is searched only in message text. However, if you enable Conversation & Advanced Search, the searchKey will be searched in message text, file name, mentions & mime type of the file.The Conversation & Advanced Search is only available in Advanced & Custom plans. If you’re already on one of these plans, please enable the Conversation & Advanced Search from CometChat Dashboard (Open your app, navigate to Chats -> Settings -> General Configuration)
FeatureBasic SearchAdvance Search
Text search
File name search
Mentions search
Mime type search

For a Particular One-on-one Conversation

int limit = 30;
int searchKeyword = "search keyboard";
String UID = "cometchat-uid-1";

MessagesRequest  messageRequest = (MessagesRequestBuilder()
      ..uid = UID
      ..limit = limit
      .searchKeyword=searchKeyword
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      });
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID507
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver user objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"cometchat-uid-1_user_cometchat-uid-2"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringUID of the receiver"cometchat-uid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"user"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."

For a Particular Group Conversation

int limit = 30;
int searchKeyword = "search keyboard";
String GUID = "cometchat-guid-1";

MessagesRequest  messageRequest = (MessagesRequestBuilder()
      ..guid = GUID
      ..limit = limit
      .searchKeyword=searchKeyword
    ).build();

messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
          for (BaseMessage message in list) {
            if(message is TextMessage){
              debugPrint("Text message received successfully: "+(message as TextMessage).toString());
            }else if(message is MediaMessage){
              debugPrint("Media message received successfully: "+(message as MediaMessage).toString());
            }
          }
      }, onError: (CometChatException e) {
        debugPrint("Message fetching failed with exception: ${e.message}");
      }); 
On Success — A List<BaseMessage> containing the fetched messages (each item is a BaseMessage object):BaseMessage Object:
ParameterTypeDescriptionSample Value
idnumberUnique message ID508
metadataobjectCustom metadata attached to the message{}
receiverobjectReceiver group objectSee below ↓
editedBystringUID of the user who edited the messagenull
conversationIdstringUnique conversation identifier"group_cometchat-guid-1"
sentAtnumberEpoch timestamp when the message was sent1745554729
receiverUidstringGUID of the receiver group"cometchat-guid-1"
typestringType of the message"text"
readAtnumberEpoch timestamp when the message was read0
deletedBystringUID of the user who deleted the messagenull
deliveredAtnumberEpoch timestamp when the message was delivered0
deletedAtnumberEpoch timestamp when the message was deleted0
replyCountnumberNumber of replies to this message0
senderobjectSender user objectSee below ↓
receiverTypestringType of the receiver"group"
editedAtnumberEpoch timestamp when the message was edited0
parentMessageIdnumberID of the parent message (for threads)0
readByMeAtnumberEpoch timestamp when read by the current user0
categorystringMessage category"message"
deliveredToMeAtnumberEpoch timestamp when delivered to the current user0
updatedAtnumberEpoch timestamp when the message was last updated1745554729
unreadRepliesCountnumberCount of unread replies0
quotedMessageIdnumberID of the quoted messagenull
quotedMessageobjectThe quoted message objectnull

sender Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the sender"cometchat-uid-2"
namestringDisplay name of the sender"George Alan"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
metadataobjectCustom metadata{}
statusstringOnline status"online"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745554700

receiver Object:
ParameterTypeDescriptionSample Value
uidstringUnique identifier of the receiver"cometchat-uid-1"
namestringDisplay name of the receiver"Andrew Joseph"
linkstringProfile linknull
avatarstringAvatar URL"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
metadataobjectCustom metadata{}
statusstringOnline status"offline"
rolestringUser role"default"
statusMessagestringStatus messagenull
tagsarrayUser tags[]
hasBlockedMebooleanWhether this user has blocked the current userfalse
blockedByMebooleanWhether the current user has blocked this userfalse
lastActiveAtnumberEpoch timestamp of last activity1745550000
ParameterTypeDescriptionSample Value
codestringError code identifier"ERR_CHAT_API_FAILURE"
messagestringHuman-readable error message"Failed to fetch the requested data."
detailsstringAdditional technical details"An unexpected error occurred while processing the request."

Unread Messages Count

In other words, as a logged-in user, how do I find out the number of unread messages that I have?

For a Particular One-on-one Conversation

In other words, how do I find out the number of unread messages I have from a particular user? In order to get the unread message count for a particular user (with respect to the logged-in user), you can use the getUnreadMessageCountForUser(). This method has the two variants:
CometChat.getUnreadMessageCountForUser(String UID, Callbacks);
If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true:
CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks);
private String UID = "cometchat-uid-1"

CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener<HashMap<String, Integer>>() {
@Override
  public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
  	// handle success
}

@Override
  public void onError(CometChatException e) {
  	// handle error
}
});
In the onSuccess() callback, you will receive a Map which will contain the UID of the user as the key and the unread message count as the value.

For a Particular Group Conversation

In other words, how do I find out the number of unread messages I have in a single group? In order to get the unread message count for a particular group, you can use the getUnreadMessageCountForGroup(). This method has two variants:
Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid);
If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:
Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid,hideMessagesFromBlockedUsers: hideBlockedUser);   
private String GUID = "cometchat-guid-1"

CometChat.getUnreadMessageCountForGroup(guid: GUID,hideMessagesFromBlockedUsers: hideBlockedUser,
                                      onSuccess: (Map<String, int> map) {
                                      
                                      },
        															onError: (CometChatException e) {
                                      
                                      }); 
In the onSuccess() callback, you will receive a Map which will contain the GUID of the group as the key and the unread message count as the value.

For All One-on-one & Group Conversations

In other words, how do I find out the number of unread messages for every one-on-one and group conversation? In order to get all the unread message counts, you can use the getUnreadMessageCount() method. This method has two variants:
await CometChat.getUnreadMessageCount();
If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:
await CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: true);
CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: hideBlockedUser,
      onSuccess: (Map<String, Map<String, int>> map) {
       
      },onError: (CometChatException e) {
       
      });
In the onSuccess() callback, you will receive a Map having two keys:
  1. user - The value for this key holds another Map that holds the UIDs of users and their corresponding unread message counts.
  2. group - The value for this key holds another Map that holds the GUIDs of groups and their corresponding unread message counts.

For Unread Count for all One-on-one Conversations

In other words, how do I find out the number of unread messages I have for every user? In order to fetch the unread message counts for just the users, you can use the getUnreadMessageCountForAllUsers() method. This method, just like others, has two variants:
await CometChat.getUnreadMessageCountForAllUsers();
If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:
await CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: true);
CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
      onSuccess: (Map<String, int> map) {
       
      },
      onError: (CometChatException e) {
       
      }); 
In the onSuccess() callback, you will receive a Map that will contain the UIDs of users as the key and the unread message counts as the values.

Fetch Unread Count for all Group Conversations

In other words, how do I find out the number of unread messages for every group? In order to fetch the unread message counts for all groups, you can use the getUnreadMessageCountForAllGroups() method. This method has two variants:
await CometChat.getUnreadMessageCountForAllGroups();
If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true:
await CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: true);
CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
      onSuccess: (Map<String, int> map) {
       
      },
      onError: (CometChatException e) {
        
      });
In the onSuccess() callback, you will receive a Map which will contain the GUIDs of the groups as the key and the unread message counts as the values.

Next Steps

Delivery & Read Receipts

Track when messages are delivered and read by recipients

Typing Indicators

Show real-time typing status in conversations

Edit Messages

Allow users to edit previously sent messages

Delete Messages

Remove messages from conversations