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

# Methods

> Reference for CometChat Flutter UI Kit methods including init, login, logout, and message-sending wrappers.

<Accordion title="AI Agent Component Spec">
  | Field                | Value                                                                                                                               |
  | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
  | Package              | `cometchat_chat_uikit`                                                                                                              |
  | Import               | `import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';`                                                                  |
  | Init                 | `CometChatUIKit.init(uiKitSettings: UIKitSettings)`                                                                                 |
  | Login (dev)          | `CometChatUIKit.login(uid)`                                                                                                         |
  | Login (prod)         | `CometChatUIKit.loginWithAuthToken(authToken)`                                                                                      |
  | Other methods        | `CometChatUIKit.logout()`, `CometChatUIKit.getLoggedInUser()`, `CometChatUIKit.createUser(user)`, `CometChatUIKit.updateUser(user)` |
  | Send messages        | `CometChatUIKit.sendTextMessage()`, `CometChatUIKit.sendMediaMessage()`, `CometChatUIKit.sendCustomMessage()`                       |
  | Interactive messages | `CometChatUIKit.sendFormMessage()`, `CometChatUIKit.sendCardMessage()`, `CometChatUIKit.sendSchedulerMessage()`                     |
  | Reactions            | `CometChatUIKit.addReaction()`, `CometChatUIKit.removeReaction()`                                                                   |
  | Note                 | Use these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing                                           |
</Accordion>

## Overview

The UI Kit's core function is to extend the [Chat SDK](/sdk/flutter/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components.

To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real-time and ensure that the UI reflects the most current state of data.

The CometChat UI Kit has thoughtfully encapsulated the critical [Chat SDK](/sdk/flutter/overview) methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers.

## Methods

You can access the methods using the `CometChatUIKit` class. This class provides access to all the public methods exposed by the CometChat UI Kit.

### Init

As a developer, you need to invoke this method every time before you use any other methods provided by the UI Kit.

This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat.

<Warning>
  `CometChatUIKit.init()` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login.
</Warning>

<Warning>
  Auth Key is for development/testing only. In production, generate Auth Tokens on the server using the REST API and pass them to the client via `loginWithAuthToken()`. Never expose Auth Keys in production client code.
</Warning>

<Note>
  Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely.
</Note>

As a developer, the `UIKitSettings` is an important parameter of the `init()` function. It functions as a base settings object, housing properties such as `appId`, `region`, and `authKey`, contained within `UIKitSettings`.

Here's the table format for the properties available in `UIKitSettings`:

| Method                            | Type                         | Description                                                                                                                           |
| --------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **appId**                         | `String`                     | Sets the unique ID for the app, available on dashboard                                                                                |
| **region**                        | `String`                     | Sets the region for the app ('us' or 'eu' or 'in')                                                                                    |
| **authKey**                       | `String`                     | Sets the auth key for the app, available on dashboard                                                                                 |
| **subscriptionType**              | `String`                     | Sets subscription type for tracking the presence of all users                                                                         |
| **roles**                         | `String`                     | Sets subscription type for tracking the presence of users with specified roles                                                        |
| **autoEstablishSocketConnection** | `Boolean`                    | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default |
| **aiFeature**                     | `List<AIExtension>`          | Sets the AI Features that need to be added in UI Kit                                                                                  |
| **extensions**                    | `List<ExtensionsDataSource>` | Sets the list of extension that need to be added in UI Kit                                                                            |
| **callingExtension**              | `ExtensionsDataSource`       | Sets the calling extension configuration                                                                                              |
| **adminHost**                     | `String`                     | Sets a custom admin host URL                                                                                                          |
| **clientHost**                    | `String`                     | Sets a custom client host URL                                                                                                         |
| **dateTimeFormatterCallback**     | `DateTimeFormatterCallback`  | Sets a custom date/time formatter for consistent formatting across all UI components                                                  |

***

The concluding code block:

