> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-llms-scoped-indexes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Threaded Messages

> Send, receive, and fetch threaded messages using the CometChat Flutter SDK.

<Accordion title="AI Integration Quick Reference">
  | Field | Value |
  | - | - |
  | Key Classes | `TextMessage`, `MediaMessage`, `CustomMessage`, `MessagesRequest`, `MessagesRequestBuilder` |
  | Key Methods | `CometChat.sendMessage()`, `CometChat.sendMediaMessage()`, `CometChat.sendCustomMessage()`, `MessagesRequest.fetchPrevious()` |
  | Key Properties | `parentMessageId`, `hideReplies` |
  | Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` |
  | Prerequisites | SDK initialized, user logged in |

  ```dart theme={null}
  // Send a message in a thread (attach to parent message)
  TextMessage textMessage = TextMessage(
    text: "Reply in thread",
    receiverUid: "UID",
    receiverType: CometChatReceiverType.user,
    type: CometChatMessageType.text,
  );
  textMessage.parentMessageId = 103; // Parent message ID
  CometChat.sendMessage(textMessage, onSuccess: (msg) {}, onError: (e) {});

  // Fetch messages from a thread
  MessagesRequest messageRequest = (MessagesRequestBuilder()
    ..uid = "UID"
    ..parentMessageId = 103
    ..limit = 50).build();
  messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {}, onError: (e) {});

  // Exclude threaded messages from main conversation
  MessagesRequest request = (MessagesRequestBuilder()
    ..uid = "UID"
    ..hideReplies = true
    ..limit = 50).build();
  ```
</Accordion>

Threaded messages (or threads) are messages started from a particular parent message. Each thread is attached to a parent message.

<Note>
  **Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview)
</Note>

## Send Message in a Thread

As mentioned in the [Send a Message](/sdk/flutter/v4/send-message) section, you can send a message to a User or a Group by mentioning the receiver (uid/guid) and `receiverType`(user/group).

A message can be categorized as:

1. Text Message
2. Media Message
3. Custom Message
4. Interactive Message

Set the `parentMessageId` on the message object to indicate which thread the message belongs to. The id specified in the `parentMessageId` parameter maps the message sent to the particular thread. Any message type — [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage), or Interactive Message — can be sent in a thread.

<Tabs>
  <Tab title="User">
    ```dart theme={null}
    String receiverID = "UID";
    String messagesText = "Hello";
    String receiverType = CometChatConversationType.user;
    String type = CometChatMessageType.text;

    TextMessage textMessage = TextMessage(
                            text: messagesText,
                            receiverUid: receiverID,
                            receiverType: receiverType,
                            type: type);
    textMessage.parentMessageId = 103;

    CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) {
      debugPrint("Message sent successfully:  $message");
    }, onError: (CometChatException e) {
      debugPrint("Message sending failed with exception:  ${e.message}");
    });
    ```
  </Tab>

  <Tab title="Group">
    ```dart theme={null}
    String receiverID = "GUID";
    String messagesText = "Hello";
    String receiverType = CometChatConversationType.group;
    String type = CometChatMessageType.text;

    TextMessage textMessage = TextMessage(
                            text: messagesText,
                            receiverUid: receiverID,
                            receiverType: receiverType,
                            type: type);
    textMessage.parentMessageId = 103;

    CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) {
      debugPrint("Message sent successfully:  $message");
    }, onError: (CometChatException e) {
      debugPrint("Message sending failed with exception:  ${e.message}");
    });
    ```
  </Tab>
</Tabs>

`TextMessage` Parameters:

| Parameter | Type | Description | Required |
| - | - | - | - |
| `text` | `String` | The text content of the message | Yes |
| `receiverUid` | `String` | The `UID` of the user or `GUID` of the group to send the message to | Yes |
| `receiverType` | `String` | The type of the receiver — `CometChatConversationType.user` or `CometChatConversationType.group` | Yes |
| `type` | `String` | The type of the message — `CometChatMessageType.text` | Yes |
| `parentMessageId` | `int` | The ID of the parent message to send this message as a thread reply | Yes (for threads) |

<Accordion title="Response">
  **On Success** — A `TextMessage` object containing all details of the sent threaded message:

  <span id="send-thread-message-object" style={{scrollMarginTop: '100px'}} />

  **TextMessage Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `id` | number | Unique message ID | `601` |
  | `metadata` | object | Custom metadata attached to the message | `{}` |
  | `receiver` | object | Receiver user object | [See below ↓](#send-thread-receiver-object) |
  | `editedBy` | string | UID of the user who edited the message | `null` |
  | `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` |
  | `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` |
  | `receiverUid` | string | UID of the receiver | `"cometchat-uid-2"` |
  | `type` | string | Type of the message | `"text"` |
  | `readAt` | number | Epoch timestamp when the message was read | `0` |
  | `deletedBy` | string | UID of the user who deleted the message | `null` |
  | `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` |
  | `deletedAt` | number | Epoch timestamp when the message was deleted | `0` |
  | `replyCount` | number | Number of replies to this message | `0` |
  | `sender` | object | Sender user object | [See below ↓](#send-thread-sender-object) |
  | `receiverType` | string | Type of the receiver | `"user"` |
  | `editedAt` | number | Epoch timestamp when the message was edited | `0` |
  | `parentMessageId` | number | ID of the parent message (for threads) | `103` |
  | `readByMeAt` | number | Epoch timestamp when read by the current user | `0` |
  | `category` | string | Message category | `"message"` |
  | `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` |
  | `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` |
  | `text` | string | The text content of the message | `"Hello"` |
  | `tags` | array | List of tags associated with the message | `[]` |
  | `unreadRepliesCount` | number | Count of unread replies | `0` |
  | `mentionedUsers` | array | List of mentioned users | `[]` |
  | `hasMentionedMe` | boolean | Whether the current user is mentioned | `false` |
  | `reactions` | array | List of reactions on the message | `[]` |
  | `moderationStatus` | string | Moderation status of the message | `null` |
  | `quotedMessageId` | number | ID of the quoted message | `null` |

  ***

  <span id="send-thread-sender-object" style={{scrollMarginTop: '100px'}} />

  **`sender` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the sender | `"cometchat-uid-1"` |
  | `name` | string | Display name of the sender | `"Andrew Joseph"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"online"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` |

  ***

  <span id="send-thread-receiver-object" style={{scrollMarginTop: '100px'}} />

  **`receiver` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` |
  | `name` | string | Display name of the receiver | `"George Alan"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"offline"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` |
