Skip to main content
FieldValue
Packagecometchat_chat_uikit
Importimport 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';
InitCometChatUIKit.init(uiKitSettings: UIKitSettings)
Login (dev)CometChatUIKit.login(uid)
Login (prod)CometChatUIKit.loginWithAuthToken(authToken)
Other methodsCometChatUIKit.logout(), CometChatUIKit.getLoggedInUser(), CometChatUIKit.createUser(user), CometChatUIKit.updateUser(user)
Send messagesCometChatUIKit.sendTextMessage(), CometChatUIKit.sendMediaMessage(), CometChatUIKit.sendCustomMessage()
Interactive messagesCometChatUIKit.sendFormMessage(), CometChatUIKit.sendCardMessage(), CometChatUIKit.sendSchedulerMessage()
ReactionsCometChatUIKit.addReaction(), CometChatUIKit.removeReaction()
NoteUse these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing

Overview

The UI Kit’s core function is to extend the Chat SDK, 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 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.
CometChatUIKit.init() must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login.
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.
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 to log in securely.
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:
MethodTypeDescription
appIdStringSets the unique ID for the app, available on dashboard
regionStringSets the region for the app (‘us’ or ‘eu’ or ‘in’)
authKeyStringSets the auth key for the app, available on dashboard
subscriptionTypeStringSets subscription type for tracking the presence of all users
rolesStringSets subscription type for tracking the presence of users with specified roles
autoEstablishSocketConnectionBooleanConfigures if web socket connections will established automatically on app initialization or be done manually, set to true by default
aiFeatureList<AIExtension>Sets the AI Features that need to be added in UI Kit
extensionsList<ExtensionsDataSource>Sets the list of extension that need to be added in UI Kit
callingExtensionExtensionsDataSourceSets the calling extension configuration
adminHostStringSets a custom admin host URL
clientHostStringSets a custom client host URL
dateTimeFormatterCallbackDateTimeFormatterCallbackSets a custom date/time formatter for consistent formatting across all UI components

The concluding code block:
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
  },
);

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 instead of Auth Key.
String uid = "user1";

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

Login using Auth Token

Production-safe authentication that does not expose the Auth Key in client code.
  1. Create a User via the CometChat API when the user signs up in your app.
  2. Create an Auth Token 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.
String authToken = "AUTH_TOKEN";

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

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
CometChatUIKit.logout(onSuccess: (s) {
    // TODO("Not yet implemented")
} , onError: (e) {
    // TODO("Not yet implemented")
});

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.
CometChatUIKit.createUser(userObject, onSuccess: (user) {
  // TODO("Not yet implemented")
}, onError: (e) {
  // TODO("Not yet implemented")
});

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.
CometChatUIKit.updateUser(userObject, onSuccess: (user) {
  // TODO("Not yet implemented")
}, onError: (e) {
  // TODO("Not yet implemented")
});

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.
CometChatUIKit.getLoggedInUser(onSuccess: (user) {
  // TODO("Not yet implemented")
}, onError: (e) {
  // TODO("Not yet implemented")
});

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”
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}");
    }
  },
);



Base Message

Text Message

Sends a text message in a 1:1 or group chat. Takes a TextMessage object.
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
  },
);

Media Message

Sends a media message in a 1:1 or group chat. Takes a MediaMessage object.
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
  },
);

Custom Message

Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a CustomMessage object.
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
  },
);

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
CometChatUIKit.sendFormMessage(formMessageObject, onSuccess: (p0) {
  // TODO("Not yet implemented")
}, onError: (p0) {
  // TODO("Not yet implemented")
});

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
CometChatUIKit.sendCardMessage(cardMessageObject, onSuccess: (p0) {
  // TODO("Not yet implemented")
}, onError: (p0) {
  // TODO("Not yet implemented")
});

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
CometChatUIKit.sendSchedulerMessage(schedulerMessageObject, onSuccess: (p0) {
  // TODO("Not yet implemented")
}, onError: (p0) {
  // TODO("Not yet implemented")
});

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
CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: (p0) {
  // TODO("Not yet implemented")
}, onError: (p0) {
  // TODO("Not yet implemented")
});

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.
CometChatUIKit.addReaction(messageId, "👍", onSuccess: (message) {
  // TODO("Not yet implemented")
}, onError: (e) {
  // TODO("Not yet implemented")
});

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.
CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) {
  // TODO("Not yet implemented")
}, onError: (e) {
  // TODO("Not yet implemented")
});