<Tabs>
  <Tab title="Dart">
    ```dart highlight={3-5} theme={null}
    UIKitSettings uiKitSettings = (UIKitSettingsBuilder()
      ..subscriptionType = CometChatSubscriptionType.allUsers
      ..autoEstablishSocketConnection = true
      ..region = "your_region"    // Replace with your region
      ..appId = "your_appID"      // Replace with your app Id
      ..authKey = "your_authKey"  // Replace with your app auth key
    ).build();

    CometChatUIKit.init(
      uiKitSettings: uiKitSettings,
      onSuccess: (successMessage) async {
        // Initialization successful, proceed to login
      },
      onError: (error) {
        // Handle initialization error
      },
    );
    ```
  </Tab>
</Tabs>

***

### Login using Auth Key

Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#login-using-auth-token) instead of Auth Key.

<Tabs>
  <Tab title="Dart">
    ```dart highlight={1} theme={null}
    String uid = "user1";

    CometChatUIKit.login(
      uid,
      onSuccess: (user) {
        // Login successful, mount your app
      },
      onError: (e) {
        // Handle login error
      },
    );
    ```
  </Tab>
</Tabs>

***

### Login using Auth Token

Production-safe authentication that does not expose the Auth Key in client code.

1. [Create a User](/rest-api/chat-apis) via the CometChat API when the user signs up in your app.

2. [Create an Auth Token](/rest-api/chat-apis) via the CometChat API for the new user and save the token in your database.

3. Load the Auth Token in your client and pass it to the `loginWithAuthToken()` method.

<Tabs>
  <Tab title="Dart">
    ```dart highlight={1} theme={null}
    String authToken = "AUTH_TOKEN";

    CometChatUIKit.loginWithAuthToken(
      authToken,
      onSuccess: (user) {
        // Login successful, mount your app
      },
      onError: (e) {
        // Handle login error
      },
    );
    ```
  </Tab>
</Tabs>

***

### Logout