</Accordion>

<Accordion title="Error">
  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` |
  | `message` | string | Human-readable error message | `"Failed to send the message."` |
  | `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` |
</Accordion>

The above snippet shows how a message with the text "Hello" can be sent in the thread with `parentMessageId` 103.

Similarly, using the `parentMessageId` parameter, Media and Custom Messages can be sent in threads too.

### Receiving Real-Time Messages

The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/flutter/v4/receive-messages) section. Use the `MessageListener` class to listen for incoming thread messages. Check if the received message belongs to the active thread using the `parentMessageId` field.

<Warning>
  Always remove message listeners when they're no longer needed (e.g., in the `dispose()` method). Failing to remove listeners can cause memory leaks and duplicate event handling.

  ```dart theme={null}
  CometChat.removeMessageListener("listenerId");
  ```
</Warning>

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    class Class_Name  with MessageListener {
    	int activeParentMessageId= 103;
    //CometChat.addMessageListener("listenerId", this);
    	@override
    void onTextMessageReceived(TextMessage textMessage) {
       if(textMessage.parentMessageId == activeParentMessageId){
          debugPrint("Text message received successfully: $textMessage");
      }

    }

    @override
    void onMediaMessageReceived(MediaMessage mediaMessage) {
      if(mediaMessage.parentMessageId== activeParentMessageId){
      	debugPrint("Media message received successfully: $mediaMessage");
      }
    }

    @override
    void onCustomMessageReceived(CustomMessage customMessage) {
      if(customMessage.parentMessageId== activeParentMessageId){
        debugPrint("Custom message received successfully: $customMessage");
      }
    }
    }
    ```
  </Tab>
</Tabs>

### Fetch all the messages for any particular thread.

