# Manage local conversations (/en/realtime-media/im/build/build-core-messaging/messages/manage-messages/flutter)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

In chat apps, a conversation is composed of all the messages in a peer-to-peer chat, chat group, or chatroom. The Chat SDK supports managing messages by conversations, including retrieving and managing unread messages, deleting the historical messages on the local device, and searching historical messages.

    This page introduces how to use the Chat SDK to implement these functionalities.

    ## Understand the tech [#understand-the-tech-3]

    SQLCipher is used to encrypt the database that stores local messages. The Chat SDK uses `ChatManager` and `ChatConversation` to manage local messages. The following are the core methods:

    * `ChatManager.loadAllConversations`: Loads the conversation list on the local device.
    * `ChatManager.deleteAllMessageAndConversation`: Clears the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms. You can also choose whether to clear the chat history on the server in one direction.
    * `ChatManage.deleteConversation`: Deletes the specified conversation.
    * `ChatManager.deleteMessage`: Deletes a message sent or received in a local conversation.
    * `ChatManager.deleteAllMessages`: Deletes all messages sent and received in a local conversation.
    * `ChatManager.deleteMessagesWithTs`: Deletes messages sent and received in a certain period in a local conversation.
    * `ChatConversation.getUnreadMessageCount`: Retrieves the count of unread messages in the specified conversation.
    * `ChatManager.getUnreadMessageCount`: Retrieves the count of all unread messages.
    * `ChatManager.pinConversation`: Pins a conversation.
    * `ChatManager.fetchPinnedConversations`: Retrieves the pinned conversations from the server with pagination.
    * `ChatManager.deleteRemoteConversation`: Deletes the conversation and historical messages from the server.
    * `ChatManager.searchMsgFromDB`: Searches for messages from the local database.
    * `ChatManager#loadMessagesWithKeyword`: Searches for messages in all conversations based on the search scope.
    * `ChatManager#loadMessagesWithKeyword`: Searches for messages in a single conversation based on the search scope.
    * `conversation#loadMessagesWithKeyword`: Inserts messages in the specified conversation.

    ## Prerequisites [#prerequisites-3]

    Before proceeding, ensure that you meet the following requirements:

    * You have integrated the Chat SDK, initialized the SDK and implemented the functionality of registering accounts and login. For details, see [Chat SDK quickstart](../../../../get-started-sdk).
    * You understand the API call frequency limits as described in [Limitations](../../limitations).

    ## Implementation [#implementation-3]

    This section shows how to implement managing messages.

    ### Retrieve conversations [#retrieve-conversations-3]

    Call `loadAllConversations` to retrieve all the conversations on the local device:

    ```dart
    try {
      List lists =
          await ChatClient.getInstance.chatManager.loadAllConversations();
      // Loading conversations succeeds
    } on ChatError catch (e) {
      // recall failed, code: e.code, reason: e.description
    }
    ```

    ### Retrieve messages in the specified conversation [#retrieve-messages-in-the-specified-conversation-2]

    You can retrieve the messages in the specified conversation from the local database by specifying the conversation ID and chat type:

    ```dart
    // Retrieves the conversation ID
    ChatConversation? conversation = await ChatClient.getInstance.chatManager
        .getConversation(conversationId, type: ChatConversationType.Chat);
    // Only one message is loaded during SDK initialization. Call loadMessages to retrieve more messages.
    List messages = await conversation!.loadMessages(
      startMsgId: startMsgId,
      loadCount: count,
      direction: ChatSearchDirection.Up,
    );
    ```

    ### Retrieve the count of unread messages in the specified conversation [#retrieve-the-count-of-unread-messages-in-the-specified-conversation-2]

    Refer to the following code example to retrieve the count of unread messages:

    ```dart
    int unreadCount = await conversation.unreadCount();
    ```

    ### Retrieve the count of unread messages in all conversations [#retrieve-the-count-of-unread-messages-in-all-conversations-2]

    Refer to the following code example to retrieve the count of all unread messages:

    ```dart
    // Gets the count of all unread messages
    int unreadCount =
            await ChatClient.getInstance.chatManager.getUnreadMessageCount();
    ```

    ### Mark unread messages as read [#mark-unread-messages-as-read-2]

    Refer to the following code example to mark the specified messages as read:

    ```dart
    await conversation.markMessageAsRead(message.msgId);
    ```

    You can also mark all unread messages of the specified conversation as read:

    ```dart
    await conversation.markAllMessagesAsRead();
    ```

    To mark all the conversations as read:

    ```dart
    await ChatClient.getInstance.chatManager.markAllConversationsAsRead();
    ```

    ### Clear chat history [#clear-chat-history-3]

    To clear the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms, you can call the `ChatManager#deleteAllMessageAndConversation` method. Additionally, you can choose whether to clear the chat history on the server. Note that clearing the chat history on the server means that you will not be able to retrieve conversations and messages from the server, although other users will not be affected.

    ```dart
    try {
      await ChatClient.getInstance.chatManager.deleteAllMessageAndConversation(clearServerData: true);
    } on ChatError catch (e) {
      debugPrint('deleteAllMessageAndConversation error: ${e.code} ${e.description}');
    }
    ```

    ### Delete all messages in a local conversation [#delete-all-messages-in-a-local-conversation-2]

    You can delete all messages in a local conversation:

    ```dart
    Conversation? conversation = await ChatClient.getInstance.chatManager
        .getConversation(conversationId);
    await conversation?.deleteAllMessages();
    ```

    ### Delete messages in a local conversation by time period [#delete-messages-in-a-local-conversation-by-time-period-2]

    You can delete messages sent and received in a certain period in a local conversation.

    ```dart
    Conversation? conversation = await ChatClient.getInstance.chatManager
        .getConversation(conversationId);
    await conversation?.deleteMessagesWithTs(startTs, endTs);
    ```

    ### Delete a specific message [#delete-a-specific-message-2]

    You can delete a specific message from a local conversation. The sample code is as follows:

    ```dart
    Conversation? conversation = await ChatClient.getInstance.chatManager
        .getConversation(conversationId);
    await conversation?.deleteMessage(messageId);
    ```

    ### Search for messages using keywords [#search-for-messages-using-keywords-2]

    Search methods provided on this page can be used to search the local database for all types of messages except command messages, because command messages are not stored in the local database.

    Call `SearchMsgFromDB` to search for messages by keywords, timestamp, and message sender:

    ```dart
    // The keyword for searchING
    String keywords = 'key';
    // The Unix timestamp (ms) of the message from which to start searching
    int timestamp = 1653971593000;
    // The maximum message count for searching
    int maxCount = 10;
    // The message sender
    String from = 'tom';
    // The search direction
    EMSearchDirection direction = EMSearchDirection.Up;
    List list =
        await ChatClient.getInstance.chatManager.searchMsgFromDB(
      keywords,
      timeStamp: timestamp,
      maxCount: maxCount,
      from: from,
      direction: direction,
    );
    ```

    ### Search for messages in all conversations based on search scope [#search-for-messages-in-all-conversations-based-on-search-scope-2]

    You can call the `ChatManager#loadMessagesWithKeyword` method to search in all conversations based on the search scope. This means that, in addition to setting the keywords, message timestamps, number of messages, sender, and search direction, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```dart
    try {
      List msgs = await ChatClient.getInstance.chatManager.loadMessagesWithKeyword(
        'keyword',
        searchScope: MessageSearchScope.All,
      );
    } on ChatError catch (e) {
      debugPrint('loadMessagesWithKeyword error: ${e.code} ${e.description}');
    }
    ```

    ### Search for messages in the current conversation based on search scope [#search-for-messages-in-the-current-conversation-based-on-search-scope-2]

    You can call the `conversation#loadMessagesWithKeyword` method to search for messages in the current conversation based on the search scope. This means that, in addition to setting keywords, message timestamps, number of messages, sender, direction, and other parameters, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```dart
     try {
      ChatConversation? conversation = await ChatClient.getInstance.chatManager.getConversation(targetId);
      List? msgs = await conversation?.loadMessagesWithKeyword(
        'keyword',
        searchScope: MessageSearchScope.All,
      );
    } on ChatError catch (e) {
      debugPrint('loadMessagesWithKeyword error: ${e.code} ${e.description}');
    }
    ```

    ### Import messages [#import-messages-2]

    To import multiple messages to the specified conversation, create a `ChatMessage` object and call `importMessages`.

    ```dart
    // Construct a message object and pass it in messages
    await ChatClient.getInstance.chatManager.importMessages(messages);
    ```

    ## Next steps [#next-steps-3]

    After implementing managing messages, you can refer to the following documents to add more messaging functionalities to your app:

    * [Retrieve conversations and messages from the server](./retrieve-messages)
    * [Message receipts](./message-receipts)

    
  
      
  
      
  
      
  