The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `.logout()` function

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.logout(onSuccess: (s) {
        // TODO("Not yet implemented")
    } , onError: (e) {
        // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

### Create User

As a developer, you can dynamically create users on CometChat using the `.createUser()` function. This can be extremely useful for situations where users are registered or authenticated by your system and then need to be created on CometChat.

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.createUser(userObject, onSuccess: (user) {
      // TODO("Not yet implemented")
    }, onError: (e) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

### Update User

As a developer, you can update user details using the `.updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed.

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.updateUser(userObject, onSuccess: (user) {
      // TODO("Not yet implemented")
    }, onError: (e) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

### Get Logged In User

You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `.getLoggedInUser()` function.

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.getLoggedInUser(onSuccess: (user) {
      // TODO("Not yet implemented")
    }, onError: (e) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

### DateFormatter

By providing a custom implementation of the DateTimeFormatterCallback, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application.

Each method in the interface corresponds to a specific case:

* time(int? timestamp) → Custom full timestamp format
* today(int? timestamp) → Called when a message is from today
* yesterday(int? timestamp) → Called for yesterday’s messages
* lastWeek(int? timestamp) → Messages from the past week
* otherDays(int? timestamp) → Older messages
* minute(int? timestamp) / hour(int? timestamp) → Exact time unit
* minutes(int? diffInMinutesFromNow, int? timestamp) → e.g., "5 minutes ago"
* hours(int? diffInHourFromNow, int? timestamp) → e.g., "2 hours ago"

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';
    import 'package:intl/intl.dart';

    /// Custom implementation of DateTimeFormatterCallback
    /// to format time and date display in the CometChat UI.
    class DateFormatter extends DateTimeFormatterCallback {
      /// Formatter for displaying full time like "10:45 PM"
      final DateFormat fullTimeFormatter = DateFormat('hh:mm a');

      /// Formatter for displaying date like "23 Jun 2025"
      final DateFormat dateFormatter = DateFormat('dd MMM yyyy');

      /// Returns formatted time (e.g., "10:45 PM") for a given timestamp.
      @override
      String? time(int? timestamp) {
        if (timestamp == null) return null;
        return fullTimeFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp));
      }

      /// Returns a static label for messages sent today.
      @override
      String? today(int? timestamp) {
        return "Today";
      }

      /// Returns a static label for messages sent yesterday.
      @override
      String? yesterday(int? timestamp) {
        return "Yesterday";
      }

      /// Returns a static label for messages sent last week.
      @override
      String? lastWeek(int? timestamp) {
        return "Last Week";
      }

      /// Returns formatted date (e.g., "23 Jun 2025") for other days.
      @override
      String? otherDays(int? timestamp) {
        if (timestamp == null) return null;
        return dateFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp));
      }

      /// Returns relative time in minutes (e.g., "5 mins ago").
      @override
      String? minutes(int? diffInMinutesFromNow, int? timestamp) {
        if (diffInMinutesFromNow == null) return null;
        return "$diffInMinutesFromNow mins ago";
      }

      /// Returns relative time in hours (e.g., "2 hrs ago").
      @override
      String? hours(int? diffInHourFromNow, int? timestamp) {
        if (diffInHourFromNow == null) return null;
        return "$diffInHourFromNow hrs ago";
      }

      /// (Optional) Returns formatted hour (e.g., "3 PM") if used by SDK.
      @override
      String? hour(int? timestamp) {
        if (timestamp == null) return null;
        return DateFormat('h a').format(DateTime.fromMillisecondsSinceEpoch(timestamp));
      }

      /// (Optional) Returns formatted minute value (e.g., "09") if used by SDK.
      @override
      String? minute(int? timestamp) {
        if (timestamp == null) return null;
        return DateFormat('mm').format(DateTime.fromMillisecondsSinceEpoch(timestamp));
      }
    }

    // Build CometChat UIKit settings
    UIKitSettings uiKitSettings = (UIKitSettingsBuilder()
          // Set subscription type (e.g., receive messages from all users)
          ..subscriptionType = CometChatSubscriptionType.allUsers

          // Set your CometChat region
          ..region = AppCredentials.region

          // Automatically connect to socket server
          ..autoEstablishSocketConnection = true

          // CometChat App ID and Auth Key
          ..appId = AppCredentials.appId
          ..authKey = AppCredentials.authKey

          // Enable calling feature
          ..callingExtension = CometChatCallingExtension()

          // Load default chat extensions (e.g., polls, stickers, reactions)
          ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions()

          // Load default AI features (e.g., Smart Replies, Sentiment Analysis)
          ..aiFeature = CometChatUIKitChatAIFeatures.getDefaultAiFeatures()

          // Inject the custom date and time formatter
          ..dateTimeFormatterCallback = DateFormatter()
        )
        .build();

    // Initialize CometChat UIKit with the configured settings
    CometChatUIKit.init(
      uiKitSettings: uiKitSettings,
      
      // Callback when initialization is successful
      onSuccess: (successMessage) async {
        // On success 
      },
      
      // Callback when initialization fails
      onError: (e) {
        shouldGoToHomeScreen.value = false;
        if (kDebugMode) {
          debugPrint("Initialization failed with error: ${e.details}");
        }
      },
    );


    ```
  </Tab>
</Tabs>

***

### Base Message

#### Text Message

Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object.

<Tabs>
  <Tab title="1:1 Chat">
    ```dart highlight={1-2} theme={null}
    String receiverID = "UID";
    String messageText = "Hello world!";

    TextMessage textMessage = TextMessage(
      text: messageText,
      receiverUid: receiverID,
      receiverType: ReceiverType.user,
    );

    CometChatUIKit.sendTextMessage(
      textMessage,
      onSuccess: (message) {
        // Message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>

  <Tab title="Group Chat">
    ```dart highlight={1-2} theme={null}
    String receiverID = "GUID";
    String messageText = "Hello world!";

    TextMessage textMessage = TextMessage(
      text: messageText,
      receiverUid: receiverID,
      receiverType: ReceiverType.group,
    );

    CometChatUIKit.sendTextMessage(
      textMessage,
      onSuccess: (message) {
        // Message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>
</Tabs>

***

#### Media Message

Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object.

<Tabs>
  <Tab title="1:1 Chat">
    ```dart highlight={1-2} theme={null}
    String receiverID = "UID";
    String filePath = "/path/to/file";

    MediaMessage mediaMessage = MediaMessage(
      receiverUid: receiverID,
      receiverType: ReceiverType.user,
      type: MessageType.file,
      file: filePath,
    );

    CometChatUIKit.sendMediaMessage(
      mediaMessage,
      onSuccess: (message) {
        // Media message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>

  <Tab title="Group Chat">
    ```dart highlight={1-2} theme={null}
    String receiverID = "GUID";
    String filePath = "/path/to/file";

    MediaMessage mediaMessage = MediaMessage(
      receiverUid: receiverID,
      receiverType: ReceiverType.group,
      type: MessageType.file,
      file: filePath,
    );

    CometChatUIKit.sendMediaMessage(
      mediaMessage,
      onSuccess: (message) {
        // Media message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>
</Tabs>

***

#### Custom Message

Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object.

<Tabs>
  <Tab title="1:1 Chat">
    ```dart highlight={1,3-4} theme={null}
    String receiverID = "UID";
    Map<String, dynamic> customData = {
      "latitude": "50.6192171633316",
      "longitude": "-72.68182268750002",
    };
    String customType = "location";

    CustomMessage customMessage = CustomMessage(
      receiverUid: receiverID,
      receiverType: ReceiverType.user,
      type: customType,
      customData: customData,
    );

    CometChatUIKit.sendCustomMessage(
      customMessage,
      onSuccess: (message) {
        // Custom message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>

  <Tab title="Group Chat">
    ```dart highlight={1,3-4} theme={null}
    String receiverID = "GUID";
    Map<String, dynamic> customData = {
      "latitude": "50.6192171633316",
      "longitude": "-72.68182268750002",
    };
    String customType = "location";

    CustomMessage customMessage = CustomMessage(
      receiverUid: receiverID,
      receiverType: ReceiverType.group,
      type: customType,
      customData: customData,
    );

    CometChatUIKit.sendCustomMessage(
      customMessage,
      onSuccess: (message) {
        // Custom message sent successfully
      },
      onError: (e) {
        // Handle error
      },
    );
    ```
  </Tab>
</Tabs>

***

### Interactive Message

#### Form Message

As a developer, if you need to send a Form message to a single user or a group, you'll need to utilize the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that messages

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.sendFormMessage(formMessageObject, onSuccess: (p0) {
      // TODO("Not yet implemented")
    }, onError: (p0) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

#### Card Message

As a developer, if you need to send a Card message to a single user or a group, you'll need to utilize the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the messages

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.sendCardMessage(cardMessageObject, onSuccess: (p0) {
      // TODO("Not yet implemented")
    }, onError: (p0) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

#### Scheduler Message

As a developer, if you need to send a Scheduler message to a single user or a group, you'll need to utilize the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.sendSchedulerMessage(schedulerMessageObject, onSuccess: (p0) {
      // TODO("Not yet implemented")
    }, onError: (p0) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

#### Custom Interactive Message

As a developer, if you need to send a Interactive message to a single user or a group, you'll need to utilize the `sendCustomInteractiveMessage()` function. This function requires a `InteractiveMessage` object as its argument, which contains the necessary information to create a custom interactive message bubble for the messages

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: (p0) {
      // TODO("Not yet implemented")
    }, onError: (p0) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

### Reactions

#### Add Reaction

As a developer, you can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly.

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.addReaction(messageId, "👍", onSuccess: (message) {
      // TODO("Not yet implemented")
    }, onError: (e) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***

#### Remove Reaction

As a developer, you can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly.

<Tabs>
  <Tab title="Dart">
    ```dart theme={null}
    CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) {
      // TODO("Not yet implemented")
    }, onError: (e) {
      // TODO("Not yet implemented")
    });
    ```
  </Tab>
</Tabs>

***