Use `MessagesRequestBuilder` with `parentMessageId` to fetch messages belonging to a specific thread. Call `fetchPrevious()` to get messages (max 100 per request), returned as [`BaseMessage`](/sdk/reference/messages#basemessage) objects. Call `fetchPrevious()` again on the same object to get the next set.

`MessagesRequestBuilder` Parameters:

| Parameter | Type | Description | Required |
| - | - | - | - |
| `uid` | `String` | The `UID` of the user whose conversation thread messages are to be fetched | Yes (for user threads) |
| `guid` | `String` | The `GUID` of the group whose conversation thread messages are to be fetched | Yes (for group threads) |
| `parentMessageId` | `int` | The ID of the parent message whose thread messages are to be fetched | Yes |
| `limit` | `int` | Number of messages to fetch in a single request (max 100) | No |

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    String UID = "cometchat-uid-1";

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

    messageRequest.fetchPrevious(onSuccess: (List<BaseMessage> list) {
             debugPrint("Message fetching Successful");
          }, onError: (CometChatException e) {
            debugPrint("Message fetching failed with exception: ${e.message}");
          });
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  **On Success** — A `List<BaseMessage>` containing the fetched thread messages (each item is a BaseMessage object):

  <span id="fetch-thread-message-object" style={{scrollMarginTop: '100px'}} />

  **BaseMessage Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `id` | number | Unique message ID | `602` |
  | `metadata` | object | Custom metadata attached to the message | `{}` |
  | `receiver` | object | Receiver user object | [See below ↓](#fetch-thread-receiver-object) |
  | `editedBy` | string | UID of the user who edited the message | `null` |
  | `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` |
  | `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` |
  | `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` |
  | `type` | string | Type of the message | `"text"` |
  | `readAt` | number | Epoch timestamp when the message was read | `0` |
  | `deletedBy` | string | UID of the user who deleted the message | `null` |
  | `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` |
  | `deletedAt` | number | Epoch timestamp when the message was deleted | `0` |
  | `replyCount` | number | Number of replies to this message | `0` |
  | `sender` | object | Sender user object | [See below ↓](#fetch-thread-sender-object) |
  | `receiverType` | string | Type of the receiver | `"user"` |
  | `editedAt` | number | Epoch timestamp when the message was edited | `0` |
  | `parentMessageId` | number | ID of the parent message (for threads) | `103` |
  | `readByMeAt` | number | Epoch timestamp when read by the current user | `0` |
  | `category` | string | Message category | `"message"` |
  | `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` |
  | `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` |
  | `unreadRepliesCount` | number | Count of unread replies | `0` |
  | `quotedMessageId` | number | ID of the quoted message | `null` |
  | `quotedMessage` | object | The quoted message object | `null` |

  ***

  <span id="fetch-thread-sender-object" style={{scrollMarginTop: '100px'}} />

  **`sender` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` |
  | `name` | string | Display name of the sender | `"George Alan"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"online"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` |

  ***

  <span id="fetch-thread-receiver-object" style={{scrollMarginTop: '100px'}} />

  **`receiver` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` |
  | `name` | string | Display name of the receiver | `"Andrew Joseph"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"offline"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` |
</Accordion>

<Accordion title="Error">
  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` |
  | `message` | string | Human-readable error message | `"Failed to fetch the requested data."` |
  | `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` |
</Accordion>

## Avoid Threaded Messages in User/Group Conversations

While fetching messages for normal user/group conversations using the `MessagesRequest`, the threaded messages by default will be a part of the list of messages received. Use `hideReplies = true` on the `MessagesRequestBuilder` to exclude threaded messages from the list.

<Tabs>
  <Tab title="User">
    ```dart theme={null}
    String UID = "cometchat-uid-1";

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

    messageRequest.fetchNext(onSuccess: (List<BaseMessage> list) {
             debugPrint("Message fetching Successful");
          }, onError: (CometChatException e) {
            debugPrint("Message fetching failed with exception: ${e.message}");
          });
    ```
  </Tab>

  <Tab title="Group">
    ```dart theme={null}
    String GUID = "cometchat-guid-1";

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

    messageRequest.fetchNext(onSuccess: (List<BaseMessage> list) {
             debugPrint("Message fetching Successful");
          }, onError: (CometChatException e) {
            debugPrint("Message fetching failed with exception: ${e.message}");
          });
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  **On Success** — A `List<BaseMessage>` containing the fetched messages excluding threaded replies (each item is a BaseMessage object):

  <span id="fetch-exclude-thread-message-object" style={{scrollMarginTop: '100px'}} />

  **BaseMessage Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `id` | number | Unique message ID | `603` |
  | `metadata` | object | Custom metadata attached to the message | `{}` |
  | `receiver` | object | Receiver user object | [See below ↓](#fetch-exclude-thread-receiver-object) |
  | `editedBy` | string | UID of the user who edited the message | `null` |
  | `conversationId` | string | Unique conversation identifier | `"cometchat-uid-1_user_cometchat-uid-2"` |
  | `sentAt` | number | Epoch timestamp when the message was sent | `1745554729` |
  | `receiverUid` | string | UID of the receiver | `"cometchat-uid-1"` |
  | `type` | string | Type of the message | `"text"` |
  | `readAt` | number | Epoch timestamp when the message was read | `0` |
  | `deletedBy` | string | UID of the user who deleted the message | `null` |
  | `deliveredAt` | number | Epoch timestamp when the message was delivered | `0` |
  | `deletedAt` | number | Epoch timestamp when the message was deleted | `0` |
  | `replyCount` | number | Number of replies to this message | `0` |
  | `sender` | object | Sender user object | [See below ↓](#fetch-exclude-thread-sender-object) |
  | `receiverType` | string | Type of the receiver | `"user"` |
  | `editedAt` | number | Epoch timestamp when the message was edited | `0` |
  | `parentMessageId` | number | ID of the parent message (for threads) | `0` |
  | `readByMeAt` | number | Epoch timestamp when read by the current user | `0` |
  | `category` | string | Message category | `"message"` |
  | `deliveredToMeAt` | number | Epoch timestamp when delivered to the current user | `0` |
  | `updatedAt` | number | Epoch timestamp when the message was last updated | `1745554729` |
  | `unreadRepliesCount` | number | Count of unread replies | `0` |
  | `quotedMessageId` | number | ID of the quoted message | `null` |
  | `quotedMessage` | object | The quoted message object | `null` |

  ***

  <span id="fetch-exclude-thread-sender-object" style={{scrollMarginTop: '100px'}} />

  **`sender` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` |
  | `name` | string | Display name of the sender | `"George Alan"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"online"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` |

  ***

  <span id="fetch-exclude-thread-receiver-object" style={{scrollMarginTop: '100px'}} />

  **`receiver` Object:**

  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `uid` | string | Unique identifier of the receiver | `"cometchat-uid-1"` |
  | `name` | string | Display name of the receiver | `"Andrew Joseph"` |
  | `link` | string | Profile link | `null` |
  | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` |
  | `metadata` | object | Custom metadata | `{}` |
  | `status` | string | Online status | `"offline"` |
  | `role` | string | User role | `"default"` |
  | `statusMessage` | string | Status message | `null` |
  | `tags` | array | User tags | `[]` |
  | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
  | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
  | `lastActiveAt` | number | Epoch timestamp of last activity | `1745550000` |
</Accordion>

<Accordion title="Error">
  | Parameter | Type | Description | Sample Value |
  | - | - | - | - |
  | `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` |
  | `message` | string | Human-readable error message | `"Failed to fetch the requested data."` |
  | `details` | string | Additional technical details | `"An unexpected error occurred while processing the request."` |
</Accordion>

The response is a list of `BaseMessage` objects, excluding any messages that are replies within a thread. Only top-level messages in the conversation are returned.

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Send Messages" icon="paper-plane" href="/sdk/flutter/send-message">
    Learn how to send text, media, and custom messages
  </Card>

  <Card title="Receive Messages" icon="inbox" href="/sdk/flutter/receive-messages">
    Handle incoming messages in real-time
  </Card>

  <Card title="Reactions" icon="face-smile" href="/sdk/flutter/reactions">
    Add emoji reactions to messages
  </Card>

  <Card title="Message Structure" icon="sitemap" href="/sdk/flutter/v4/message-structure-and-hierarchy">
    Understand message types and hierarchy
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.