From 6b21e6d8b1887e499a3b6db71df4343d0887fd7e Mon Sep 17 00:00:00 2001 From: Anshuman-cometchat Date: Thu, 12 Feb 2026 15:24:05 +0530 Subject: [PATCH 01/32] added code snippets and made it agentic friendly --- ui-kit/flutter/ai-features.mdx | 63 +- ui-kit/flutter/call-features.mdx | 118 +++- ui-kit/flutter/core-features.mdx | 185 ++++-- ui-kit/flutter/events.mdx | 159 +++-- ui-kit/flutter/extensions.mdx | 107 +++- ui-kit/flutter/flutter-conversation.mdx | 294 ++++++++- ui-kit/flutter/flutter-one-to-one-chat.mdx | 530 ++++++++++++++- ui-kit/flutter/flutter-tab-based-chat.mdx | 604 ++++++++++++++++-- ui-kit/flutter/getting-started.mdx | 573 ++++++++++++----- ui-kit/flutter/guide-block-unblock-user.mdx | 73 ++- ui-kit/flutter/guide-call-log-details.mdx | 70 +- ui-kit/flutter/guide-group-chat.mdx | 76 ++- ui-kit/flutter/guide-message-agentic-flow.mdx | 70 +- ui-kit/flutter/guide-message-privately.mdx | 75 ++- ui-kit/flutter/guide-new-chat.mdx | 77 ++- ui-kit/flutter/guide-overview.mdx | 47 +- ui-kit/flutter/guide-threaded-messages.mdx | 74 ++- ui-kit/flutter/overview.mdx | 140 +++- 18 files changed, 2813 insertions(+), 522 deletions(-) diff --git a/ui-kit/flutter/ai-features.mdx b/ui-kit/flutter/ai-features.mdx index 18e1637c9..8ffcac57f 100644 --- a/ui-kit/flutter/ai-features.mdx +++ b/ui-kit/flutter/ai-features.mdx @@ -1,7 +1,43 @@ --- -title: "AI" +title: "AI Features" +description: "Enhance user interaction with AI-powered conversation starters, smart replies, and conversation summaries in your Flutter app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Enable AI features in UIKitSettings +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..aiFeature = [ + AISmartRepliesExtension(), + AIConversationStarterExtension(), + AIAssistBotExtension(), + AIConversationSummaryExtension() + ] +).build(); + +// Initialize with AI features +CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + +**Key AI Extensions:** +- `AISmartRepliesExtension` → Smart reply suggestions +- `AIConversationStarterExtension` → Conversation starters +- `AIAssistBotExtension` → AI assistant bot +- `AIConversationSummaryExtension` → Conversation summaries + +**Components:** +- Conversation Starters → Auto-displayed in `CometChatMessageList` ([Docs](/ui-kit/flutter/message-list)) +- Smart Replies → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) +- Conversation Summary → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) + +Activate features from [CometChat Dashboard](https://app.cometchat.com) → Extensions → AI + + ## Overview CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the Flutter UI Kit achieves these features. @@ -10,6 +46,10 @@ CometChat's AI capabilities greatly enhance user interaction and engagement in y + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) + + *** ## Usage @@ -67,8 +107,27 @@ The Conversation Summary feature provides concise summaries of long conversation For a comprehensive understanding and guide on implementing and using the Conversation Summary, refer to our specific guide on the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary). -Once you have successfully activated the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/flutter/message-composer) Widget of UI Kits. +Once you have successfully activated the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/flutter/message-composer) Widget of UI Kits. + +--- + +## Next Steps + + + + Display and manage conversation messages with AI-powered starters + + + Compose messages with smart replies and AI assistance + + + Learn more about AI features and configuration + + + Explore other extensions to enhance your chat experience + + diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index 12559e904..2322a5c28 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -1,11 +1,53 @@ --- -title: "Call" +title: "Call Features" +description: "Integrate one-on-one and group audio/video calling capabilities into your Flutter app with CometChat UI Kit" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; + +// Enable calling features in UIKitSettings +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "APP_ID" + ..authKey = "AUTH_KEY" + ..region = "REGION" + ..callingExtension = CometChatCallingExtension() +).build(); + +// Initialize with calling support +CometChatUIKit.init(uiKitSettings: uiKitSettings); + +// Set navigation key for incoming calls +CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey) + +// Add call listener +CometChat.addCallListener(listenerId, this); +``` + +**Key Calling Components:** +- `CometChatCallButtons` → [Docs](/ui-kit/flutter/call-buttons) +- `CometChatIncomingCall` → [Docs](/ui-kit/flutter/incoming-call) +- `CometChatOutgoingCall` → [Docs](/ui-kit/flutter/outgoing-call) +- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) +- `CometChatCallingExtension` → Calling extension +- `CallNavigationContext` → Navigation context for calls + +**Requirements:** `cometchat_calls_uikit` package, minSdkVersion 24 (Android), iOS 12+ + + ## Overview CometChat's Calls feature is an advanced functionality that allows you to seamlessly integrate one-on-one as well as group audio and video calling capabilities into your application. This document provides a technical overview of these features, as implemented in the Flutter UI Kit. + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) + + ## Integration First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/flutter/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your Flutter project. @@ -24,9 +66,7 @@ Add the following dependency to your `pubspec.yaml` file: dependencies: cometchat_calls_uikit: ^5.0.12 ``` - - *** @@ -47,17 +87,11 @@ defaultConfig { versionName flutterVersionName } ``` - - - -If you want to use the Flutter UI Kit or enable calling support within it, you'll need to: - -1. Set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. - +If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. *** @@ -73,9 +107,7 @@ In your Podfile located at `ios/Podfile`, update the minimum iOS version that yo ```xml platform :ios, '12.0' ``` - - *** @@ -94,22 +126,24 @@ Example UIKitSettings uiKitSettings = (UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true - ..region = "REGION"//Replace with your App Region - ..appId = "APP_ID" //Replace with your App ID - ..authKey = "AUTH_KEY" //Replace with your app Auth Key - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array you want to disable all extensions - ..callingExtension = CometChatCallingExtension() //Added this to Enable calling feature in the UI Kit + ..region = "REGION" // Replace with your App Region + ..appId = "APP_ID" // Replace with your App ID + ..authKey = "AUTH_KEY" // Replace with your app Auth Key + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Enable calling feature ).build(); -CometChatUIKit.init(uiKitSettings: uiKitSettings,onSuccess: (successMessage) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) { + // TODO("Not yet implemented") + }, + onError: (e) { + // TODO("Not yet implemented") + } +); ``` - - To allow launching of Incoming Call screen from any widget whenever a call is received provide set key: CallNavigationContext.navigatorKey in the top most widget of your project (the widget that appears first of your app launch). @@ -118,14 +152,19 @@ To allow launching of Incoming Call screen from any widget whenever a call is re ```dart CometChatUIKit.login(uid, onSuccess: (s) { - Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey))); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUsersWithMessages( + key: CallNavigationContext.navigatorKey + ) + ) + ); }, onError: (e) { // TODO("Not yet implemented") }); ``` - - After adding this dependency, the Flutter UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/flutter/call-buttons) widget rendered in [MessageHeader](/ui-kit/flutter/message-header) Widget. @@ -147,13 +186,13 @@ class _YourClassNameState extends State with CallListener { @override void initState() { super.initState(); - CometChat.addCallListener(listenerId, this); //Add listener + CometChat.addCallListener(listenerId, this); // Add listener } @override void dispose() { super.dispose(); - CometChat.removeCallListener(listenerId); //Remove listener + CometChat.removeCallListener(listenerId); // Remove listener } @override @@ -193,9 +232,7 @@ class _YourClassNameState extends State with CallListener { } } ``` - - *** @@ -229,3 +266,22 @@ Importantly, the Outgoing Call widget is smartly designed to transition automati + +--- + +## Next Steps + + + + Add audio and video call buttons to your chat interface + + + Handle and display incoming call screens + + + Manage outgoing call screens and transitions + + + Display call history and records + + diff --git a/ui-kit/flutter/core-features.mdx b/ui-kit/flutter/core-features.mdx index 5d91b8c1f..fc991048d 100644 --- a/ui-kit/flutter/core-features.mdx +++ b/ui-kit/flutter/core-features.mdx @@ -1,13 +1,35 @@ --- -title: "Core" +title: "Core Features" +sidebarTitle: "Core" +description: "Comprehensive guide to CometChat's core messaging features including instant messaging, media sharing, read receipts, and more" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Key components for core features: +- **Instant Messaging** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Media Sharing** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Read Receipts** → [Conversations](/ui-kit/flutter/conversations) | [MessageList](/ui-kit/flutter/message-list) +- **Typing Indicators** → [Conversations](/ui-kit/flutter/conversations) | [MessageHeader](/ui-kit/flutter/message-header) +- **User Presence** → [Conversations](/ui-kit/flutter/conversations) | [Users](/ui-kit/flutter/users) +- **Reactions** → [MessageList](/ui-kit/flutter/message-list) +- **Mentions** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Threaded Messages** → [Threaded Messages](/ui-kit/flutter/threaded-messages-header) +- **Group Chat** → [Groups](/ui-kit/flutter/groups) + The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [REST API](https://api-explorer.cometchat.com) + + Here's how different UI Kit widgets work together to achieve CometChat's Core features: +*** + ## Instant Messaging At the heart of CometChat's functionality is the ability to support real-time text messaging. Users can send and receive instant messages, fostering quick and efficient communication. @@ -16,10 +38,12 @@ At the heart of CometChat's functionality is the ability to support real-time te -| Widgets | Functionality | -| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that enables users to write and send a variety of messages. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders a list of messages sent and messages received using [TextBubble](/ui-kit/flutter/message-bubble-styling#text-bubble). | +| Widgets | Functionality | +| --- | --- | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that enables users to write and send a variety of messages. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders a list of messages sent and messages received using [TextBubble](/ui-kit/flutter/message-bubble-styling#text-bubble). | + +*** ## Media Sharing @@ -29,10 +53,12 @@ Beyond text, CometChat allows users to share various media types within their co -| Widgets | Functionality | -| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that has ActionSheet, ActionSheet is a menu that appears over the context of the app, providing multiple options for sharing media files. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different Media Message bubbles like [Image Bubble](/ui-kit/flutter/message-bubble-styling-styling#image-bubble), [File Bubble](/ui-kit/flutter/message-bubble-styling-styling#file-bubble), [Audio Bubble](/ui-kit/flutter/message-bubble-styling-styling#audio-bubble) [Video Bubble](/ui-kit/flutter/message-bubble-styling#video-bubble) | +| Widgets | Functionality | +| --- | --- | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that has ActionSheet, ActionSheet is a menu that appears over the context of the app, providing multiple options for sharing media files. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different Media Message bubbles like [Image Bubble](/ui-kit/flutter/message-bubble-styling#image-bubble), [File Bubble](/ui-kit/flutter/message-bubble-styling#file-bubble), [Audio Bubble](/ui-kit/flutter/message-bubble-styling#audio-bubble), [Video Bubble](/ui-kit/flutter/message-bubble-styling#video-bubble) | + +*** ## Read Receipts @@ -42,11 +68,12 @@ CometChat's Read Receipts feature provides visibility into the message status, l -| Widgets | Functionality | -| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Read Recept status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | -| [MessageInformation](/ui-kit/flutter/message-information) | [MessageInformation](/ui-kit/flutter/message-information) widget provides transparency into the status of each sent message, giving the sender insights into whether their message has been delivered and read. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Read Receipt status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | + +*** ## Mark As Unread @@ -56,10 +83,12 @@ Mark as Unread feature allows users to manually mark messages as unread, helping -| Widgets | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/flutter/message-list#functionality) | [Message List](/ui-kit/flutter/message-list#functionality) provides the "Mark as unread" option in message actions and supports starting from the first unread message when enabled. | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget listens to conversation updates and reflects the updated unread count in real-time. | +| Widgets | Functionality | +| --- | --- | +| [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) provides the "Mark as unread" option in message actions and supports starting from the first unread message when enabled. | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget listens to conversation updates and reflects the updated unread count in real-time. | + +*** ## Typing Indicator @@ -69,11 +98,13 @@ The Typing Indicator feature in CometChat shows when a user is typing a response -| Widgets | Functionality | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows real-time typing status indicators. This means that if a user in a one-on-one chat or a participant in a group chat is currently typing a message | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows real-time typing status indicators. This means that if a user in a one-on-one chat or a participant in a group chat is currently typing a message | | [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles the Typing Indicator functionality. When a user or a member in a group is typing, the MessageHeader dynamically updates to display a 'typing...' status in real-time. | +*** + ## User Presence CometChat's User Presence feature allows users to see whether their contacts are online, offline. This helps users know the best time to initiate a conversation and sets expectations about response times. @@ -82,12 +113,14 @@ CometChat's User Presence feature allows users to see whether their contacts are -| Widgets | Functionality | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows user presence information. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows user presence information. | | [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles user Presence information. | -| [Users](/ui-kit/flutter/users) | [Users](/ui-kit/flutter/users) renders list of users available in your app.It also responsible to render users Presence information. | -| [Group Members](/ui-kit/flutter/group-members) | [Group Members](/ui-kit/flutter/group-members) renders list of users available in the group. The Group Members widget also handles user Presence information. | +| [Users](/ui-kit/flutter/users) | [Users](/ui-kit/flutter/users) renders list of users available in your app. It also responsible to render users Presence information. | +| [Group Members](/ui-kit/flutter/group-members) | [Group Members](/ui-kit/flutter/group-members) renders list of users available in the group. The Group Members widget also handles user Presence information. | + +*** ## Reactions @@ -101,10 +134,12 @@ In the example, tapping on this element (depicted as "+2" in the provided image) -| Widgets | Functionality | -| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Irrespective of the type of message bubble, Reactions are an integral part and offer a more engaging, expressive way for users to respond to messages. | +*** + ## Mentions Mentions is a robust feature provided by CometChat that enhances the interactivity and clarity of group or 1-1 chats by allowing users to directly address or refer to specific individuals in a conversation. The feature also supports group mentions like @all, enabling users to quickly notify all members in a group chat simultaneously. @@ -113,38 +148,45 @@ Mentions is a robust feature provided by CometChat that enhances the interactivi -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget provides an enhanced user experience by integrating the Mentions feature. This means that from the conversation list itself, users can see where they or someone else have been specifically mentioned. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer)is a widget that allows users to craft and send various types of messages, including the usage of the Mentions feature for direct addressing within the conversation. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a widget that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget provides an enhanced user experience by integrating the Mentions feature. This means that from the conversation list itself, users can see where they or someone else have been specifically mentioned. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a widget that allows users to craft and send various types of messages, including the usage of the Mentions feature for direct addressing within the conversation. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a widget that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | + +*** ## Quoted Reply -Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the “Reply” option from a message’s action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. +Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) supports replying to messages via the “Reply” option. Users can select “Reply” on a message to open the composer with the quoted reply pre-filled, maintaining context. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer)works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | +| Widgets | Functionality | +| --- | --- | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | + +*** ## Conversation and Advanced Search Conversation and Advanced Search is a powerful feature provided by CometChat that enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. + -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Search](/ui-kit/flutter/message-header) | [Search](/ui-kit/flutter/message-header) allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | -| [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) shows the search button in the chat header, allowing users to search within a conversation. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) shows the selected message when clicked from search results and highlights it in the message list. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) displays the search input. | +| Widgets | Functionality | +| --- | --- | +| [Search](/ui-kit/flutter/search) | [Search](/ui-kit/flutter/search) allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | +| [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) shows the search button in the chat header, allowing users to search within a conversation. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) shows the selected message when clicked from search results and highlights it in the message list. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) displays the search input. | + +*** ## Moderation @@ -158,12 +200,14 @@ CometChat's Message Moderation feature helps maintain a safe and respectful chat Learn more about setting up moderation rules and managing content in the [Moderation](/moderation/overview) documentation. -| Widgets | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) automatically handles moderated messages, displaying blocked content appropriately based on your moderation settings. | After implementing moderation rules, users can report messages they find inappropriate or harmful. As a next step, you can enable the **[Report Message](#report-message)** feature to allow users to flag messages for review by moderators. +*** + ## Report Message The Report Message feature allows users to report inappropriate or harmful messages within the chat. Users can choose from predefined reasons and provide additional remarks for detailed context. This feature helps maintain a safe and respectful chat environment. @@ -173,12 +217,14 @@ Learn more about how flagged messages are handled, reviewed, and moderated in th - + -| Components | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | +| Widgets | Functionality | +| --- | --- | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | + +*** ## Threaded Conversations @@ -188,21 +234,11 @@ The Threaded Conversations feature enables users to respond directly to a specif -| Widgets | Functionality | -| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [Threaded Messages](/ui-kit/flutter/threaded-messages-header) | [Threaded Messages](/ui-kit/flutter/threaded-messages-header) that displays all replies made to a particular message in a conversation. | -## Report Message - -The Report Message feature allows users to report inappropriate or harmful messages within the chat. Users can choose from predefined reasons and provide additional remarks for detailed context. This feature helps maintain a safe and respectful chat environment. - - - - - -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) provides the “Report Message” option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | +*** ## Group Chat @@ -213,3 +249,24 @@ CometChat facilitates Group Chats, allowing users to have conversations with mul For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, you should refer to our detailed guide on [Groups](/ui-kit/flutter/groups). + +*** + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Display and manage messages with real-time updates + + + Show conversation lists with typing indicators and receipts + + + Create and manage group conversations + + + +*** diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 7e059a76b..7d7f857d1 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -1,17 +1,47 @@ --- title: "Events" +description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Add event listener +CometChatMessageEvents.addMessagesListener("LISTENER_ID", this); + +// Remove event listener +CometChatMessageEvents.removeMessagesListener("LISTENER_ID"); + +// Implement listener methods +@override +void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { + // Handle message sent event +} +``` + +**Available Event Types:** +- **User Events** → Block/Unblock users +- **Group Events** → Create, delete, join, leave groups +- **Conversation Events** → Delete conversations +- **Message Events** → Send, edit, delete, receive messages +- **Call Events** → Outgoing, accepted, rejected, ended calls +- **UI Events** → Show/hide panels, active chat changes + Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. -### User Events +*** + +## User Events `CometChatUserEvents` emit events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events, as well as methods to handle specific user actions such as blocking and unblocking users. +**Available Events:** + 1. `ccUserBlocked`: Triggered when the logged-in user blocks another user. 2. `ccUserUnblocked`: Triggered when the logged-in user unblocks another user. @@ -61,18 +91,16 @@ class _UserEventsExampleState extends State with CometChatUse } } ``` - - *** -### Group Events +## Group Events `CometChatGroupEvents` Emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events and handle them accordingly. -Following are all the group events +**Available Events:** 1. `ccGroupCreated`: Triggered when the logged-in user creates a group. 2. `ccGroupDeleted`: Triggered when the logged-in user deletes a group. @@ -85,8 +113,6 @@ Following are all the group events 9. `ccGroupMemberAdded`: Triggered when the logged-in user adds new members to the group. 10. `ccOwnershipChanged`: Triggered when the logged-in user transfers the ownership of their group to some other member. -To listen to group events - ```dart @@ -165,30 +191,27 @@ class _GroupEventsExampleState extends State with CometChatG @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - + // TODO("Not yet implemented") } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - *** -### Conversation Events +## Conversation Events -The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. Below are the events emitted by the Conversation Component: +The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. -1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. +**Available Events:** -To listen to conversation events and handle them in your application, you can use the following code snippets: +1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. @@ -229,19 +252,18 @@ class _ConversationEventsExampleState extends State w Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - *** -### Message Events +## Message Events + +`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. -`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. Below are the events emitted by the MessageEvents component: +**Available Events:** 1. `ccMessageSent`: Triggered whenever a logged-in user sends any message. It can have two states: `inProgress` and `sent`. 2. `ccMessageEdited`: Triggered whenever a logged-in user edits any message from the list of messages. It can have two states: `inProgress` and `sent`. @@ -267,8 +289,6 @@ class _ConversationEventsExampleState extends State w 22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. 23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. -To listen to message events and handle them in your application, you can use the following code snippets: - ```dart @@ -296,7 +316,7 @@ class _MessageEventsExampleState extends State with CometC void dispose() { super.dispose(); - CometChatConversationEvents.removeConversationListListener(listenerID); // Remove the listener + CometChatMessageEvents.removeMessagesListener(listenerID); // Remove the listener } @override @@ -407,7 +427,7 @@ class _MessageEventsExampleState extends State with CometC @override void onMessageReactionRemoved(ReactionEvent reactionEvent) { - // TODO("Not yet implemented") + // TODO("Not yet implemented") } @override @@ -416,17 +436,17 @@ class _MessageEventsExampleState extends State with CometC } } ``` - - *** -### Call Events +## Call Events `CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events and handle them accordingly. +**Available Events:** + 1. `ccOutgoingCall`: Triggered when the logged-in user initiates an outgoing call. 2. `ccCallAccepted`: Triggered when a call is accepted. 3. `ccCallRejected`: Triggered when a call is rejected. @@ -488,26 +508,22 @@ class _CallEventsExampleState extends State with CometChatCal } } ``` - - *** -### UI Events +## UI Events `CometChatUIEvents` emits events related to UI components within the CometChat UI. This class provides methods to listen to UI-related events and handle them accordingly. -Following are the UI events +**Available Events:** 1. `showPanel`: Triggered to show an additional UI panel with custom elements. 2. `hidePanel`: Triggered to hide a previously shown UI panel. 3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. 4. `ccOpenChat`: Triggered to open a chat with a specific user or group. -To listen to UI events and handle them in your application, you can use the following code snippet: - ```dart @@ -574,9 +590,80 @@ class _UIEventsExampleState extends State with CometChatUIEvent } } ``` - - *** + +## Best Practices + + + + Always remove event listeners in the `dispose()` method to prevent memory leaks: + + + + ```dart + @override + void dispose() { + super.dispose(); + CometChatMessageEvents.removeMessagesListener(listenerID); + } + ``` + + + + + + Use unique listener IDs for each widget to avoid conflicts: + + + + ```dart + String listenerID = "message_list_${widget.key}"; + ``` + + + + + + Keep event handlers lightweight and avoid heavy operations: + + + + ```dart + @override + void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { + if (messageStatus == MessageStatus.sent) { + // Update UI efficiently + setState(() { + // Minimal state update + }); + } + } + ``` + + + + + +*** + +## Next Steps + + + + Learn how to display and manage messages with events + + + Handle conversation events and updates + + + Manage group events and member actions + + + Explore available methods for UI Kit operations + + + +*** diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 0e4c88e7c..24d3cc1d9 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -1,16 +1,48 @@ --- title: "Extensions" +description: "Enhance your chat with built-in extensions including stickers, polls, collaborative tools, message translation, and link previews" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** -CometChat’s UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. +```dart +// Enable extensions during initialization +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() +).build(); + +await CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + +**Built-in Extensions:** +- **Stickers** → Express emotions with pre-designed stickers +- **Polls** → Create polls for group discussions +- **Collaborative Whiteboard** → Real-time drawing and brainstorming +- **Collaborative Document** → Shared document editing +- **Message Translation** → Translate messages to local locale +- **Link Preview** → Show URL summaries with thumbnails +- **Thumbnail Generation** → Auto-generate image previews + +**Enable from:** [CometChat Dashboard](https://app.cometchat.com) → Extensions + + +CometChat's UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. + + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) + Activating any of the extensions in CometChat is a simple process done through your application's dashboard. Refer to our guide For detailed information on [Extensions](/fundamentals/extensions-overview) Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. Please note, that the extension features will only be available if they are supported by CometChat UI Kit. -CometChat’s UI Kit offers built-in support for 12 powerful extensions. This seamless integration makes it easy for you to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant widgets of your application, providing a richer and more engaging experience for your users. +CometChat's UI Kit offers built-in support for 12 powerful extensions. This seamless integration makes it easy for you to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant widgets of your application, providing a richer and more engaging experience for your users. + +*** ## Built-in Extensions @@ -26,6 +58,8 @@ Once you have successfully activated the [Sticker Extension](/fundamentals/stick +*** + ### Polls The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive understanding and guide on implementing and using the Polls Extension, refer to our specific guide on the [Polls Extension](/fundamentals/polls). @@ -36,6 +70,8 @@ Once you have successfully activated the [Polls Extension](/fundamentals/polls) +*** + ### Collaborative Whiteboard The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive understanding and guide on implementing and using the Collaborative Whiteboard Extension, refer to our specific guide on the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard). @@ -46,6 +82,8 @@ Once you have successfully activated the [Collaborative Whiteboard Extension](/f +*** + ### Collaborative Document With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive understanding and guide on implementing and using the Collaborative Document Extension, refer to our specific guide on the [Collaborative Document Extension](/fundamentals/collaborative-document). @@ -56,6 +94,8 @@ Once you have successfully activated the [Collaborative Document Extension](/fun +*** + ### Message Translation The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). @@ -66,6 +106,8 @@ Once you have successfully activated the [Message Translation Extension](/fundam +*** + ### Link Preview The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). @@ -76,6 +118,8 @@ Once you have successfully activated the [Link Preview Extension](/fundamentals/ +*** + ### Thumbnail Generation The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). @@ -85,3 +129,60 @@ Once you have successfully activated the [Thumbnail Generation Extension](/funda + +*** + +## Enabling Extensions + +To enable extensions in your Flutter app, configure them during initialization: + + + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..authKey = "YOUR_AUTH_KEY" + ..subscriptionType = CometChatSubscriptionType.allUsers + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Enable all default extensions +).build(); + +await CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + + + +To disable all extensions, pass an empty array: + + + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..extensions = [] // Disable all extensions +).build(); +``` + + + +*** + +## Next Steps + + + + Learn how extensions integrate with the message composer + + + See how extensions enhance message display + + + Explore all available extensions in detail + + + Enable extensions from your CometChat Dashboard + + + +*** diff --git a/ui-kit/flutter/flutter-conversation.mdx b/ui-kit/flutter/flutter-conversation.mdx index 6a198673c..965ae8489 100644 --- a/ui-kit/flutter/flutter-conversation.mdx +++ b/ui-kit/flutter/flutter-conversation.mdx @@ -1,7 +1,50 @@ --- title: "Conversation List + Message View" +sidebarTitle: "Conversation + Message" +description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Show conversations with navigation to messages +CometChatConversations( + showBackButton: true, + onItemTap: (conversation) { + final target = conversation.conversationWith; + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, + ), + ), + ); + }, +) + +// Messages screen with header, list, and composer +Scaffold( + appBar: CometChatMessageHeader(user: user, group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), + ], + ), +) +``` + +**Key Components:** +- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) +- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) +- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) +- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) + + The **Conversation List + Message View** layout provides a seamless **two-panel chat interface**, commonly seen in modern messaging apps like **WhatsApp Web**, **Slack**, and **Microsoft Teams**. This layout allows users to switch between conversations while keeping the active chat open, delivering a **smooth, real-time messaging experience**. @@ -12,43 +55,71 @@ This layout allows users to switch between conversations while keeping the activ *** +## **How It Works** + +This implementation uses Flutter's navigation system to create a mobile-friendly chat experience: + +1. **Conversation List Screen** – Displays all recent conversations using `CometChatConversations` +2. **Navigation** – Tapping a conversation pushes the message screen onto the navigation stack +3. **Message Screen** – Shows the full chat interface with header, message list, and composer +4. **Back Navigation** – Users can return to the conversation list using the back button + +*** + +## **Implementation** + ### **Step 1: Render the Conversation Component** The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - - final target = conversation.conversationWith; - - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), +@override +Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: CometChatConversations( + showBackButton: true, + onItemTap: (conversation) { + final target = conversation.conversationWith; + + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, ), - ); - }, - ), + ), + ); + }, ), - ); - } + ), + ); +} ``` + + + +**Key Properties:** + +| Property | Type | Description | +| --- | --- | --- | +| `showBackButton` | bool | Shows/hides the back button in the app bar | +| `onItemTap` | Function | Callback when a conversation is tapped | +| `conversationWith` | User or Group | The target entity (user or group) for the conversation | + +*** -#### **Full Example: main.dart** +### **Full Example: main.dart** + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -80,8 +151,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -131,7 +202,6 @@ class ConversationsPage extends StatelessWidget { child: CometChatConversations( showBackButton: true, onItemTap: (conversation) { - final target = conversation.conversationWith; Navigator.push( @@ -150,19 +220,25 @@ class ConversationsPage extends StatelessWidget { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -205,6 +281,16 @@ class _MessagesScreenState extends State { } } ``` + + + +**Component Breakdown:** + +| Component | Purpose | Key Features | +| --- | --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | +| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | +| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | *** @@ -212,7 +298,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -220,10 +306,150 @@ This will launch the app and display the **Conversation List**. Tapping a conver *** -## **Next Steps** +## **Customization Options** + +### **Conversation List Customization** + + + +```dart +CometChatConversations( + title: "My Chats", + showBackButton: false, + hideSearch: false, + onItemTap: (conversation) { + // Custom navigation logic + }, + onItemLongPress: (conversation) { + // Show options menu + }, + conversationsStyle: ConversationsStyle( + background: Colors.white, + titleStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), +) +``` + + + +### **Message Screen Customization** + + + +```dart +CometChatMessageList( + user: user, + group: group, + hideMessageComposer: false, + hideMessageHeader: false, + messageListStyle: MessageListStyle( + background: Colors.grey[100], + ), +) +``` + + + +For complete customization options, see: +* [Conversations Customization](/ui-kit/flutter/conversations) +* [Message List Customization](/ui-kit/flutter/message-list) +* [Message Composer Customization](/ui-kit/flutter/message-composer) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** -### **Enhance the User Experience** +## **Common Use Cases** + + + + + + ```dart + CometChatConversations( + conversationsRequestBuilder: ConversationsRequestBuilder() + ..conversationType = CometChatConversationType.user // or .group + ..limit = 30, + ) + ``` + + + + + + + + ```dart + CometChatConversations( + onItemLongPress: (conversation) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Options'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + title: Text('Delete Conversation'), + onTap: () { + // Delete conversation logic + }, + ), + ], + ), + ), + ); + }, + ) + ``` + + + + + + + + ```dart + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: (context, animation, secondaryAnimation) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, + ), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + return SlideTransition( + position: Tween( + begin: const Offset(1.0, 0.0), + end: Offset.zero, + ).animate(animation), + child: child, + ); + }, + ), + ); + ``` + + + + + +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Learn about all conversation list customization options + + + Explore message list, header, and composer features + + + Customize colors, fonts, and styles to match your brand + + + Handle real-time events and user interactions + + *** diff --git a/ui-kit/flutter/flutter-one-to-one-chat.mdx b/ui-kit/flutter/flutter-one-to-one-chat.mdx index 36a22d780..136095916 100644 --- a/ui-kit/flutter/flutter-one-to-one-chat.mdx +++ b/ui-kit/flutter/flutter-one-to-one-chat.mdx @@ -1,8 +1,54 @@ --- title: "Building A One To One/Group Chat Experience" sidebarTitle: "One To One/Group Chat" +description: "Create a focused direct messaging interface for one-to-one or group conversations using Flutter UI Kit" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Fetch a user and show messages directly +Future fetchCometChatUser(String uid) async { + final completer = Completer(); + CometChat.getUser( + uid, + onSuccess: (user) => completer.complete(user), + onError: (error) => completer.completeError(error), + ); + return completer.future; +} + +// Show messages screen directly +FutureBuilder( + future: fetchCometChatUser("cometchat-uid-2"), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } + return CircularProgressIndicator(); + }, +) + +// Messages screen +Scaffold( + appBar: CometChatMessageHeader(user: user, group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), + ], + ), +) +``` + +**Key Components:** +- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) +- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) +- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) + + The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. @@ -11,40 +57,79 @@ The **One-to-One Chat** feature provides a streamlined **direct messaging interf *** +## **How It Works** + +This implementation bypasses the conversation list and opens directly into a chat: + +1. **Fetch User/Group** – Retrieve the target user or group using their UID/GUID +2. **Direct Navigation** – Launch directly into the message screen +3. **Focused Experience** – No conversation list, just the active chat +4. **Ideal for Context** – Perfect for support tickets, notifications, or deep links + +*** + +## **Use Cases** + +* **Customer Support** – Direct users to agent chat from help center +* **Dating Apps** – Open chat after a match +* **Notifications** – Deep link from push notification to specific chat +* **Onboarding** – Guide new users through a welcome chat +* **Contextual Messaging** – Start chat from user profile or product page + +*** + +## **Implementation** + ### **Step 1: Render the Message View** -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +The `CometChatMessageList` widget displays all messages for a specific user or group. Follow the steps below to render this component: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), +@override +Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: FutureBuilder( + future: fetchCometChatUser("cometchat-uid-2"), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + return Center(child: Text("Error: ${snapshot.error}")); + } else if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } else { + return const Center(child: Text("User not found")); + } + }, ), - ); - } + ), + ); +} ``` + + + +**Key Concepts:** -#### **Full Example: main.dart** +| Concept | Description | +| --- | --- | +| `fetchCometChatUser()` | Async function to retrieve user by UID | +| `FutureBuilder` | Widget that builds based on async operation state | +| `MessagesScreen` | Custom widget containing message components | +*** + +### **Full Example: main.dart** + + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -78,8 +163,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -155,19 +240,25 @@ class MessagesPage extends StatelessWidget { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -210,6 +301,16 @@ class _MessagesScreenState extends State { } } ``` + + + +**Component Breakdown:** + +| Component | Purpose | Key Features | +| --- | --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | +| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | +| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | *** @@ -217,7 +318,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -225,10 +326,375 @@ This will launch the app, and you should see the one-to-one chat interface with *** -## **Next Steps** +## **Variations** + +### **For Group Chat** + +To open a group chat instead of a one-to-one chat, fetch a group instead of a user: + + + +```dart +Future fetchCometChatGroup(String guid) async { + final completer = Completer(); + CometChat.getGroup( + guid, + onSuccess: (group) => completer.complete(group), + onError: (error) => completer.completeError(error), + ); + return completer.future; +} -### **Enhance the User Experience** +// In your widget +FutureBuilder( + future: fetchCometChatGroup("your-group-guid"), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(group: snapshot.data!); + } + return CircularProgressIndicator(); + }, +) +``` + + + +### **From Route Parameters** + +Pass user/group ID through navigation: + + + +```dart +// Navigate with parameters +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(userId: "cometchat-uid-2"), + ), +); + +// ChatScreen widget +class ChatScreen extends StatelessWidget { + final String userId; + + const ChatScreen({Key? key, required this.userId}) : super(key: key); + + Future fetchUser() async { + final completer = Completer(); + CometChat.getUser( + userId, + onSuccess: (user) => completer.complete(user), + onError: (error) => completer.completeError(error), + ); + return completer.future; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: fetchUser(), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } + return Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + }, + ); + } +} +``` + + + +### **From Deep Link** + +Handle deep links to open specific chats: + + + +```dart +// In your main app +MaterialApp( + onGenerateRoute: (settings) { + if (settings.name == '/chat') { + final args = settings.arguments as Map; + return MaterialPageRoute( + builder: (_) => ChatScreen( + userId: args['userId'], + groupId: args['groupId'], + ), + ); + } + return null; + }, +) + +// Navigate from deep link +Navigator.pushNamed( + context, + '/chat', + arguments: {'userId': 'cometchat-uid-2'}, +); +``` + + + +*** + +## **Customization Options** + +### **Hide Header or Composer** + + + +```dart +MessagesScreen( + user: user, + hideMessageHeader: true, // Hide the header + hideMessageComposer: false, // Show the composer +) +``` + + + +### **Custom Message Actions** + + + +```dart +CometChatMessageList( + user: user, + onMessageTap: (message) { + // Handle message tap + }, + onMessageLongPress: (message) { + // Show options menu + }, +) +``` + + + +### **Styling** + + + +```dart +CometChatMessageList( + user: user, + messageListStyle: MessageListStyle( + background: Colors.grey[100], + loadingIconTint: Colors.blue, + ), +) +``` + + + +For complete customization options, see: +* [Message List Customization](/ui-kit/flutter/message-list) +* [Message Header Customization](/ui-kit/flutter/message-header) +* [Message Composer Customization](/ui-kit/flutter/message-composer) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** + +## **Common Use Cases** + + + + + + ```dart + // From support ticket screen + ElevatedButton( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen( + userId: ticket.assignedAgentId, + ), + ), + ); + }, + child: Text('Chat with Support'), + ) + ``` + + + + + + + + ```dart + // From user profile screen + IconButton( + icon: Icon(Icons.message), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(userId: profile.userId), + ), + ); + }, + ) + ``` + + + + + + + + ```dart + // Handle notification tap + void handleNotificationTap(Map data) { + final userId = data['senderId']; + Navigator.pushNamed( + context, + '/chat', + arguments: {'userId': userId}, + ); + } + ``` + + + + + + + + ```dart + CometChatMessageComposer( + user: user, + text: "Hello! I need help with...", // Pre-filled text + ) + ``` + + + + + +*** + +## **Best Practices** + + + + Always handle errors when fetching users or groups: + + + + ```dart + FutureBuilder( + future: fetchCometChatUser(userId), + builder: (context, snapshot) { + if (snapshot.hasError) { + return Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error, size: 48, color: Colors.red), + SizedBox(height: 16), + Text('Failed to load chat'), + ElevatedButton( + onPressed: () => setState(() {}), // Retry + child: Text('Retry'), + ), + ], + ), + ), + ); + } + // ... rest of builder + }, + ) + ``` + + + + + + Provide clear loading indicators: + + + + ```dart + if (snapshot.connectionState == ConnectionState.waiting) { + return Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text('Loading chat...'), + ], + ), + ), + ); + } + ``` + + + + + + Cache fetched users to avoid repeated API calls: + + + + ```dart + class UserCache { + static final Map _cache = {}; + + static Future getUser(String uid) async { + if (_cache.containsKey(uid)) { + return _cache[uid]!; + } + + final completer = Completer(); + CometChat.getUser( + uid, + onSuccess: (user) { + _cache[uid] = user; + completer.complete(user); + }, + onError: (error) => completer.completeError(error), + ); + return completer.future; + } + } + ``` + + + + + +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Explore message list, header, and composer features + + + Add a conversation list for multi-chat support + + + Customize colors, fonts, and styles to match your brand + + + Handle real-time events and user interactions + + *** diff --git a/ui-kit/flutter/flutter-tab-based-chat.mdx b/ui-kit/flutter/flutter-tab-based-chat.mdx index cc2abe662..5959a206b 100644 --- a/ui-kit/flutter/flutter-tab-based-chat.mdx +++ b/ui-kit/flutter/flutter-tab-based-chat.mdx @@ -1,9 +1,49 @@ --- title: "Building A Messaging UI With Tabs, Sidebar, And Message View" sidebarTitle: "Tab Based Chat Experience" +description: "Create a multi-tab chat interface with conversations, calls, users, and groups using Flutter bottom navigation" --- -This guide walks you through creating a **tab-based messaging UI** using **React** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Tab-based UI with bottom navigation +Scaffold( + body: PageView( + controller: _pageController, + children: [ + CometChatConversations(), + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: (index) { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + }, + items: [ + BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chat"), + BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), + BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), + BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), + ], + ), +) +``` + +**Key Components:** +- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) +- **Call Logs** → [CometChatCallLogs](/ui-kit/flutter/call-logs) +- **Users** → [CometChatUsers](/ui-kit/flutter/users) +- **Groups** → [CometChatGroups](/ui-kit/flutter/groups) + + +This guide walks you through creating a **tab-based messaging UI** using **Flutter** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. *** @@ -15,50 +55,123 @@ This guide walks you through creating a **tab-based messaging UI** using **React This layout consists of: -1. **Sidebar (Conversation List)** – Displays recent conversations with active users and groups. -2. **Message View** – Shows the selected chat with real-time messages. -3. **Message Input Box** – Allows users to send messages seamlessly. +1. **Bottom Navigation Bar** – Tabs for switching between Chats, Calls, Users, and Groups +2. **Page View** – Displays the selected tab's content +3. **Conversation List** – Shows recent conversations with active users and groups +4. **Message View** – Opens when a conversation is tapped + +*** + +## **How It Works** + +This implementation uses Flutter's `BottomNavigationBar` and `PageView` to create a tabbed interface: + +1. **Bottom Navigation** – Provides quick access to different sections +2. **Page View** – Swipeable pages for each tab +3. **State Management** – Syncs selected tab with page view +4. **Navigation** – Tapping a conversation opens the message screen *** +## **Use Cases** + +* **All-in-One Chat Apps** – Complete messaging solution with multiple features +* **Business Messengers** – Professional communication with organized sections +* **Social Platforms** – Community chat with user discovery +* **Support Apps** – Help desk with call logs and user management +* **Team Collaboration** – Internal communication with group management + +*** + +## **Implementation** + ### **Step 1: Render the Tab Component** -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +The tab-based UI uses `BottomNavigationBar` for navigation and `PageView` for content display: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), - body: SafeArea( - child: Column( - children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, +@override +Widget build(BuildContext context) { + return Scaffold( + body: PageView( + controller: _pageController, + onPageChanged: (index) { + setState(() { + _selectedIndex = index; + }); + }, + children: [ + CometChatConversations( + showBackButton: false, + onItemTap: (conversation) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen( + user: conversation.conversationWith is User + ? conversation.conversationWith as User + : null, + group: conversation.conversationWith is Group + ? conversation.conversationWith as Group + : null, + ), ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, - ), - ], + ); + }, ), - ), - ); - } + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: _onItemTapped, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.chat), + label: "Chat", + ), + BottomNavigationBarItem( + icon: Icon(Icons.call), + label: "Calls", + ), + BottomNavigationBarItem( + icon: Icon(Icons.person), + label: "Users", + ), + BottomNavigationBarItem( + icon: Icon(Icons.group), + label: "Groups", + ), + ], + ), + ); +} ``` + + + +**Key Components:** -#### **Full Example: main.dart** +| Component | Purpose | Key Features | +| --- | --- | --- | +| `PageView` | Container for swipeable pages | Smooth transitions, gesture support | +| `BottomNavigationBar` | Tab navigation | Icon + label, active state | +| `PageController` | Controls page view | Jump to page, animate transitions | + +*** +### **Full Example: main.dart** + + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -90,8 +203,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -149,6 +262,12 @@ class _TabsScreenState extends State { _pageController.jumpToPage(index); } + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -179,13 +298,34 @@ class _TabsScreenState extends State { }, ), CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), + CometChatUsers( + onItemTap: (user) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen(user: user), + ), + ); + }, + ), + CometChatGroups( + onItemTap: (group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen(group: group), + ), + ); + }, + ), ], ), bottomNavigationBar: BottomNavigationBar( + type: BottomNavigationBarType.fixed, currentIndex: _selectedIndex, onTap: _onItemTapped, + selectedItemColor: Colors.deepPurple, + unselectedItemColor: Colors.grey, items: const [ BottomNavigationBarItem( icon: Icon(Icons.chat), @@ -209,19 +349,25 @@ class _TabsScreenState extends State { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -264,6 +410,8 @@ class _MessagesScreenState extends State { } } ``` + + *** @@ -271,7 +419,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -279,10 +427,384 @@ This will launch the app, and you should see the tab-based chat experience with *** -## **Next Steps** +## **Tab Descriptions** + +### **1. Chat Tab** + +Displays recent conversations with users and groups: + +* **CometChatConversations** – Shows conversation list +* **Real-time updates** – New messages appear instantly +* **Unread counts** – Badge showing unread message count +* **Last message preview** – Shows snippet of last message +* **Tap to open** – Navigate to full message view + +### **2. Calls Tab** + +Shows call history and logs: + +* **CometChatCallLogs** – Displays all call records +* **Call types** – Audio and video calls +* **Call status** – Missed, incoming, outgoing +* **Tap to call back** – Initiate new call from history +* **Call duration** – Shows length of completed calls + +### **3. Users Tab** + +Browse and search all users: + +* **CometChatUsers** – Lists all available users +* **Search functionality** – Find users by name +* **User status** – Online/offline indicators +* **Tap to chat** – Start conversation with any user +* **User avatars** – Profile pictures + +### **4. Groups Tab** + +Manage and join groups: + +* **CometChatGroups** – Shows all groups +* **Group types** – Public, private, password-protected +* **Member count** – Number of participants +* **Join groups** – Request to join or join directly +* **Tap to chat** – Open group conversation + +*** + +## **Customization Options** + +### **Custom Tab Icons** + + + +```dart +BottomNavigationBar( + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.forum), + activeIcon: Icon(Icons.forum, size: 28), + label: "Chats", + ), + BottomNavigationBarItem( + icon: Icon(Icons.phone), + activeIcon: Icon(Icons.phone, size: 28), + label: "Calls", + ), + // ... more tabs + ], +) +``` + + + +### **Custom Tab Colors** + + + +```dart +BottomNavigationBar( + selectedItemColor: Colors.blue, + unselectedItemColor: Colors.grey, + backgroundColor: Colors.white, + elevation: 8, + // ... items +) +``` + + + +### **Disable Swipe Between Tabs** + + + +```dart +PageView( + controller: _pageController, + physics: NeverScrollableScrollPhysics(), // Disable swipe + children: [ + // ... pages + ], +) +``` + + + +### **Add More Tabs** + + + +```dart +// Add a Settings tab +children: [ + CometChatConversations(), + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + SettingsScreen(), // New tab +], + +items: [ + // ... existing items + BottomNavigationBarItem( + icon: Icon(Icons.settings), + label: "Settings", + ), +], +``` + + + +### **Custom Tab Styling** + + + +```dart +CometChatConversations( + title: "My Chats", + conversationsStyle: ConversationsStyle( + background: Colors.white, + titleStyle: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), +) +``` + + + +For complete customization options, see: +* [Conversations Customization](/ui-kit/flutter/conversations) +* [Call Logs Customization](/ui-kit/flutter/call-logs) +* [Users Customization](/ui-kit/flutter/users) +* [Groups Customization](/ui-kit/flutter/groups) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** + +## **Common Use Cases** + + + + + + ```dart + BottomNavigationBarItem( + icon: Stack( + children: [ + Icon(Icons.chat), + if (unreadCount > 0) + Positioned( + right: 0, + top: 0, + child: Container( + padding: EdgeInsets.all(2), + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(10), + ), + constraints: BoxConstraints( + minWidth: 16, + minHeight: 16, + ), + child: Text( + '$unreadCount', + style: TextStyle( + color: Colors.white, + fontSize: 10, + ), + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + label: "Chat", + ) + ``` + + + + + + + + ```dart + // Save selected tab to shared preferences + void _onItemTapped(int index) async { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('selected_tab', index); + } + + // Load selected tab on init + @override + void initState() { + super.initState(); + _loadSelectedTab(); + } + + Future _loadSelectedTab() async { + final prefs = await SharedPreferences.getInstance(); + final savedIndex = prefs.getInt('selected_tab') ?? 0; + setState(() => _selectedIndex = savedIndex); + _pageController.jumpToPage(savedIndex); + } + ``` + + + + + + + + ```dart + void _onItemTapped(int index) { + setState(() => _selectedIndex = index); + _pageController.animateToPage( + index, + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + } + ``` + + + + + + + + ```dart + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async { + if (_selectedIndex != 0) { + // Go back to first tab instead of exiting + _onItemTapped(0); + return false; + } + return true; // Allow exit + }, + child: Scaffold( + // ... rest of widget + ), + ); + } + ``` + + + + + +*** + +## **Best Practices** + + + + Always dispose of controllers to prevent memory leaks: + + + + ```dart + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + ``` + + + + + + For 4+ tabs, use fixed type to prevent shifting: + + + + ```dart + BottomNavigationBar( + type: BottomNavigationBarType.fixed, // Prevents label shifting + // ... rest of properties + ) + ``` + + + + + + Load tab content only when needed: + + + + ```dart + PageView( + controller: _pageController, + children: [ + _selectedIndex == 0 ? CometChatConversations() : SizedBox(), + _selectedIndex == 1 ? CometChatCallLogs() : SizedBox(), + _selectedIndex == 2 ? CometChatUsers() : SizedBox(), + _selectedIndex == 3 ? CometChatGroups() : SizedBox(), + ], + ) + ``` + + + + + + Refresh tab content when switching: + + + + ```dart + void _onItemTapped(int index) { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + + // Refresh current tab + _refreshTab(index); + } + + void _refreshTab(int index) { + // Implement refresh logic for each tab + switch (index) { + case 0: + // Refresh conversations + break; + case 1: + // Refresh call logs + break; + // ... etc + } + } + ``` + + + + -### **Enhance the User Experience** +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Customize the conversation list appearance and behavior + + + Configure call history and calling features + + + Manage user lists and group memberships + + + Customize colors, fonts, and styles to match your brand + + *** diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index d919825e9..1b53fde4e 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -1,48 +1,127 @@ --- title: "Getting Started With CometChat Flutter UI Kit" sidebarTitle: "Getting Started" +description: "Install and configure CometChat Flutter UI Kit with step-by-step setup, initialization, and authentication guide" --- -CometChat UI Kit for Flutter is a package of pre-assembled UI elements crafted to streamline the creation of an in-app chat equipped with essential messaging functionalities. Our UI Kit presents options for light and dark themes, diverse fonts, colors, and extra customization capabilities. +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** + +```bash +# Install +flutter pub add cometchat_chat_uikit +flutter pub add cometchat_calls_uikit # Optional: for calling + +# Initialize (run once at app start) +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..authKey = "YOUR_AUTH_KEY" + ..subscriptionType = CometChatSubscriptionType.allUsers + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() +).build(); +await CometChatUIKit.init(uiKitSettings: uiKitSettings); + +# Login (after init) +await CometChatUIKit.login("cometchat-uid-1"); +``` -CometChat UI Kit supports both one-to-one and group conversations. Follow the guide below to initiate conversations from scratch using CometChat Flutter UI Kit. +**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys -{/* - - */} +**Integration Paths:** +- **Conversation List + Message** → [flutter-conversation](/ui-kit/flutter/flutter-conversation) +- **One-to-One Chat** → [flutter-one-to-one-chat](/ui-kit/flutter/flutter-one-to-one-chat) +- **Tab-Based Chat** → [flutter-tab-based-chat](/ui-kit/flutter/flutter-tab-based-chat) + + +The **CometChat UI Kit for Flutter** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI widgets**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. + +With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat Flutter UI Kit. -## Prerequisites +*** + +## **Prerequisites** + +Before installing the **CometChat UI Kit for Flutter**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: + +* **User Management** +* **Group Chat & Messaging** +* **Voice & Video Calling** +* **Real-time Notifications** + + + +To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: + +1. **App ID** +2. **Auth Key** +3. **Region** + +Ensure you have these details ready before proceeding with the installation and configuration. + + + +*** + +## **Register & Set Up CometChat** + +Follow these steps to **register on CometChat** and **set up your development environment**. + +### **Step 1: Register on CometChat** + +To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. + +🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** + +### **Step 2: Get Your Application Keys** -Before installing the **UI Kit**, you need to create a CometChat application on the CometChat Dashboard, which includes all the necessary data for a chat service, such as users, groups, calls, and messages. You will require the `App ID`, `AuthKey`, and `Region` of your CometChat application when initializing the SDK. +After registering, create a **new app** and retrieve your **authentication details**: -**i. Register on CometChat** +1. Navigate to the **QuickStart** or **API & Auth Keys** section. -* You need to register on the **CometChat Dashboard** first. [Click here to sign up](https://app.cometchat.com/login). +2. Note down the following keys: -**ii. Get Your Application Keys** + * **App ID** + * **Auth Key** + * **Region** -* Create a **new app** -* Head over to the **QuickStart** or **API & Auth Keys section** and note the **App ID**, **Auth Key**, and **Region**. + -> Each CometChat application can be integrated with a single client app. Within the same application, users can communicate with each other across all platforms, whether they are on mobile devices or on the web. +Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **iOS, Android, and web**. -**iii. Platform & IDE Setup** + -* Flutter installed on your system. -* Android Studio or VS Code with configured Flutter/Dart plugins. -* Xcode & Pod (CocoaPods) for iOS -* An iOS device or emulator with iOS 12.0 or above. -* Android device or emulator with Android version 5.0 or above. +### **Step 3: Set Up Your Development Environment** -## Getting Started +Ensure your system meets the following **prerequisites** before proceeding with integration. -### **Step 1: Create Flutter application project** +**System Requirements:** -To get started, create a new flutter application project. +* **Flutter** installed on your system (Flutter 3.0 or higher recommended) +* **Android Studio** or **VS Code** with configured Flutter/Dart plugins +* **Xcode & CocoaPods** for iOS development +* An **iOS device or simulator** with iOS 12.0 or above +* An **Android device or emulator** with Android version 5.0 (API level 21) or above + +*** + +## **Getting Started** + +### **Step 1: Create Flutter Application Project** + +To get started, create a new Flutter application project: + +```bash +flutter create my_chat_app +cd my_chat_app +``` *** @@ -53,46 +132,57 @@ To get started, create a new flutter application project. To use this UI Kit in your Flutter project, you'll need to add the following dependency to the dependencies section of your `pubspec.yaml` file: ```yaml pubspec.yaml +dependencies: + flutter: + sdk: flutter + cometchat_chat_uikit: ^5.2.8 - cometchat_calls_uikit: ^5.0.12 #Optional: Include if you're using Audio/Video Calling + cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling ``` -Final `pubspec.yaml` +**Final `pubspec.yaml` Example:** ```yaml pubspec.yaml - name: getting_started - description: "A new Flutter project." +name: my_chat_app +description: "A Flutter chat application using CometChat UI Kit" - publish_to: 'none' # Remove this line if you wish to publish to pub.dev +publish_to: 'none' - version: 1.0.0+1 +version: 1.0.0+1 - environment: - sdk: ^3.5.3 +environment: + sdk: ^3.5.3 - dependencies: - flutter: - sdk: flutter +dependencies: + flutter: + sdk: flutter - cometchat_chat_uikit: ^5.2.8 - cometchat_calls_uikit: ^5.0.12 #Optional: Include if you're using Audio/Video Calling - cupertino_icons: ^1.0.8 + cometchat_chat_uikit: ^5.2.8 + cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling + cupertino_icons: ^1.0.8 - dev_dependencies: - flutter_test: - sdk: flutter +dev_dependencies: + flutter_test: + sdk: flutter - flutter_lints: ^4.0.0 + flutter_lints: ^4.0.0 - flutter: - uses-material-design: true +flutter: + uses-material-design: true +``` + +After updating `pubspec.yaml`, run: + +```bash +flutter pub get ``` *** **2. Android App Setup** -To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**.\ +To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**. + Update the `minSdkVersion` in your Android project configuration, located at `android/app/build.gradle`: ```gradle build.gradle @@ -108,20 +198,34 @@ android { **3. Update iOS Podfile** -In your Podfile (located at ios/Podfile), update the minimum iOS version your project supports to 12.0: +In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: ```ruby Podfile platform :ios, '12.0' ``` +After updating, run: + +```bash +cd ios +pod install +cd .. +``` + *** -4. Import CometChat UIKit In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your main.dart file: +**4. Import CometChat UIKit** + +In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your `main.dart` file: + + ```dart main.dart - import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling ``` + + *** @@ -129,64 +233,153 @@ platform :ios, '12.0' Before using any features from the CometChat UI Kit, initialize it with your app credentials. -1. **Import & Configure UIKit Settings** You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. - - **Example Configuration File:** - - ```dart cometchat_config.dart - class CometChatConfig { - static const String appId = "APP_ID"; // Replace with your App ID - static const String region = "REGION"; // Replace with your App Region - static const String authKey = "AUTH_KEY"; // Replace with your Auth Key - } - ``` - - **Initialization Code:** - - ```dart main.dart - import 'cometchat_config.dart'; - - UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..region = CometChatConfig.region - ..appId = CometChatConfig.appId - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling - ).build(); - - CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) async { - debugPrint('CometChat Initialized'); - // You can now log in the user - }, - onError: (error) { - debugPrint('CometChat Initialization error'); - }, - ); - ``` - - > Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding. + + +You must call `CometChatUIKit.init()` before rendering any UI Kit widgets or calling any SDK methods. Initialization must complete before login. + + + +**1. Import & Configure UIKit Settings** + +You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. + +**Example Configuration File:** + + + +```dart cometchat_config.dart +class CometChatConfig { + static const String appId = "APP_ID"; // Replace with your App ID + static const String region = "REGION"; // Replace with your App Region + static const String authKey = "AUTH_KEY"; // Replace with your Auth Key +} +``` + + + +**Initialization Code:** + + + +```dart main.dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional +import 'cometchat_config.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'CometChat UI Kit', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const Home(), + ); + } +} + +class Home extends StatelessWidget { + const Home({super.key}); + + Future _initializeAndLogin() async { + final settings = UIKitSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..appId = CometChatConfig.appId + ..region = CometChatConfig.region + ..authKey = CometChatConfig.authKey + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if using Audio/Video Calling + + await CometChatUIKit.init( + uiKitSettings: settings.build(), + onSuccess: (successMessage) { + debugPrint('✅ CometChat Initialized'); + }, + onError: (error) { + debugPrint('❌ CometChat Initialization error: $error'); + }, + ); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _initializeAndLogin(), + builder: (ctx, snap) { + if (snap.connectionState != ConnectionState.done) { + return const Scaffold( + body: SafeArea( + child: Center(child: CircularProgressIndicator()), + ), + ); + } + if (snap.hasError) { + return Scaffold( + body: SafeArea( + child: Center( + child: Text( + 'Error starting app:\n${snap.error}', + textAlign: TextAlign.center, + ), + ), + ), + ); + } + return const LoginScreen(); // Navigate to your login screen + }, + ); + } +} +``` + + + + + +Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding sensitive information. + + + + + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + *** ### **Step 4: Login to UI Kit** -Once the UI Kit is initialized, authenticate your user using the `login()` method. You’ll receive a `User` object upon success. +Once the UI Kit is initialized, authenticate your user using the `login()` method. You'll receive a `User` object upon success. + + ```dart main.dart CometChatUIKit.login( - "cometchat-uid-1", // Replace with a valid UID + "cometchat-uid-1", // Replace with a valid UID onSuccess: (user) { - debugPrint('CometChat LoggedIn success'); + debugPrint('✅ CometChat LoggedIn success: ${user.name}'); + // Navigate to your chat screen }, onError: (error) { - debugPrint('CometChat LoggedIn error'); + debugPrint('❌ CometChat LoggedIn error: $error'); }, ); ``` + + + +**Test Users:** You can test using any of the following pre-generated users: @@ -196,47 +389,99 @@ You can test using any of the following pre-generated users: * `cometchat-uid-4` * `cometchat-uid-5` -> For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). + + +For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). -#### **Example: Initialization and Login Combined** + +**Example: Initialization and Login Combined** + + + ```dart main.dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; import 'cometchat_config.dart'; -void main() { - UIKitSettings uiKitSettings = (UIKitSettingsBuilder() +void main() => runApp(const MyApp()); + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'CometChat UI Kit', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const Home(), + ); + } +} + +class Home extends StatelessWidget { + const Home({super.key}); + + Future _initializeAndLogin() async { + final settings = UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true - ..region = CometChatConfig.region ..appId = CometChatConfig.appId + ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling - ).build(); - - CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) async { - debugPrint('CometChat Initialized'); - - CometChatUIKit.login( - "cometchat-uid-1", - onSuccess: (user) { - debugPrint('CometChat LoggedIn success'); - }, - onError: (error) { - debugPrint('CometChat LoggedIn error'); - }, - ); - }, - onError: (error) { - debugPrint('CometChat Initialization error'); - }, - ); + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension(); + + await CometChatUIKit.init(uiKitSettings: settings.build()); + await CometChatUIKit.login( + 'cometchat-uid-1', + onSuccess: (_) => debugPrint('✅ Login Successful'), + onError: (err) => throw Exception('Login Failed: $err'), + ); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _initializeAndLogin(), + builder: (ctx, snap) { + if (snap.connectionState != ConnectionState.done) { + return const Scaffold( + body: SafeArea( + child: Center(child: CircularProgressIndicator()), + ), + ); + } + if (snap.hasError) { + return Scaffold( + body: SafeArea( + child: Center( + child: Text( + 'Error starting app:\n${snap.error}', + textAlign: TextAlign.center, + ), + ), + ), + ); + } + return const ConversationsPage(); // Your main chat screen + }, + ); + } } ``` + + + + -> Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. +Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. + + *** @@ -252,12 +497,12 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation. -* **One-to-One & Group Chats** – Built-in support for private and group conversations. -* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events. -* **State Persistence** – Session-aware updates across screens and app restarts. -* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes. -* **Extremely Customizable** – Modify styles, themes, and components easily. +* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation +* **One-to-One & Group Chats** – Built-in support for private and group conversations +* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events +* **State Persistence** – Session-aware updates across screens and app restarts +* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes +* **Extremely Customizable** – Modify styles, themes, and components easily @@ -265,9 +510,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* You want a **clean navigation experience** for multiple chat sessions. -* Your Flutter app supports **both direct and group messaging**. -* You prefer a **stack-based routing approach** using `Navigator`. +* You want a **clean navigation experience** for multiple chat sessions +* Your Flutter app supports **both direct and group messaging** +* You prefer a **stack-based routing approach** using `Navigator` [Integrate Conversation List + Message View](./flutter-conversation) @@ -279,11 +524,11 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Single Screen Chat** – Use `CometChatMessages` widget with preselected user/group. -* **No Conversation List** – Start with just the message screen. -* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication. -* **Simplified Routing** – Pass user/group as route argument. -* **Real-Time Communication** – Auto-updates messages and statuses. +* **Single Screen Chat** – Use `CometChatMessageList` widget with preselected user/group +* **No Conversation List** – Start with just the message screen +* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication +* **Simplified Routing** – Pass user/group as route argument +* **Real-Time Communication** – Auto-updates messages and statuses @@ -291,9 +536,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* Your chat starts **from a specific user or group ID**. -* You want a **clean, focused chat interface**. -* Use case involves **support, onboarding, or one-time messages**. +* Your chat starts **from a specific user or group ID** +* You want a **clean, focused chat interface** +* Use case involves **support, onboarding, or one-time messages** [Integrate One-to-One / Group Chat](./flutter-one-to-one-chat) @@ -305,11 +550,11 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features. -* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets. -* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices. -* **Scalable** – Add new tabs like Profile, Notifications, or Help later. -* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate. +* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features +* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets +* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices +* **Scalable** – Add new tabs like Profile, Notifications, or Help later +* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate @@ -317,9 +562,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* You need a **full-featured chat solution** in one UI. -* Your users require **structured navigation** between modules. -* Use cases like **support apps, business messengers, or social platforms**. +* You need a **full-featured chat solution** in one UI +* Your users require **structured navigation** between modules +* Use cases like **support apps, business messengers, or social platforms** [Integrate Tab-Based Chat](./flutter-tab-based-chat) @@ -327,31 +572,39 @@ Integrate a conversation view that suits your application's **UX requirements**. ## **Build Your Own Chat Experience** -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. +**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app's design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. **Recommended for:** -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. +* Apps that require **a fully customized chat experience** +* Developers who want to **extend functionalities and modify UI components** +* Businesses integrating chat seamlessly into **existing platforms** **Key Areas to Explore:** -* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development +* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities +* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design +* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding +* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience *** ## **Next Steps** -Now that you’ve selected your **chat experience**, proceed to the **integration guide**: - -* **[Integrate Conversation List + Message](/ui-kit/flutter/flutter-conversation)** -* **[Integrate One-to-One Chat](/ui-kit/flutter/flutter-one-to-one-chat)** -* **[Integrate Tab-Based Chat](/ui-kit/flutter/flutter-tab-based-chat)** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** + + + Two-panel layout with conversation list and message view + + + Direct messaging interface for focused conversations + + + Multi-tab experience with chats, calls, users, and groups + + + Adjust colors, fonts, and styles to match your brand + + *** diff --git a/ui-kit/flutter/guide-block-unblock-user.mdx b/ui-kit/flutter/guide-block-unblock-user.mdx index 125c6185f..5a7eed5c4 100644 --- a/ui-kit/flutter/guide-block-unblock-user.mdx +++ b/ui-kit/flutter/guide-block-unblock-user.mdx @@ -1,8 +1,48 @@ --- title: "Implementing Block/Unblock User in Flutter with CometChat UIKit" sidebarTitle: "Block/Unblock User" +description: "Enable users to block and unblock other users for privacy and spam control" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Block a user +await CometChatUIKit.blockUsers([user.uid]); + +// Unblock a user +await CometChatUIKit.unblockUsers([user.uid]); + +// Navigate to user info screen +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometChatUserInfo(user: tappedUser), + ), +); + +// Check block status +if (user.blockedByMe) { + // Show unblock button +} else { + // Show block button +} +``` + +**Key Components & Methods:** +- `CometChatUIKit.blockUsers()` → SDK method to block users +- `CometChatUIKit.unblockUsers()` → SDK method to unblock users +- `CometChatUserInfo` → User profile screen +- `User.blockedByMe` → Block status property (SDK) + +**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) + + + Enable users to block and unblock other users in your Flutter chat app by integrating CometChat’s `blockUsers` and `unblockUsers` methods with a simple UI. ## Overview @@ -125,22 +165,19 @@ This guide covers only user-to-user blocking. For group moderation (ban or remov | Unblock User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.unblockUsers([...])` | | Group Management | [sample_app/lib/group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | Group-related actions (not blocking) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage user lists + + + View messages with blocked user handling + + + Learn about group moderation features + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-call-log-details.mdx b/ui-kit/flutter/guide-call-log-details.mdx index 14ee8bc67..e7393ed16 100644 --- a/ui-kit/flutter/guide-call-log-details.mdx +++ b/ui-kit/flutter/guide-call-log-details.mdx @@ -1,8 +1,45 @@ --- title: "Managing & Viewing Call Logs in Your Flutter Chat App" sidebarTitle: "Call Logs" +description: "Display call history and detailed call information in your Flutter chat app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Display call logs list +CometChatCallLogs( + onItemClick: (callLog) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatCallLogDetails(callLog: callLog), + ), + ); + }, +); + +// Show call log details +CometChatCallLogDetails( + callLog: callLog, +); +``` + +**Key Components:** +- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) +- `CometChatCallLogDetails` → Call details screen +- `CallLog` → Call log data model (SDK) + +**Sample Implementation:** [call_log_details/cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) + +**Requirements:** Call functionality enabled in CometChat dashboard, microphone/camera permissions + + + Learn how to integrate and customize CometChat’s `CometChatCallLogs` and `CometChatCallLogDetails` components to display call history and detailed call information in your Flutter chat app. ## Overview @@ -116,22 +153,19 @@ CometChatCallLogDetails( | Display call logs | `CometChatCallLogs` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | | Show call details | `CometChatCallLogDetails(callLog)` | [`call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Learn more about the Call Logs component + + + Explore all calling capabilities + + + Add call buttons to your chat interface + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-group-chat.mdx b/ui-kit/flutter/guide-group-chat.mdx index 958fdd469..cdc640522 100644 --- a/ui-kit/flutter/guide-group-chat.mdx +++ b/ui-kit/flutter/guide-group-chat.mdx @@ -1,8 +1,55 @@ --- title: "Managing Groups in Flutter UI Kit" sidebarTitle: "Groups" +description: "Create groups, manage members, assign roles, and transfer ownership in your Flutter chat app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Create a group +await CometChat.createGroup( + group: Group( + guid: groupId, + name: groupName, + type: groupType, + password: groupPassword, + ), +); + +// Join a group +await CometChat.joinGroup(guid: groupId, groupType: groupType, password: password); + +// Add members +CometChatAddMembers(group: group); + +// Ban/unban members +CometChatBannedMembers(group: group); + +// Change member scope +CometChatChangeScope(group: group, user: user); + +// Transfer ownership +CometChatTransferOwnership(group: group); +``` + +**Key Components:** +- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) +- `CometChatCreateGroup` → Group creation UI +- `CometChatGroupInfo` → Group info screen +- `CometChatAddMembers` → Add members UI +- `CometChatBannedMembers` → Banned members management +- `CometChatTransferOwnership` → Ownership transfer UI +- `JoinProtectedGroupUtils` → Password group join utility (sample app) + +**Sample Implementation:** [group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) + + + Learn how to create groups, join public/password groups, manage members, ban users, update roles, and transfer group ownership using CometChat UIKit for Flutter. ## Overview @@ -203,18 +250,19 @@ CometChatTransferOwnership( | Change scope | `CometChatChangeScope` | `group_info/cometchat_group_info.dart` | | Transfer ownership | `CometChatTransferOwnership` | `transfer_ownership/cometchat_transfer_ownership.dart` | -## Next Steps & Further Reading - - - -Explore the working implementation in our official sample app. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - -Get the full UI Kit source for deeper customization. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - +## Next Steps + + + + Learn more about the Groups component + + + Display and manage group members + + + View group conversations + + + Explore other implementation guides + diff --git a/ui-kit/flutter/guide-message-agentic-flow.mdx b/ui-kit/flutter/guide-message-agentic-flow.mdx index acbb37885..545f64be1 100644 --- a/ui-kit/flutter/guide-message-agentic-flow.mdx +++ b/ui-kit/flutter/guide-message-agentic-flow.mdx @@ -1,8 +1,57 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" +description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in your Flutter app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Check if user is an AI agent +bool isUserAgentic() { + return widget.user?.role == AIConstants.aiRole; +} + +// AI Assistant chat screen +AIAssistantChatScreen( + user: aiUser, + group: group, + parentMessage: message, + isHistory: true, +); + +// AI chat history +CometChatAIAssistantChatHistory( + user: widget.user, + group: widget.group, + onNewChatButtonClicked: () => onNewChatClicked(true), + onMessageClicked: (message) => navigateToThread(message), +); + +// Custom AI bubble styling +CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + border: Border.all(color: Colors.blueAccent), + textColor: Color(0xFF141414), +); +``` + +**Key Components:** +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) +- `CometChatMessageHeader` → [Docs](/ui-kit/flutter/message-header) +- `CometChatAIAssistantChatHistory` → [Docs](/ui-kit/flutter/ai-assistant-chat-history) +- `CometChatAiAssistantBubbleStyle` → AI bubble styling +- `AIConstants.aiRole` → AI role constant + +**Sample Implementation:** Custom AI Assistant chat screen (see guide for full implementation) + + + Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v5 with AI Agent integration: - **AI Assistant Chat History** @@ -396,4 +445,23 @@ class MyApp extends StatelessWidget { | Feature | Implementation | UI Component | |:-----------------------|:-------------------------------------------- |:------------------------| | AI Chat | `AIAssistantChatScreen` | Full chat screen | -| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | \ No newline at end of file +| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | + +--- + +## Next Steps + + + + Explore all AI-powered features + + + Learn about message display and management + + + Compose messages with AI assistance + + + Explore other implementation guides + + \ No newline at end of file diff --git a/ui-kit/flutter/guide-message-privately.mdx b/ui-kit/flutter/guide-message-privately.mdx index ed8f83321..245dbbf32 100644 --- a/ui-kit/flutter/guide-message-privately.mdx +++ b/ui-kit/flutter/guide-message-privately.mdx @@ -1,8 +1,50 @@ --- title: "Message a User Privately from a Group Chat" sidebarTitle: "Message Privately" +description: "Initiate private one-on-one chats with group members directly from group chat" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Navigate to user info from group chat +IconButton( + icon: Icon(Icons.info_outline), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUserInfo(user: user), + ), + ); + }, +); + +// Start private chat with user +ElevatedButton( + onPressed: () { + PageManager().navigateToMessages( + context: context, + user: user, + ); + }, + child: Text('Message'), +); +``` + +**Key Components:** +- `CometChatUserInfo` → User profile screen +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `PageManager` → Navigation utility (sample app) + +**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) + + + Learn how to initiate a private one-on-one chat with a group member directly from a group chat screen. ## Overview @@ -103,22 +145,19 @@ ElevatedButton( | Message user | `PageManager.navigateToMessages` | [`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | | Access from group | Avatar/IconButton | [`lib/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage group lists + + + View and manage group members + + + Display messages in private chats + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-new-chat.mdx b/ui-kit/flutter/guide-new-chat.mdx index 8ec4b682f..c337f3fce 100644 --- a/ui-kit/flutter/guide-new-chat.mdx +++ b/ui-kit/flutter/guide-new-chat.mdx @@ -1,8 +1,52 @@ --- title: "New Chat / Create Conversation in Your Flutter Chat App" sidebarTitle: "New Chat" +description: "Enable users to start one-on-one or group chats with a searchable contact list" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Add avatar menu with "Create Conversation" option +PopupMenuButton( + icon: CometChatAvatar( + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + itemBuilder: (context) => [ + PopupMenuItem(value: '/Create', child: Text("Create Conversation")), + ], + onSelected: (value) { + if (value == '/Create') { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatContacts()), + ); + } + }, +); + +// Handle user/group selection +CometChatUsers( + onItemTap: (context, user) => PageManager.navigateToMessages(context: context, user: user), +); +``` + +**Key Components:** +- `CometChatAvatar` → Avatar display widget +- `CometChatContacts` → Contact selection screen +- `CometChatUsers` → [Docs](/ui-kit/flutter/users) +- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) +- `CometChatContactsController` → Tab switching controller (sample app) + +**Sample Implementation:** [contacts/cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) + + + Enable users to start one-on-one or group chats by integrating CometChat’s avatar menu and `CometChatContacts` screen, providing a seamless flow from the dashboard to a conversation. ## Overview @@ -146,22 +190,19 @@ void _onItemTap({required BuildContext context, User? user, Group? group}) { | Handle selection | `_onItemTap` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | | Navigate to chat | `PageManager.navigateToMessages` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and search user lists + + + Display and manage group lists + + + View and manage conversation history + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 609ddfba0..896324117 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -1,8 +1,30 @@ --- -title: "Overview" +title: "Guides Overview" sidebarTitle: "Overview" +description: "Task-oriented feature guides for implementing specific capabilities in the Flutter UI Kit" --- -> This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. + +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Available implementation guides for Flutter UI Kit: + +**Feature Guides:** +- [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) → `CometChatThreadedMessageList` +- [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` +- [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` +- [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` +- [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` +- [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` +- [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` + +**Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) + +Each guide provides end-to-end implementation with code examples and component references. + + +This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. ## When to Use These Guides @@ -18,6 +40,25 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [Message Privately](/ui-kit/flutter/guide-message-privately) | Start a direct 1:1 chat from a profile or list; optionally send an initial message to surface the conversation. | | [New Chat](/ui-kit/flutter/guide-new-chat) | Offer a unified discovery screen for users & groups and launch new chats quickly. | | [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) | Enable threaded replies: open parent message context, browse replies, and compose within a focused thread. | -| [Call Log Details](/ui-kit/flutter/guide-call-log-details) | Provide a post‑call details screen with metadata, participants, history, and recordings for audit & support. | +| [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) | Integrate AI agents with chat history, contextual responses, and seamless handoffs. | Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. + +--- + +## Next Steps + + + + Set up the Flutter UI Kit in your project + + + Explore all available UI components + + + Learn about core chat features + + + View complete working examples + + diff --git a/ui-kit/flutter/guide-threaded-messages.mdx b/ui-kit/flutter/guide-threaded-messages.mdx index 7e140d86a..510f2dc63 100644 --- a/ui-kit/flutter/guide-threaded-messages.mdx +++ b/ui-kit/flutter/guide-threaded-messages.mdx @@ -1,8 +1,49 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" +description: "Enable threaded replies in your Flutter chat app with focused sub-conversations" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Enable thread replies in message list +CometChatMessageList( + onThreadRepliesClick: (BaseMessage message) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometChatThread(parentMessage: message), + ), + ); + }, +); + +// Display threaded messages +CometChatThreadedMessageList( + parentMessageId: parentMessage.id, +); + +// Send threaded reply +CometChatMessageComposer( + parentMessageId: parentMessage.id, +); +``` + +**Key Components:** +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `CometChatThreadedMessageList` → Displays threaded messages +- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) +- `CometChatThreadedHeader` → [Docs](/ui-kit/flutter/threaded-messages-header) + +**Sample Implementation:** [thread_screen/cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) + + + Enhance your Flutter chat app with threaded messaging by integrating CometChat’s `CometChatThreadedMessageList` and `CometChatMessageList` components to reply to messages in threads and view focused sub-conversations seamlessly. ## Overview @@ -153,22 +194,19 @@ Ensures only relevant threaded messages are shown. | Send threaded message | `CometChatMessageComposer(parentMessageId)` | | Fetch thread replies | `MessagesRequestBuilder.setParentMessageId` | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage conversation messages + + + Compose and send messages with threading support + + + Display thread context and parent message + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index e1d04635d..ea11a9337 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -1,8 +1,39 @@ --- title: "CometChat UI Kit For Flutter" sidebarTitle: "Overview" +description: "Prebuilt Flutter widgets for chat, calling, and messaging with modular, customizable components for iOS and Android" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Install +flutter pub add cometchat_chat_uikit + +// Initialize (run once at app start) +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..subscriptionType = CometChatSubscriptionType.allUsers +).build(); +CometChatUIKit.init(uiKitSettings: uiKitSettings); + +// Login +CometChatUIKit.login("UID"); + +// Show conversations +CometChatConversations() + +// Show messages +CometChatMessageList(user: user) // or group: group +``` + +**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + + The **CometChat UI Kit** for Flutter is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI widgets** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. *** @@ -60,12 +91,91 @@ To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) g *** -## **Next Steps for Developers** +## **Key Features** + +### **Comprehensive Widget Library** + +The UI Kit includes a complete set of widgets for building chat experiences: + +* **CometChatConversations** – Display recent conversations with users and groups +* **CometChatMessageList** – Full-featured messaging interface with real-time updates +* **CometChatMessageComposer** – Input field for sending text, media, and attachments +* **CometChatMessageHeader** – Conversation header with user/group info and actions +* **CometChatUsers** – Browse and search users +* **CometChatGroups** – Manage and join groups +* **CometChatGroupMembers** – View and manage group participants +* **Calling Components** – Voice and video calling widgets + +### **Built-in Chat Logic** + +Each widget comes with integrated CometChat SDK functionality: + +* Real-time message delivery and updates +* Typing indicators and read receipts +* User presence and status +* Message reactions and threading +* File and media sharing +* Push notifications support + +### **Extensive Customization** + +Tailor the UI to match your brand: + +* **Theming** – Customize colors, fonts, and spacing +* **Styling** – Override default styles for any component +* **Templates** – Create custom message bubble layouts +* **Formatters** – Add mentions, shortcuts, and URL previews +* **Configurations** – Control feature availability and behavior + +*** + +## **Architecture** + +The CometChat UI Kit for Flutter is built on top of the [CometChat Flutter SDK](/sdk/flutter/overview) and follows a modular architecture: + +``` +Your Flutter App + ↓ +CometChat UI Kit (Widgets) + ↓ +CometChat Flutter SDK (Core Chat Logic) + ↓ +CometChat Platform +``` + +This layered approach means: + +* **Widgets handle UI** – Rendering, user interactions, animations +* **SDK handles logic** – Message delivery, real-time events, data management +* **Platform handles infrastructure** – Scalability, reliability, security + +*** + +## **Supported Platforms** + +The Flutter UI Kit works seamlessly across: -1. **Learn the Basics** – [Key Concepts](/fundamentals/key-concepts). -2. **Follow the Setup Guide** – [Flutter Integration Guide](/ui-kit/flutter/getting-started) -3. **Customize UI** – Adjust styles, themes, and widgets. -4. **Test & Deploy** – Run tests and launch your chat app. +* **iOS** – iPhone and iPad (iOS 12.0+) +* **Android** – Phones and tablets (API level 21+) + +*** + +## **Next Steps** + + + + Install the UI Kit and build your first chat screen + + + Understand CometChat's core concepts and terminology + + + Explore all available widgets and their capabilities + + + Customize colors, fonts, and styles to match your brand + + *** @@ -73,27 +183,35 @@ To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) g Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. - - + + Fully functional sample applications to accelerate your development. -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) +View on GitHub - + Access the complete UI Kit source code on GitHub. -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) +View on GitHub + + + + + +UI design resources for customization and prototyping. + +View on Figma *** -## **💡 Need Help?** +## **Need Help?** If you need assistance, check out: From ae7404bfd11481fdfdd5b7327d15154242146d6a Mon Sep 17 00:00:00 2001 From: Anshuman-cometchat Date: Thu, 12 Feb 2026 16:01:17 +0530 Subject: [PATCH 02/32] fix : removed code snippet --- ui-kit/flutter/extensions.mdx | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 24d3cc1d9..6a8a01c01 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -152,19 +152,6 @@ await CometChatUIKit.init(uiKitSettings: uiKitSettings); -To disable all extensions, pass an empty array: - - - -```dart -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..extensions = [] // Disable all extensions -).build(); -``` - - *** From cacae38d8cd664d45064cd5c142a39af78f9b7a9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 14:25:38 +0530 Subject: [PATCH 03/32] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 96adadbc8..19273fa01 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .DS_Store .kiro/ +/codebase From ce931013c36f8b729626b6db6c98be5df5ed36df Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 14:49:44 +0530 Subject: [PATCH 04/32] adds missing methods --- ui-kit/flutter/conversations.mdx | 7 +++++++ ui-kit/flutter/message-list.mdx | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index 32dc1707c..adaac93ab 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -403,6 +403,13 @@ List of Poperties exposed by `CometChatConversations` | **Disable Sound For Messages** | Disable sound for messages | `disableSoundForMessages: bool` | | **Mention All Label Id** | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | `mentionAllLabelId: String` | | **Mention All Label** | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | `mentionAllLabel: String` | +| **Hide Search** | Hides the search bar in the app bar | `hideSearch: bool` | +| **Search Read Only** | Makes the search box read-only | `searchReadOnly: bool` | +| **On Search Tap** | Callback triggered when the search box is tapped | `onSearchTap: GestureTapCallback` | +| **Search Box Icon** | Custom prefix icon for the search box | `searchBoxIcon: Widget` | +| **Search Padding** | Provides padding for the search box | `searchPadding: EdgeInsetsGeometry` | +| **Search Content Padding** | Provides padding for the search box content | `searchContentPadding: EdgeInsetsGeometry` | +| **Date Time Formatter Callback** | Callback that can be used to format the date and time | `dateTimeFormatterCallback: DateTimeFormatterCallback` | ### Advanced diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index 097a01648..aaf056e49 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -451,6 +451,10 @@ Below is a list of customizations along with corresponding code snippets: | `startFromUnreadMessages` | `bool?` | Starts the message list from the first unread message. | | `showMarkAsUnreadOption` | `bool?` | show the visibility of the "Mark unread" option in the message actions menu. | | `newMessageIndicatorView` | `Widget?` | Custom view for the unread message indicator. | +| `enableConversationSummary` | `bool?` | Enables conversation summary generation. | +| `generateConversationSummary` | `bool?` | Triggers conversation summary generation. | +| `hideReplyOption` | `bool?` | Hides the reply message option. | +| `flagReasonLocalizer` | `String Function(String reasonId)?` | Function to localize flag reason IDs to the desired language. | *** From f2bd637ec39b10c416e42c93a573cf5c32d49bf0 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 15:19:28 +0530 Subject: [PATCH 05/32] Update group-members.mdx --- ui-kit/flutter/group-members.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index 8ad574c0b..693396536 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -486,7 +486,7 @@ CometChatGroupMembers( | `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | | `leadingStateView` | `Widget? Function(BuildContext, GroupMember)?` | Widget for the leading section of each group member. | | `titleView` | `Widget? Function(BuildContext, GroupMember)?` | Custom title view for each group member. | -| `hideUserStatus` | `bool?` | Flag to hide the user status indicator on the avatar. | +| `usersStatusVisibility` | `bool?` | Controls visibility of the user status indicator on the avatar (default: true). | | `hideBanMemberOption` | `bool?` | Flag to hide the ban member option. | | `hideKickMemberOption` | `bool?` | Flag to hide the kick member option. | | `hideScopeChangeOption` | `bool?` | Flag to hide the scope change option. | From 4bd9167fb9ee5f16f605b4643ed11cdc52cb9e5d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 16:11:16 +0530 Subject: [PATCH 06/32] updates events and methods --- ui-kit/flutter/events.mdx | 52 +++++++++++++++++++++- ui-kit/flutter/methods.mdx | 88 +++++++++++++++++++++++++++++++++++++- 2 files changed, 137 insertions(+), 3 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 7d7f857d1..4b0a0a06e 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -24,8 +24,8 @@ void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { **Available Event Types:** - **User Events** → Block/Unblock users - **Group Events** → Create, delete, join, leave groups -- **Conversation Events** → Delete conversations -- **Message Events** → Send, edit, delete, receive messages +- **Conversation Events** → Delete conversations, update conversations +- **Message Events** → Send, edit, delete, receive messages, reactions, AI messages - **Call Events** → Outgoing, accepted, rejected, ended calls - **UI Events** → Show/hide panels, active chat changes @@ -212,6 +212,7 @@ The `CometChatConversationEvents` component emits events when the logged-in user **Available Events:** 1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. +2. `ccUpdateConversation`: Triggered when a conversation is updated (e.g., unread count changes). @@ -248,6 +249,11 @@ class _ConversationEventsExampleState extends State w // TODO("Not yet implemented") } + @override + void ccUpdateConversation(Conversation conversation) { + // TODO("Not yet implemented") + } + @override Widget build(BuildContext context) { return const Placeholder(); @@ -288,6 +294,13 @@ class _ConversationEventsExampleState extends State w 21. `onSchedulerMessageReceived`: Triggered when a scheduler message is received. 22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. 23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. +24. `ccReplyToMessage`: Triggered when the logged-in user replies to a message. +25. `onMessagesDeliveredToAll`: Triggered when messages are delivered to all recipients. +26. `onMessagesReadByAll`: Triggered when messages are read by all recipients. +27. `onMessageModerated`: Triggered when a message is moderated. +28. `onAIAssistantMessageReceived`: Triggered when an AI Assistant message is received. +29. `onAIToolResultReceived`: Triggered when an AI tool result is received. +30. `onAIToolArgumentsReceived`: Triggered when AI tool arguments are received. @@ -430,6 +443,41 @@ class _MessageEventsExampleState extends State with CometC // TODO("Not yet implemented") } + @override + void ccReplyToMessage(BaseMessage message, MessageStatus status) { + // TODO("Not yet implemented") + } + + @override + void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessagesReadByAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessageModerated(BaseMessage message) { + // TODO("Not yet implemented") + } + + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + // TODO("Not yet implemented") + } + @override Widget build(BuildContext context) { return const Placeholder(); diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index 9423a6005..d0ab76a2a 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -40,6 +40,10 @@ Here's the table format for the properties available in `UIKitSettings`: | **autoEstablishSocketConnection** | `Boolean` | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default | | **aiFeature** | `List` | Sets the AI Features that need to be added in UI Kit | | **extensions** | `List` | 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 | *** @@ -142,7 +146,47 @@ As a developer, you can dynamically create users on CometChat using the `.create ```dart -CometChat.createUser(userObject, 'authKey', onSuccess: (user) { +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. + + + +```dart +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. + + + +```dart +CometChatUIKit.getLoggedInUser(onSuccess: (user) { // TODO("Not yet implemented") }, onError: (e) { // TODO("Not yet implemented") @@ -446,3 +490,45 @@ CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: *** + +### 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. + + + +```dart +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. + + + +```dart +CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); +``` + + + + + +*** From e46793eaab88869f50a285255fcd580d600b575e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 16:36:28 +0530 Subject: [PATCH 07/32] updates the findings --- ui-kit/flutter/mentions-formatter-guide.mdx | 47 +++++++++++++++++++- ui-kit/flutter/message-template.mdx | 48 ++++++++++++++++++++ ui-kit/flutter/shortcut-formatter-guide.mdx | 49 +++++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/mentions-formatter-guide.mdx b/ui-kit/flutter/mentions-formatter-guide.mdx index aa5989ca2..97a49cfed 100644 --- a/ui-kit/flutter/mentions-formatter-guide.mdx +++ b/ui-kit/flutter/mentions-formatter-guide.mdx @@ -129,7 +129,6 @@ CometChatMessages( | **showLoadingIndicator** | Whether to show a loading indicator during mention search. | `bool? showLoadingIndicator` | | **onSearch** | Callback function to perform search when mention is triggered. | `void Function(String)? onSearch` | | **onError** | Callback function to handle errors during mention search. | `void Function(String)? onError` | -| **theme** | The theme for styling the mentions formatter. | `ThemeData? theme` | | **message** | The message in which mentions are to be formatted. | `String? message` | | **messageBubbleTextStyle** | The text style for the message bubble. | `TextStyle? messageBubbleTextStyle` | | **messageInputTextStyle** | The text style for the message input. | `TextStyle? messageInputTextStyle` | @@ -143,6 +142,11 @@ CometChatMessages( | **mentionsType** | The type of mentions (e.g., user, group). | `MentionsType? mentionsType` | | **onMentionTap** | Callback function to handle mention tap actions. | `void Function(User)? onMentionTap` | | **visibleIn** | Defines where the mentions are visible. | `Set? visibleIn` | +| **style** | Style configuration for customizing mention appearance. | `CometChatMentionsStyle? style` | +| **disableMentions** | Disables mentions in the composer (default: false). | `bool disableMentions` | +| **disableMentionAll** | Controls whether @all mention is enabled (default: false). | `bool disableMentionAll` | +| **mentionAllLabel** | Custom label to display for @all mention. | `String? mentionAllLabel` | +| **mentionAllLabelId** | Custom ID for @all mention (default: "all"). | `String? mentionAllLabelId` | *** @@ -150,6 +154,47 @@ CometChatMessages( For advanced-level customization, you can set the style of the Mentions formatters. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your formatters style. +### @all Mention Feature + +The `CometChatMentionsFormatter` supports mentioning all members in a group using the @all feature. When enabled, users can type `@` followed by "all" (or a custom label) to notify everyone in the group. + + + +```dart +CometChatMessages( + group: group, + messageComposerConfiguration: MessageComposerConfiguration( + textFormatters: [ + CometChatMentionsFormatter( + disableMentionAll: false, // Enable @all mention (default) + mentionAllLabel: "everyone", // Custom label (optional) + mentionAllLabelId: "all", // Custom ID (optional) + ) + ] + ), +) +``` + + + + + +To disable the @all mention feature: + + + +```dart +CometChatMentionsFormatter( + disableMentionAll: true, // Disable @all mention +) +``` + + + + + +*** + ### Composer Mention Text Style Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageComposer](/ui-kit/flutter/message-composer) refer to the below code snippet diff --git a/ui-kit/flutter/message-template.mdx b/ui-kit/flutter/message-template.mdx index ddd2891da..6be26a674 100644 --- a/ui-kit/flutter/message-template.mdx +++ b/ui-kit/flutter/message-template.mdx @@ -154,6 +154,54 @@ MessageTemplate provides you with methods that allow you to alter various proper +9. **Status Info Widget** + + The `statusInfoView` property allows you to assign a custom status info widget to the MessageBubble. By default, it displays the timestamp and read receipt under the content view. + + + + ```dart + cometChatMessageTemplate.statusInfoView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment) { + return const Placeholder(); + }; + ``` + + + + + +10. **Thread Widget** + + The `threadView` property allows you to assign a custom thread widget to the MessageBubble. This is displayed at the bottom of the bubble for threaded messages. + + + + ```dart + cometChatMessageTemplate.threadView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment) { + return const Placeholder(); + }; + ``` + + + + + +11. **Reply Widget** + + The `replyView` property allows you to assign a custom reply widget to the MessageBubble. This is displayed at the top of the bubble when replying to a message. + + + + ```dart + cometChatMessageTemplate.replyView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment, {AdditionalConfigurations? additionalConfigurations}) { + return const Placeholder(); + }; + ``` + + + + + ## Customization Let's dive into how you can use the [properties](#properties) of MessageTemplate to customize an existing template or add a new one to the [MessageList](/ui-kit/flutter/message-list) Widget. diff --git a/ui-kit/flutter/shortcut-formatter-guide.mdx b/ui-kit/flutter/shortcut-formatter-guide.mdx index efa1b70c7..cae25ad9e 100644 --- a/ui-kit/flutter/shortcut-formatter-guide.mdx +++ b/ui-kit/flutter/shortcut-formatter-guide.mdx @@ -189,6 +189,55 @@ void onScrollToBottom(TextEditingController textEditingController) { +6. **Additional Base Class Methods**: The `CometChatTextFormatter` base class provides additional methods you can override for advanced customization: + + + +```dart +/// Override to customize the text style in message bubbles +@override +TextStyle getMessageBubbleTextStyle(BuildContext context, BubbleAlignment? alignment, {bool forConversation = false}) { + return TextStyle( + color: alignment == BubbleAlignment.right ? Colors.white : Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ); +} + +/// Override to build custom attributed text for the input field +@override +List buildInputFieldText({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + required String text, + List? existingAttributes, +}) { + return existingAttributes ?? []; +} + +/// Override to get attributed text for styling in message bubbles +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, { + List? existingAttributes, + Function(String)? onTap, + bool forConversation = false, +}) { + // Custom implementation + return super.getAttributedText(text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap, + forConversation: forConversation); +} +``` + + + + + *** ## Usage From 0059870001fc82c4a893feac715c31bd4a14a409 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:16:23 +0530 Subject: [PATCH 08/32] fixes discrepancies --- docs.json | 25 +- .../flutter/custom-text-formatter-guide.mdx | 398 ++++++++++++++++++ ui-kit/flutter/getting-started.mdx | 10 +- ui-kit/flutter/guide-overview.mdx | 19 +- ui-kit/flutter/guide-search-messages.mdx | 222 ++++++++++ ui-kit/flutter/overview.mdx | 2 +- ui-kit/flutter/troubleshooting.mdx | 211 ++++++++++ ui-kit/flutter/url-formatter-guide.mdx | 300 +++++++++++++ 8 files changed, 1167 insertions(+), 20 deletions(-) create mode 100644 ui-kit/flutter/custom-text-formatter-guide.mdx create mode 100644 ui-kit/flutter/guide-search-messages.mdx create mode 100644 ui-kit/flutter/troubleshooting.mdx create mode 100644 ui-kit/flutter/url-formatter-guide.mdx diff --git a/docs.json b/docs.json index 6fe2a0c07..f12ad9f4f 100644 --- a/docs.json +++ b/docs.json @@ -1861,11 +1861,11 @@ "group": "Chat", "pages": [ "ui-kit/flutter/core-features", - "ui-kit/flutter/extensions" + "ui-kit/flutter/extensions", + "ui-kit/flutter/ai-features" ] }, - "ui-kit/flutter/call-features", - "ui-kit/flutter/ai-features" + "ui-kit/flutter/call-features" ] }, { @@ -1890,6 +1890,7 @@ "ui-kit/flutter/message-header", "ui-kit/flutter/message-list", "ui-kit/flutter/message-composer", + "ui-kit/flutter/message-template", "ui-kit/flutter/threaded-messages-header", "ui-kit/flutter/incoming-call", "ui-kit/flutter/outgoing-call", @@ -1906,14 +1907,6 @@ "ui-kit/flutter/events" ] }, - { - "group": "Advanced", - "pages": [ - "ui-kit/flutter/message-template", - "ui-kit/flutter/mentions-formatter-guide", - "ui-kit/flutter/shortcut-formatter-guide" - ] - }, { "group": "Guides", "pages": [ @@ -1922,9 +1915,14 @@ "ui-kit/flutter/guide-block-unblock-user", "ui-kit/flutter/guide-new-chat", "ui-kit/flutter/guide-message-privately", + "ui-kit/flutter/guide-search-messages", "ui-kit/flutter/guide-call-log-details", "ui-kit/flutter/guide-group-chat", - "ui-kit/flutter/guide-message-agentic-flow" + "ui-kit/flutter/guide-message-agentic-flow", + "ui-kit/flutter/custom-text-formatter-guide", + "ui-kit/flutter/mentions-formatter-guide", + "ui-kit/flutter/url-formatter-guide", + "ui-kit/flutter/shortcut-formatter-guide" ] }, { @@ -1935,7 +1933,8 @@ ] }, "ui-kit/flutter/link/sample", - "ui-kit/flutter/link/changelog" + "ui-kit/flutter/link/changelog", + "ui-kit/flutter/troubleshooting" ] } ] diff --git a/ui-kit/flutter/custom-text-formatter-guide.mdx b/ui-kit/flutter/custom-text-formatter-guide.mdx new file mode 100644 index 000000000..ce0274947 --- /dev/null +++ b/ui-kit/flutter/custom-text-formatter-guide.mdx @@ -0,0 +1,398 @@ +--- +title: "Custom Text Formatter" +description: "Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks in Flutter." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | +| Required setup | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Extend to create custom inline text patterns with regex, styling, and callbacks | +| Features | Text formatting, customizable styles, dynamic text replacement, input field integration | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [ShortCut Formatter](/ui-kit/flutter/shortcut-formatter-guide) \| [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) \| [All Guides](/ui-kit/flutter/guide-overview) | + + + +`CometChatTextFormatter` is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, keywords, or any regex-based pattern. + +| Capability | Description | +| --- | --- | +| Text formatting | Auto-format text based on regex patterns and styles | +| Custom styles | Set colors, fonts, and backgrounds for matched text | +| Dynamic replacement | Regex-based find-and-replace in user input | +| Input integration | Real-time monitoring of the composer input field | +| Attributed text | Build styled text spans for message bubbles | + +--- + +## Steps + +### 1. Import the base class + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +``` + +### 2. Extend CometChatTextFormatter + +```dart +class HashTagTextFormatter extends CometChatTextFormatter { + HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + ); + + // Override required methods... +} +``` + +### 3. Configure tracking character and regex + +Set the character that triggers formatting and the regex to match. + +```dart +HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + showLoadingIndicator: false, +); +``` + +### 4. Implement required methods + +```dart +@override +void init() { + // Initialize formatter +} + +@override +void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Process message before sending +} + +@override +TextStyle getMessageInputTextStyle(BuildContext context) { + return TextStyle(color: Colors.blue); +} + +@override +void onScrollToBottom(TextEditingController textEditingController) { + // Handle scroll events +} + +@override +void onChange(TextEditingController textEditingController, String previousText) { + // Handle text changes +} +``` + +### 5. Customize message bubble styling + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + return TextStyle( + color: alignment == BubbleAlignment.right + ? Colors.white + : Colors.blue, + fontWeight: FontWeight.bold, + decoration: TextDecoration.underline, + ); +} +``` + +--- + +## Example + +A hashtag formatter used with [CometChatMessageList](/ui-kit/flutter/message-list) and [CometChatMessageComposer](/ui-kit/flutter/message-composer). + + + + + + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class HashTagTextFormatter extends CometChatTextFormatter { + HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + showLoadingIndicator: false, + ); + + @override + void init() { + // Initialization logic + } + + @override + void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Process hashtags before sending + } + + @override + TextStyle getMessageInputTextStyle(BuildContext context) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + return TextStyle( + color: colorPalette.primary, + fontWeight: FontWeight.w500, + ); + } + + @override + TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} + ) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + return TextStyle( + color: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.primary, + fontWeight: FontWeight.bold, + decoration: TextDecoration.underline, + ); + } + + @override + void onScrollToBottom(TextEditingController textEditingController) { + // Handle scroll to bottom + } + + @override + void onChange(TextEditingController textEditingController, String previousText) { + // Handle text changes - detect new hashtags + String currentText = textEditingController.text; + if (currentText.contains('#')) { + // Process hashtag + } + } + + @override + List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} + ) { + return super.getAttributedText( + text, + context, + alignment, + existingAttributes: existingAttributes, + onTap: onTap ?? (hashtag) { + // Handle hashtag tap - e.g., search for hashtag + print('Tapped hashtag: $hashtag'); + }, + forConversation: forConversation, + ); + } +} +``` + + + + + +Pass the formatter via the `textFormatters` property. + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class MessageListDemo extends StatefulWidget { + const MessageListDemo({super.key}); + + @override + State createState() => _MessageListDemoState(); +} + +class _MessageListDemoState extends State { + User? chatUser; + + @override + void initState() { + super.initState(); + CometChat.getUser("uid").then((user) { + setState(() { + chatUser = user; + }); + }); + } + + @override + Widget build(BuildContext context) { + if (chatUser == null) { + return const Center(child: CircularProgressIndicator()); + } + + return CometChatMessageList( + user: chatUser, + textFormatters: [HashTagTextFormatter()], + ); + } +} +``` + + + + +--- + +## Methods Reference + +| Field | Description | +| --- | --- | +| `trackingCharacter` | Character that starts tracking (e.g. `#` for hashtags) | +| `pattern` | Regex pattern to match text for formatting | +| `showLoadingIndicator` | Whether to show loading indicator during search | +| `messageBubbleTextStyle` | Function to style message bubble text | +| `messageInputTextStyle` | Function to style composer input text | +| `message` | Current message being processed | +| `user` | User context for the formatter | +| `group` | Group context for the formatter | + +--- + +## Override Methods + + + + +Initialize the formatter. Called when the formatter is first used. + +```dart +@override +void init() { + // Setup any initial state +} +``` + + + + + +Process the message before it's sent. Use this to modify message metadata. + +```dart +@override +void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Add hashtag metadata to message + if (baseMessage is TextMessage) { + final hashtags = pattern?.allMatches(baseMessage.text) + .map((m) => m.group(1)) + .toList(); + // Store hashtags in message metadata + } +} +``` + + + + + +Returns the TextStyle for formatted text in message bubbles. + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + return TextStyle( + color: Colors.blue, + fontWeight: FontWeight.bold, + ); +} +``` + + + + + +Returns styled text spans for the message bubble. + +```dart +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} +) { + // Return attributed text with styling + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap, + forConversation: forConversation, + ); +} +``` + + + + + +Called when text changes in the composer. + +```dart +@override +void onChange(TextEditingController textEditingController, String previousText) { + // Detect and process new patterns +} +``` + + + + +--- + +## Built-in Formatters + +Flutter UI Kit includes these pre-built formatters: + +| Formatter | Description | +| --- | --- | +| `CometChatMentionsFormatter` | @mentions with user suggestions | +| `CometChatUrlFormatter` | Auto-detect and style URLs | +| `CometChatEmailFormatter` | Auto-detect and style email addresses | +| `CometChatPhoneNumberFormatter` | Auto-detect and style phone numbers | + +--- + +## Next Steps + + + + Add @mentions with styled tokens. + + + Customize the message input component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index 1b53fde4e..ac00ff131 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -107,7 +107,7 @@ Ensure your system meets the following **prerequisites** before proceeding with * **Flutter** installed on your system (Flutter 3.0 or higher recommended) * **Android Studio** or **VS Code** with configured Flutter/Dart plugins * **Xcode & CocoaPods** for iOS development -* An **iOS device or simulator** with iOS 12.0 or above +* An **iOS device or simulator** with iOS 13.0 or above * An **Android device or emulator** with Android version 5.0 (API level 21) or above *** @@ -136,7 +136,7 @@ dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.8 + cometchat_chat_uikit: ^5.2.10 cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling ``` @@ -151,13 +151,13 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ^3.5.3 + sdk: '>=3.8.0 <4.0.0' dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.8 + cometchat_chat_uikit: ^5.2.10 cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling cupertino_icons: ^1.0.8 @@ -201,7 +201,7 @@ android { In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: ```ruby Podfile -platform :ios, '12.0' +platform :ios, '13.0' ``` After updating, run: diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 896324117..0cecb9a9c 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -15,10 +15,17 @@ Available implementation guides for Flutter UI Kit: - [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` - [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` - [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` +- [Search Messages](/ui-kit/flutter/guide-search-messages) → `CometChatSearch` - [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` - [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` - [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` +**Formatter Guides:** +- [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) → `CometChatTextFormatter` +- [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) → `CometChatMentionsFormatter` +- [URL Formatter](/ui-kit/flutter/url-formatter-guide) → `CometChatUrlFormatter` +- [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) → `ShortcutFormatter` + **Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) Each guide provides end-to-end implementation with code examples and component references. @@ -30,7 +37,7 @@ This page indexes focused, task‑oriented feature guides for the Flutter UI Kit Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and wiring a basic conversations/messages experience. Add them incrementally to deepen functionality without rebuilding fundamentals. -## Guide Directory +## Feature Guides | Guide | Description | |:------|:------------| @@ -39,9 +46,19 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [Group Management](/ui-kit/flutter/guide-group-chat) | Create/join groups, view members, add / remove users, manage roles, and moderate participation. | | [Message Privately](/ui-kit/flutter/guide-message-privately) | Start a direct 1:1 chat from a profile or list; optionally send an initial message to surface the conversation. | | [New Chat](/ui-kit/flutter/guide-new-chat) | Offer a unified discovery screen for users & groups and launch new chats quickly. | +| [Search Messages](/ui-kit/flutter/guide-search-messages) | Full-text message search across conversations with result routing and navigation. | | [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) | Enable threaded replies: open parent message context, browse replies, and compose within a focused thread. | | [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) | Integrate AI agents with chat history, contextual responses, and seamless handoffs. | +## Formatter Guides + +| Guide | Description | +|:------|:------------| +| [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) | Build custom inline text patterns with regex, styling, and callbacks. | +| [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) | Add @mentions with user suggestions and styled tokens. | +| [URL Formatter](/ui-kit/flutter/url-formatter-guide) | Auto-detect and style URLs as clickable links. | +| [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) | Create keyboard shortcuts for quick text insertion. | + Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. --- diff --git a/ui-kit/flutter/guide-search-messages.mdx b/ui-kit/flutter/guide-search-messages.mdx new file mode 100644 index 000000000..bdf9382aa --- /dev/null +++ b/ui-kit/flutter/guide-search-messages.mdx @@ -0,0 +1,222 @@ +--- +title: "Search Messages" +sidebarTitle: "Search Messages" +description: "Add full-text message search across conversations with result routing in CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatSearch`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Init | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Full-text message search across conversations with result routing and navigation | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | + + + +Search Messages lets users locate specific messages across conversations and groups using keyword search, then navigate directly to the result. + +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatSearch` | Main container for searching messages and conversations | +| `CometChatMessageList` | Displays messages and supports scrolling to specific messages | +| `CometChatMessageComposer` | Supports navigation after selecting a search result | +| `CometChatMessageHeader` | Displays search context and navigation controls | + +--- + +## Integration Steps + +### 1. Launch Search Component + +Launch the `CometChatSearch` widget directly using Navigator or embed it in your widget tree. + +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatSearch()) +); +``` + +--- + +### 2. Handle Search Result Clicks + +Wire up the `onMessageClicked` callback to navigate to the message in context. + +```dart +CometChatSearch( + onMessageClicked: (message) { + // Navigate to the conversation containing this message + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: message.sender, // or group for group messages + ), + ), + ); + }, + onConversationClicked: (conversation) { + // Navigate to the selected conversation + if (conversation.conversationWith is User) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: conversation.conversationWith as User, + ), + ), + ); + } else if (conversation.conversationWith is Group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + group: conversation.conversationWith as Group, + ), + ), + ); + } + }, +); +``` + +--- + +### 3. Filter Search Results + +Use request builders to customize what gets searched. + +```dart +CometChatSearch( + // Filter conversations + conversationsRequestBuilder: ConversationsRequestBuilder() + ..limit = 30, + // Filter messages + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 50 + ..searchKeyword = "hello", +); +``` + +--- + +### 4. Customize Search Appearance + +Apply custom styling to match your app's design. + +```dart +CometChatSearch( + searchStyle: CometChatSearchStyle( + backgroundColor: Colors.white, + searchTextStyle: TextStyle(fontSize: 16), + searchFilterChipTextStyle: TextStyle(color: Colors.blue), + searchMessageItemBackgroundColor: Color(0xFFF5F5F5), + ), +); +``` + +--- + +## Feature Matrix + +| Feature | Component / Method | Description | +|:---|:---|:---| +| Search input | `CometChatSearch` | Main search interface | +| Display results | `CometChatSearch` | Shows matching conversations and messages | +| Conversation click | `onConversationClicked` | Handle conversation selection | +| Message click | `onMessageClicked` | Handle message selection | +| Filter conversations | `conversationsRequestBuilder` | Customize conversation search | +| Filter messages | `messagesRequestBuilder` | Customize message search | + +--- + +## Complete Example + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class SearchScreen extends StatelessWidget { + const SearchScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Search')), + body: CometChatSearch( + onConversationClicked: (conversation) { + _navigateToConversation(context, conversation); + }, + onMessageClicked: (message) { + _navigateToMessage(context, message); + }, + onBack: () { + Navigator.pop(context); + }, + onError: (error) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: ${error.message}')), + ); + }, + ), + ); + } + + void _navigateToConversation(BuildContext context, Conversation conversation) { + if (conversation.conversationWith is User) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: conversation.conversationWith as User, + ), + ), + ); + } else if (conversation.conversationWith is Group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + group: conversation.conversationWith as Group, + ), + ), + ); + } + } + + void _navigateToMessage(BuildContext context, BaseMessage message) { + // Navigate to the message's conversation + // Implementation depends on your app's navigation structure + } +} +``` + +--- + +## Next Steps + + + + Full search component reference. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index ea11a9337..84839787b 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -155,7 +155,7 @@ This layered approach means: The Flutter UI Kit works seamlessly across: -* **iOS** – iPhone and iPad (iOS 12.0+) +* **iOS** – iPhone and iPad (iOS 13.0+) * **Android** – Phones and tablets (API level 21+) *** diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx new file mode 100644 index 000000000..afde830f4 --- /dev/null +++ b/ui-kit/flutter/troubleshooting.mdx @@ -0,0 +1,211 @@ +--- +title: "Troubleshooting" +description: "Common failure modes and fixes for the CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Page type | Troubleshooting reference | +| Scope | All CometChat Flutter UI Kit v5 issues — initialization, rendering, theming, calling, extensions, AI features, localization, sound, events | +| When to reference | When a component fails to render, data is missing, styling doesn't apply, or a feature doesn't appear | + + + +## Initialization and Login + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `CometChatUIKit.init()` fails silently | Invalid App ID, Region, or Auth Key | Double-check credentials from the [CometChat Dashboard](https://app.cometchat.com/) | +| Widget doesn't render | `init()` not called or not awaited before rendering | Ensure `init()` completes before mounting widgets. See [Methods](/ui-kit/flutter/methods) | +| Widget renders but shows no data | User not logged in | Call `CometChatUIKit.login("UID")` after init | +| Login fails with "UID not found" | UID doesn't exist in your CometChat app | Create the user via Dashboard, SDK, or API first | +| Blank screen after login | Widget mounted before init/login completes | Use `FutureBuilder` or state to conditionally render after login resolves | +| `getLoggedInUser()` returns null | User not logged in or session expired | Call `login()` or `loginWithAuthToken()` first | +| `sendTextMessage()` fails | User not logged in or invalid receiver | Ensure login completes before sending messages | +| Auth Key exposed in production | Using Auth Key instead of Auth Token | Switch to [Auth Token](/ui-kit/flutter/methods#login-using-auth-token) for production | + +--- + +## Platform-Specific Issues + +### Android + +| Symptom | Cause | Fix | +| --- | --- | --- | +| App crashes on launch | Missing internet permission | Add `` to `AndroidManifest.xml` | +| Network requests fail | Missing network security config | For debug builds, add `android:usesCleartextTraffic="true"` to `AndroidManifest.xml` | +| Camera/microphone not working | Missing permissions | Add camera and microphone permissions to `AndroidManifest.xml` | +| Build fails with minSdk error | minSdkVersion too low | Set `minSdkVersion 21` or higher in `build.gradle` | +| ProGuard issues in release build | Missing ProGuard rules | Add CometChat ProGuard rules to `proguard-rules.pro` | + +### iOS + +| Symptom | Cause | Fix | +| --- | --- | --- | +| App crashes on camera/mic access | Missing Info.plist entries | Add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` | +| Build fails with deployment target error | iOS version too low | Set `platform :ios, '13.0'` or higher in `Podfile` | +| Pod install fails | CocoaPods cache issue | Run `pod cache clean --all` then `pod install` | +| Bitcode error | Bitcode enabled | Disable bitcode in Xcode build settings | +| Simulator crashes | Architecture mismatch | Ensure you're using the correct simulator architecture | + +--- + +## Theming and Styling + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Theme not applied | Theme not passed to widget | Wrap your app with `CometChatTheme` or pass theme to individual widgets | +| Colors not changing | Using wrong color palette | Use `CometChatThemeHelper.getColorPalette(context)` to access theme colors | +| Typography not applied | Font family not set | Set font family in `CometChatTypography` | +| Dark mode not working | Theme mode not set | Use `ThemeMode.dark` and ensure `CometChatColorPalette` has dark mode colors | +| Custom style not applying | Style property not set correctly | Check the component's style class (e.g., `CometChatConversationsStyle`) | +| Spacing issues | Using wrong spacing values | Use `CometChatSpacing` for consistent spacing | + +--- + +## Components + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Callback not firing | Wrong callback name or signature | Check the Actions section on the component page for exact callback name and parameters | +| Custom view not appearing | Returning `null` from view builder | Ensure view builder returns a valid Widget | +| Messages not loading | Invalid user/group object passed | Ensure you fetch the user/group via SDK before passing to components | +| List not refreshing | State not updated | Call `setState()` or use a state management solution | +| Scroll position lost | Key not set on list items | Ensure unique keys are set on list items | +| Empty state not showing | `emptyStateView` not set | Provide an `emptyStateView` builder | + +--- + +## Calling + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Call buttons not appearing | Calling extension not installed | Add `cometchat_calls_uikit` to your `pubspec.yaml` | +| Incoming call screen not showing | `CometChatIncomingCall` not in widget tree | Add `CometChatIncomingCall` at the app root level | +| Call fails to connect | WebRTC permissions not granted | Ensure camera and microphone permissions are granted | +| Audio not working in call | Audio session not configured | Configure audio session for iOS in `AppDelegate.swift` | +| Video not showing | Camera permission denied | Request camera permission before starting video call | +| Call drops immediately | Network connectivity issue | Check internet connection and firewall settings | + +--- + +## Extensions + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Extension feature not appearing | Extension not activated in Dashboard | Enable the specific extension from your [Dashboard](/fundamentals/extensions-overview) | +| Stickers not showing in composer | Sticker extension not enabled | Activate [Sticker Extension](/fundamentals/stickers) in Dashboard | +| Polls option missing | Polls extension not enabled | Activate [Polls Extension](/fundamentals/polls) in Dashboard | +| Link preview not rendering | Link Preview extension not enabled | Activate [Link Preview Extension](/fundamentals/link-preview) in Dashboard | +| Reactions not working | Reactions extension not enabled | Activate [Reactions Extension](/fundamentals/reactions) in Dashboard | + +--- + +## AI Features + +| Symptom | Cause | Fix | +| --- | --- | --- | +| AI features not appearing | Feature not activated in Dashboard | Enable the specific AI feature from your [Dashboard](/fundamentals/ai-user-copilot/overview) | +| Conversation Starter not showing | Feature not enabled or no conversation context | Ensure [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) is activated | +| Smart Replies not appearing | Feature not enabled in Dashboard | Ensure [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) is activated | +| AI extension not in UIKitSettings | AI features not configured | Add AI extensions to `UIKitSettings.aiFeature` list | + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..aiFeature = [ + AISmartRepliesExtension(), + AIConversationStarterExtension(), + AIConversationSummaryExtension(), + ] +).build(); +``` + +--- + +## Localization + +| Symptom | Cause | Fix | +| --- | --- | --- | +| UI text not translated | Language code not matching | Check supported languages in [Localize](/ui-kit/flutter/localize) | +| Custom translations not appearing | Translations not added correctly | Use `Translations` class to add custom translations | +| Date/time format unchanged | Locale not set | Set locale in `MaterialApp` or use `dateTimeFormatterCallback` | +| RTL layout not working | Text direction not set | Set `textDirection: TextDirection.rtl` for RTL languages | + +--- + +## Sound + +| Symptom | Cause | Fix | +| --- | --- | --- | +| No sound plays | Sound disabled or volume muted | Check `CometChatSoundManager` settings and device volume | +| Custom sound not playing | Invalid file path or format | Ensure the path is correct and file is WAV/MP3 format | +| Sound plays multiple times | Multiple listeners registered | Ensure you're not registering duplicate sound listeners | +| Sound continues after app backgrounded | Sound not stopped | Call `CometChatSoundManager.stop()` when appropriate | + +--- + +## Events + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Event listener not firing | Subscribed to wrong event | Check the [Events](/ui-kit/flutter/events) page for exact event names | +| Duplicate event triggers | Multiple subscriptions | Remove listener in `dispose()` method | +| Event fires but UI doesn't update | State not updated in handler | Call `setState()` in the event handler | +| Memory leak from events | Listener not removed | Always remove listeners in `dispose()` | + +```dart +@override +void dispose() { + CometChatMessageEvents.removeMessagesListener("listenerId"); + super.dispose(); +} +``` + +--- + +## Build and Dependencies + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Dependency conflict | Version mismatch | Run `flutter pub upgrade` and check version constraints | +| Build fails with Dart version error | Dart SDK too old | Upgrade Flutter: `flutter upgrade` | +| iOS build fails | Pod dependencies outdated | Run `cd ios && pod update` | +| Android build fails with Gradle error | Gradle version mismatch | Update Gradle in `android/gradle/wrapper/gradle-wrapper.properties` | +| Package not found | Package not in pubspec.yaml | Add `cometchat_chat_uikit: ^5.x.x` to dependencies | + +--- + +## Performance + +| Symptom | Cause | Fix | +| --- | --- | --- | +| UI janky/laggy | Too many rebuilds | Use `const` constructors and optimize state management | +| Memory usage high | Images not cached | Enable image caching and limit message history | +| Slow message loading | Large message history | Use pagination with `MessagesRequestBuilder().limit` | +| App freezes on large groups | Too many members loaded | Use pagination for group members | + +--- + +## Common Error Messages + +| Error | Cause | Fix | +| --- | --- | --- | +| `ERR_APP_NOT_FOUND` | Invalid App ID | Check App ID in Dashboard | +| `ERR_AUTH_TOKEN_NOT_FOUND` | Invalid or expired auth token | Generate new auth token | +| `ERR_UID_NOT_FOUND` | User doesn't exist | Create user first via Dashboard or API | +| `ERR_GROUP_NOT_FOUND` | Group doesn't exist | Create group first | +| `ERR_NOT_LOGGED_IN` | User not authenticated | Call `login()` before using SDK | +| `ERR_WEBSOCKET_CONNECTION_FAILED` | Network issue | Check internet connection | + +--- + +## Getting Help + +If you're still experiencing issues: + +1. Check the [CometChat Documentation](https://www.cometchat.com/docs) +2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) +3. Contact [CometChat Support](https://www.cometchat.com/support) +4. Join the [CometChat Community](https://community.cometchat.com) diff --git a/ui-kit/flutter/url-formatter-guide.mdx b/ui-kit/flutter/url-formatter-guide.mdx new file mode 100644 index 000000000..6627d0be0 --- /dev/null +++ b/ui-kit/flutter/url-formatter-guide.mdx @@ -0,0 +1,300 @@ +--- +title: "URL Formatter" +description: "Detect and style plain URLs as clickable links with optional tracking logic in CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatUrlFormatter` (extends `CometChatTextFormatter`) | +| Required setup | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Auto-detects URLs in text messages and converts them to clickable links | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) \| [All Guides](/ui-kit/flutter/guide-overview) | + + + +`CometChatUrlFormatter` extends [CometChatTextFormatter](/ui-kit/flutter/custom-text-formatter-guide) to detect URLs in text messages and render them as clickable links. + + + + + +--- + +## Overview + +The URL formatter is included by default in the Flutter UI Kit. It automatically: +- Detects URLs in message text using regex patterns +- Styles URLs with underline and link color +- Opens URLs in the browser when tapped + +--- + +## Default Behavior + +The `CometChatUrlFormatter` is automatically applied to messages. URLs are: +- Styled with underline decoration +- Colored based on bubble alignment (white for outgoing, info color for incoming) +- Clickable - tapping opens the URL in the default browser + +--- + +## Usage + +### Basic Usage (Default) + +The URL formatter is included by default. No additional setup required. + +```dart +CometChatMessageList( + user: chatUser, + // URL formatter is automatically included +) +``` + +### Custom URL Formatter + +Create a custom URL formatter with your own styling and behavior. + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class CustomUrlFormatter extends CometChatUrlFormatter { + CustomUrlFormatter() : super( + pattern: RegExp(r'(https?:\/\/[^\s]+)'), + messageBubbleTextStyle: (context, alignment, {forConversation}) { + return TextStyle( + color: Colors.blue, + decoration: TextDecoration.underline, + decorationColor: Colors.blue, + ); + }, + ); + + @override + List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} + ) { + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap ?? (url) async { + // Custom URL handling + _trackUrlClick(url); + await _openUrl(url); + }, + forConversation: forConversation, + ); + } + + void _trackUrlClick(String url) { + // Add analytics tracking + print('URL clicked: $url'); + } + + Future _openUrl(String url) async { + if (!url.startsWith('http://') && !url.startsWith('https://')) { + url = 'https://$url'; + } + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } +} +``` + +### Apply Custom Formatter + +```dart +CometChatMessageList( + user: chatUser, + textFormatters: [ + CustomUrlFormatter(), + CometChatMentionsFormatter(), // Keep other formatters + ], +) +``` + +--- + +## Customization + +### Styling Links + +Override `getMessageBubbleTextStyle` to customize link appearance: + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + + return TextStyle( + color: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.info, + fontWeight: FontWeight.w500, + decoration: TextDecoration.underline, + decorationColor: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.info, + ); +} +``` + +### Custom URL Pattern + +Use a custom regex pattern to match specific URL formats: + +```dart +CometChatUrlFormatter( + pattern: RegExp( + r'(https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*))' + ), +) +``` + +### Handle URL Clicks + +Override `getAttributedText` to add custom click handling: + +```dart +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} +) { + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: (url) async { + // Show confirmation dialog before opening + final shouldOpen = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Open Link'), + content: Text('Open $url?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: Text('Open'), + ), + ], + ), + ); + + if (shouldOpen == true) { + await launchUrl(Uri.parse(url)); + } + }, + forConversation: forConversation, + ); +} +``` + +--- + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| `pattern` | `RegExp?` | Regex pattern to match URLs | +| `messageBubbleTextStyle` | `Function?` | Custom style for URL text in bubbles | +| `onSearch` | `Function?` | Callback when URL is detected | +| `showLoadingIndicator` | `bool?` | Show loading indicator during processing | + +--- + +## Complete Example + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class UrlFormatterExample extends StatefulWidget { + const UrlFormatterExample({super.key}); + + @override + State createState() => _UrlFormatterExampleState(); +} + +class _UrlFormatterExampleState extends State { + User? chatUser; + + @override + void initState() { + super.initState(); + CometChat.getUser("uid").then((user) { + setState(() => chatUser = user); + }); + } + + @override + Widget build(BuildContext context) { + if (chatUser == null) { + return const Center(child: CircularProgressIndicator()); + } + + return Scaffold( + body: CometChatMessageList( + user: chatUser, + textFormatters: [ + CometChatUrlFormatter( + messageBubbleTextStyle: (context, alignment, {forConversation}) { + return TextStyle( + color: alignment == BubbleAlignment.right + ? Colors.white + : Colors.blue, + decoration: TextDecoration.underline, + ); + }, + ), + CometChatMentionsFormatter(), + ], + ), + ); + } +} +``` + +--- + +## Next Steps + + + + Build custom inline text patterns. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + From a013171ca62c7521332f163caeaef42dc342464d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:27:52 +0530 Subject: [PATCH 09/32] Create .mintignore --- .mintignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .mintignore diff --git a/.mintignore b/.mintignore new file mode 100644 index 000000000..a2bfd86bc --- /dev/null +++ b/.mintignore @@ -0,0 +1,2 @@ +.kiro/ +/codebase \ No newline at end of file From ec9577a17ae0e9786948e5e08ec2445b2d055195 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:31:53 +0530 Subject: [PATCH 10/32] Update conversations.mdx --- ui-kit/flutter/conversations.mdx | 2377 +++++++++++++++++------------- 1 file changed, 1351 insertions(+), 1026 deletions(-) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index adaac93ab..239fda8b6 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -1,54 +1,219 @@ --- title: "Conversations" +description: "Scrollable list of recent one-on-one and group conversations for the logged-in user." --- -## Overview + +```json +{ + "component": "CometChatConversations", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Scrollable list of recent one-on-one and group conversations for the logged-in user.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(Conversation conversation)" + }, + "props": { + "data": { + "conversationsRequestBuilder": { + "type": "ConversationsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + } + }, + "callbacks": { + "onItemTap": "Function(Conversation conversation)", + "onItemLongPress": "Function(Conversation conversation)", + "onSelection": "Function(List? list)", + "onBack": "VoidCallback", + "onError": "OnError", + "onLoad": "OnLoad", + "onEmpty": "OnEmpty", + "onSearchTap": "GestureTapCallback" + }, + "visibility": { + "receiptsVisibility": { "type": "bool", "default": true }, + "usersStatusVisibility": { "type": "bool", "default": true }, + "groupTypeVisibility": { "type": "bool", "default": true }, + "deleteConversationOptionVisibility": { "type": "bool", "default": true }, + "hideAppbar": { "type": "bool", "default": false }, + "hideError": { "type": "bool", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool", "default": false }, + "customSoundForMessages": { "type": "String", "default": "built-in" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(Conversation conversation)", + "leadingView": "Widget? Function(BuildContext context, Conversation conversation)", + "titleView": "Widget? Function(BuildContext context, Conversation conversation)", + "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)", + "trailingView": "Widget? Function(Conversation conversation)", + "loadingStateView": "WidgetBuilder", + "emptyStateView": "WidgetBuilder", + "errorStateView": "WidgetBuilder", + "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)", + "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)" + }, + "formatting": { + "textFormatters": { + "type": "List", + "default": "default formatters from data source" + } + } + }, + "events": [ + { + "name": "CometChatConversationEvents.ccConversationDeleted", + "payload": "Conversation", + "description": "Conversation deleted from list" + } + ], + "sdkListeners": [ + "onTextMessageReceived", + "onMediaMessageReceived", + "onCustomMessageReceived", + "onTypingStarted", + "onTypingEnded", + "onMessagesDelivered", + "onMessagesRead", + "onUserOnline", + "onUserOffline", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "Sidebar conversations wired to message view", + "components": [ + "CometChatConversations", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + } + } +} +``` + -The `CometChatConversations` is a [Widget](/ui-kit/flutter/components-overview#components), That shows all conversations related to the currently logged-in user, - - - +## Where It Fits -## Usage +`CometChatConversations` is a sidebar list widget. It renders recent conversations and emits the selected `Conversation` via `onItemTap`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard two-panel chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatConversations` is a widget, it can be initiated either by tapping a button or through the trigger of any event. It offers multiple parameters and methods for tailoring its user interface. +class ChatApp extends StatefulWidget { + const ChatApp({super.key}); -You can launch `CometChatConversations` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _ChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatConversations` +class _ChatAppState extends State { + User? selectedUser; + Group? selectedGroup; + + void handleItemTap(Conversation conversation) { + final entity = conversation.conversationWith; + setState(() { + if (entity is User) { + selectedUser = entity; + selectedGroup = null; + } else if (entity is Group) { + selectedGroup = entity; + selectedUser = null; + } + }); + } - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatConversations())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatConversations( + onItemTap: handleItemTap, + ), + ), + Expanded( + child: selectedUser != null || selectedGroup != null + ? CometChatMessages( + user: selectedUser, + group: selectedGroup, + ) + : const Center( + child: Text('Select a conversation'), + ), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatConversations` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Conversations extends StatefulWidget { - const Conversations({super.key}); - - @override - State createState() => _ConversationsState(); -} +class ConversationsDemo extends StatelessWidget { + const ConversationsDemo({super.key}); -class _ConversationsState extends State { @override Widget build(BuildContext context) { - return Scaffold( + return const Scaffold( body: SafeArea( child: CometChatConversations(), ), @@ -56,206 +221,185 @@ class _ConversationsState extends State { } } ``` - - -### Actions + + + + +You can also launch it using `Navigator.push`: -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatConversations()) +); +``` + +--- -##### onItemTap +## Filtering Conversations -`onItemTap` is triggered when you click on a ListItem of the `CometChatConversations` widget. This `onItemTap` method proves beneficial when a user intends to customize the click behavior in CometChatConversations. +Pass a `ConversationsRequestBuilder` to `conversationsRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatConversations( - onItemTap: (conversation) => { - // TODO("Not yet implemented") - } -), + conversationsRequestBuilder: ConversationsRequestBuilder() + ..conversationType = "user" + ..limit = 10, +) ``` - - -*** +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Only user conversations | `ConversationsRequestBuilder()..conversationType = "user"` | +| Only group conversations | `ConversationsRequestBuilder()..conversationType = "group"` | +| Limit to 10 per page | `ConversationsRequestBuilder()..limit = 10` | +| With specific tags | `ConversationsRequestBuilder()..tags = ["vip"]` | +| With user and group tags | `ConversationsRequestBuilder()..withUserAndGroupTags = true` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + +Refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations) for the full builder API. + +--- + + +## Actions and Events + +### Callback Props -##### onItemLongPress +#### onItemTap -`onItemLongPress` is triggered when you on long press on a ListItem of the `CometChatConversations` widget. This `onItemLongPress` method proves beneficial when a user intends to customize the long press behavior in CometChatConversations. +Fires when a conversation row is tapped. Primary navigation hook — set the active conversation and render the message view. ```dart CometChatConversations( - onItemLongPress: (conversation) => { - // Handle long press on conversation item - } -), + onItemTap: (conversation) { + print("Selected: ${conversation.conversationId}"); + }, +) ``` - - -*** +#### onItemLongPress -##### onBack - -This `onBack` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatConversations. +Fires when a conversation row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatConversations( - onBack: () => { - // TODO("Not yet implemented") - }, -), + onItemLongPress: (conversation) { + // Show custom context menu + }, +) ``` - - -*** - -##### setOnSelection +#### onSelection -The `onSelection` feature enables selection with modes: `SelectionMode.single` and `SelectionMode.multiple`. - -The `onSelection` event is triggered upon the completion of a selection in `onSelection`. This returns the selected conversations list when the callback is triggered. It can be executed with any button or action. +Fires when conversations are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatConversations( - selectionMode: SelectionMode.multiple, - onSelection: (list) => { - // TODO("Not yet implemented") - }, -), + selectionMode: SelectionMode.multiple, + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} conversations"); + }, +) ``` - - -*** - -##### onError +#### onError -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatConversations. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatConversations( - onError: (e) { - // TODO("Not yet implemented") - }, -), + onError: (error) { + print("CometChatConversations error: $error"); + }, +) ``` - - -*** +#### onBack -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires when the back button is pressed. ```dart CometChatConversations( - onLoad: (list) { - // Handle conversations list load - }, -), + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, +) ``` - - -*** - -##### onEmpty +#### onLoad -Called when the list is empty, enabling custom handling such as showing a placeholder message +Fires when the conversation list is successfully loaded. ```dart CometChatConversations( - onEmpty: () { - // Handle empty conversations list - }, -), + onLoad: (list) { + print("Loaded ${list.length} conversations"); + }, +) ``` - - -*** - -### Filters - -You can set `ConversationsRequestBuilder` in the `CometChatConversations` widget to filter the conversation list. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations). +#### onEmpty -You can set filters using the following parameters. - -* Conversation Type: Filters on type of Conversation, User or Groups. -* Limit: Number of conversations fetched in a single request. -* WithTags: Filter on fetching conversations containing tags. -* Tags: Filters on specific Tag. -* UserTags: Filters on specific User Tag. -* GroupTags: Filters on specific Group Tag. +Fires when the conversation list is empty. ```dart CometChatConversations( - conversationsRequestBuilder: ConversationsRequestBuilder() - ..conversationType = "user" - ..limit = 10 - ..withTags = false, + onEmpty: () { + print("No conversations found"); + }, ) ``` - - -You can set filters using the following parameters: - -| Property | Description | Code | -| ---------------------------- | ---------------------------------------------------- | ------------------------------- | -| **Build** | Builds and returns an `ConversationsRequest` object. | `build(): ConversationsRequest` | -| **Conversation Type** | Type of the conversation. | `conversationType: String?` | -| **Limit** | Number of results to limit the query. | `limit: int?` | -| **Tags** | Tags for filtering. | `tags: List?` | -| **With Tags** | Flag to include tags. | `withTags: bool?` | -| **With User And Group Tags** | Flag to include user and group tags. | `withUserAndGroupTags: bool?` | -*** +### Global UI Events -### Events +`CometChatConversationEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccConversationDeleted` | A conversation is deleted from the list | `Conversation` | -##### 1. Conversation Deleted - -This `ccConversationDeleted` will be emitted when the user deletes a conversation +When to use: sync external UI with conversation state changes. For example, update an unread count badge in a tab bar when a conversation is deleted. @@ -267,1140 +411,1321 @@ class _YourScreenState extends State with CometChatConversationEvent @override void initState() { super.initState(); - CometChatConversationEvents.addConversationListListener("listenerId", this); // Add the listener + CometChatConversationEvents.addConversationListListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatConversationEvents.removeConversationListListener("listenerId"); super.dispose(); - CometChatConversationEvents.removeConversationListListener("listenerId"); // Remove the listener } @override void ccConversationDeleted(Conversation conversation) { - // TODO("Not yet implemented") + print("Deleted: ${conversation.conversationId}"); } } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To align with your app's design specifications, you have the flexibility to customize the appearance of the conversation widget. We offer accessible methods that empower you to tailor the experience and functionality to meet your unique requirements. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Moves conversation to top, updates last message preview and unread count | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator in the subtitle | +| `onMessagesDelivered` / `onMessagesRead` | Updates receipt ticks (unless `receiptsVisibility: false`) | +| `onUserOnline` / `onUserOffline` | Updates online/offline status dot (unless `usersStatusVisibility: false`) | +| `onGroupMemberJoined` / `onGroupMemberLeft` / `onGroupMemberKicked` / `onGroupMemberBanned` / `onMemberAddedToGroup` | Updates group conversation metadata | -You can set the `CometChatConversationsStyle` to the `CometChatConversations` Widget to customize the styling. +Automatic: new messages, typing indicators, receipts, user presence, group membership changes. - - -```dart -CometChatConversations( - conversationsStyle: CometChatConversationsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - badgeStyle:CometChatBadgeStyle( - backgroundColor: Color(0xFFF76808) - ) -) -), -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a conversation parameter receive the `Conversation` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(Conversation)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, Conversation)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, Conversation)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, Conversation)` | Last message preview | +| `trailingView` | `Widget? Function(Conversation)` | Timestamp / badge / right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Conversation, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Conversation, Controller, BuildContext)` | Context menu actions (adds to default) | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart - CometChatConversations( - showBackButton: false, - title: "Your Title", +CometChatConversations( + listItemView: (conversation) { + final entity = conversation.conversationWith; + final name = entity is User ? entity.name : (entity as Group).name; + + return CometChatListItem( + avatarName: name, + avatarURL: entity is User ? entity.avatar : (entity as Group).icon, + title: name, + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + ), + ); + }, ) ``` - - -List of Poperties exposed by `CometChatConversations` - -| Property | Description | Code | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -| **Activate Selection** | Used to specify if the listed conversations can be selected, selection can be activated on tap or on long press | `activateSelection: ActivateSelection` | -| **AppBar Options** | Used to set the options available in the app bar | `appBarOptions: List` | -| **Back Button** | Used to set back button located in the app bar | `backButton: Widget` | -| **Scroll Controller** | Used to programmatically update the scroll physics of list containing the conversations | `scrollController: ScrollController` | -| **Date Pattern** | Used to display a custom string instead of the timestamp show at the tail of the conversation item | `datePattern: String Function(Conversation conversation)` | -| **Empty State View** | Used to set a custom widget response when fetching the conversations has returned an empty list | `emptyStateView: WidgetBuilder` | -| **Error State View** | Used to set a custom widget response when some error occurs on fetching the list of conversations | `errorStateView: WidgetBuilder` | -| **Loading State View** | Used to set a custom widget response when conversations are loading | `loadingStateView: WidgetBuilder` | -| **Hide Appbar** | Toggle visibility for app bar | `hideAppbar: bool` | -| **Hide Error** | Used to hide error on fetching conversations | `hideError: bool` | -| **Hide Receipt** | Used to toggle visibility of message receipts shown in the subtitle of the conversation | `receiptsVisibility: bool` | -| **Protected Group Icon** | Used to set icon shown in place of status indicator if the conversation is taking place in a password-protected group | `protectedGroupIcon: Widget` | -| **Private Group Icon** | Used to set icon shown in place of status indicator if the conversation is taking place in a private group | `privateGroupIcon: Widget` | -| **Selection Icon** | Change selection icon | `selectionIcon: Widget` | -| **Sent Icon** | Used to customize the receipt icon shown in the subtitle of the conversation item if receiptsVisibility is false and the status of the last message in the conversation is sent | `sentIcon: Widget` | -| **Delivered Icon** | Used to customize the receipt icon if the message was delivered | `deliveredIcon: Widget` | -| **Read Icon** | Used to customize the receipt icon if the message was read | `readIcon: Widget` | -| **Show Back Button** | Used to toggle visibility for back button | `showBackButton: bool` | -| **Theme** | Used to set a custom theme | `conversationsStyle: CometChatConversationsStyle` | -| **Title** | Used to set the title in the app bar | `title: String` | -| **Typing Indicator Text** | Used to customize the text response shown in the subtitle of the conversation item if a participant of a conversation is typing | `typingIndicatorText: String` | -| **Disable Conversation Delete Option Visibility** | Used to toggle visibility for delete option | `deleteConversationOptionVisibility: bool` | -| **User Status Visibility** | Used to control visibility of status indicator shown if a user is online | `usersStatusVisibility: bool` | -| **Group Type Visibility** | Used to control visibility of the status indicator shown for the group type | `groupTypeVisibility: bool` | -| **On Back** | Callback triggered when closing the screen | `onBack: VoidCallback` | -| **On Item Tap** | Callback triggered when tapping a conversation item | `onItemTap: Function(Conversation conversation)` | -| **On Item Long Press** | Callback triggered when long pressing a conversation item | `onItemLongPress: Function(Conversation conversation)` | -| **Text Formatters** | List of text formatters for message bubbles with text type | `textFormatters: List` | -| **Date Padding** | Provides padding for the conversation date | `datePadding: EdgeInsets` | -| **Date Height** | Provides height for the conversation date | `dateHeight: double` | -| **Date Background Transparency** | Controls the background transparency of the conversation date | `dateBackgroundIsTransparent: bool` | -| **Date Width** | Provides width for the conversation date | `dateWidth: double` | -| **Badge Width** | Provides width for conversation badges | `badgeWidth: double` | -| **Badge Height** | Provides height for conversation badges | `badgeHeight: double` | -| **Badge Padding** | Provides padding for conversation badges | `badgePadding: EdgeInsetsGeometry` | -| **Avatar Width** | Provides width for user/group avatars | `avatarWidth: double` | -| **Avatar Height** | Provides height for user/group avatars | `avatarHeight: double` | -| **Avatar Padding** | Provides padding for user/group avatars | `avatarPadding: EdgeInsetsGeometry` | -| **Avatar Margin** | Provides margin for user/group avatars | `avatarMargin: EdgeInsetsGeometry` | -| **Status Indicator Width** | Provides width for the user/group status indicator | `statusIndicatorWidth: double` | -| **Status Indicator Height** | Provides height for the user/group status indicator | `statusIndicatorHeight: double` | -| **Status Indicator Border Radius** | Provides border radius for the user/group status indicator | `statusIndicatorBorderRadius: BorderRadiusGeometry` | -| **Controller Tag** | Tag for controller, used when parent needs to control the widget | `controllerTag: String` | -| **Submit Icon** | Used to override the default submit icon | `submitIcon: Widget` | -| **Set Options** | Sets the list of actions available on long press of a list item | `setOptions: Function(Conversation, Controller, Context)` | -| **Add Options** | Adds into the current list of actions available on long press of a list item | `addOptions: Function(Conversation, Controller, Context)` | -| **Leading View** | Custom widget for the leading section of each conversation | `leadingView: Widget Function(BuildContext, Conversation)` | -| **Title View** | Custom widget for the title section of each conversation | `titleView: Widget Function(BuildContext, Conversation)` | -| **On Load** | Callback when conversation list is loading | `onLoad: OnLoad` | -| **On Empty** | Callback when conversation list is empty | `onEmpty: OnEmpty` | -| **On Error** | Callback when an error occurs | `onError: OnError` | -| **Custom Sound For Messages** | Set a custom notification sound for messages | `customSoundForMessages: String` | -| **Disable Sound For Messages** | Disable sound for messages | `disableSoundForMessages: bool` | -| **Mention All Label Id** | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | `mentionAllLabelId: String` | -| **Mention All Label** | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | `mentionAllLabel: String` | -| **Hide Search** | Hides the search bar in the app bar | `hideSearch: bool` | -| **Search Read Only** | Makes the search box read-only | `searchReadOnly: bool` | -| **On Search Tap** | Callback triggered when the search box is tapped | `onSearchTap: GestureTapCallback` | -| **Search Box Icon** | Custom prefix icon for the search box | `searchBoxIcon: Widget` | -| **Search Padding** | Provides padding for the search box | `searchPadding: EdgeInsetsGeometry` | -| **Search Content Padding** | Provides padding for the search box content | `searchContentPadding: EdgeInsetsGeometry` | -| **Date Time Formatter Callback** | Callback that can be used to format the date and time | `dateTimeFormatterCallback: DateTimeFormatterCallback` | - -### Advanced - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a conversation in the list. These options typically include: - -* Deleting a conversation -* Marking a conversation as read or unread -* Pinning or unpinning a conversation -* Muting notifications for a specific conversation - -By customizing these options, developers can provide a streamlined and contextually relevant user experience. +### leadingView + +Replace the avatar / left section. Typing-aware avatar example. + + + + ```dart +Map typingMap = {}; + CometChatConversations( - setOptions: (conversation, controller, context) { return [];}, + leadingView: (context, conversation) { + final entity = conversation.conversationWith; + final id = entity is User ? entity.uid : (entity as Group).guid; + + if (typingMap.containsKey(id)) { + return Container( + decoration: BoxDecoration( + border: Border.all(color: Color(0xFFF76808), width: 2), + borderRadius: BorderRadius.circular(8), + ), + child: Image.asset("assets/typing_icon.png", height: 40, width: 40), + ); + } + return null; // Use default avatar + }, ) ``` - - -Demonstration + +### titleView + +Replace the name / title text. Inline user status example. - + ```dart CometChatConversations( - setOptions: (conversation, controller, context) { - return [ - CometChatOption( - id: "Delete Conversation", - icon: AssetConstants.delete, - title: "Delete", - onClick: () { - // Delete Conversation - }, - ), - ]; - }, -), + titleView: (context, conversation) { + final entity = conversation.conversationWith; + final name = entity is User ? entity.name : (entity as Group).name; + final statusMessage = entity is User ? entity.statusMessage : null; + + return Row( + children: [ + Text(name ?? "", style: TextStyle(fontWeight: FontWeight.w500)), + if (statusMessage != null) + Text(" · $statusMessage", style: TextStyle(color: Color(0xFF6852D6))), + ], + ); + }, +) ``` - - -*** - -#### addOptions +### subtitleView -This method extends the existing set of actions available when users long press a conversation item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +Replace the last message preview text. -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" - -This method provides flexibility in modifying user interaction capabilities. + + + ```dart CometChatConversations( - addOptions: (conversation, controller, context) { return [];}, -), + subtitleView: (context, conversation) { + final entity = conversation.conversationWith; + String subtitle; + + if (entity is User) { + final dateTime = entity.lastActiveAt ?? DateTime.now(); + subtitle = "Last Active: ${DateFormat('dd/MM/yyyy, HH:mm').format(dateTime)}"; + } else { + final dateTime = (entity as Group).createdAt ?? DateTime.now(); + subtitle = "Created: ${DateFormat('dd/MM/yyyy, HH:mm').format(dateTime)}"; + } + + return Text(subtitle, style: TextStyle(color: Color(0xFF727272), fontSize: 14)); + }, +) ``` - - -Demonstration +### trailingView + +Replace the timestamp / badge / right section. Relative time badge example. - + ```dart CometChatConversations( -addOptions: (conversation, controller, context) { - return [ - CometChatOption( - id: "Archive", - iconWidget: Icon( - Icons.archive_outlined, - color: colorPalette.error, - ), - title: "Archive", - onClick: () { - // Archive Conversation - }, - ), - CometChatOption( - id: "Pin", - iconWidget: Icon( - Icons.push_pin_outlined, - color: colorPalette.error, - ), - title: "Pin", - onClick: () { - // Pin Conversation - }, - ), - CometChatOption( - id: "Mark As Read", - iconWidget: Icon( - Icons.mark_chat_unread_outlined, - color: colorPalette.error, - ), - title: "Mark as unread", - onClick: () { - // Mark as unread - }, - ), - ]; - }, -), -``` + trailingView: (conversation) { + final timestamp = conversation.updatedAt?.millisecondsSinceEpoch ?? 0; + final now = DateTime.now(); + final lastSeen = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + final diffInMinutes = now.difference(lastSeen).inMinutes; + final diffInHours = now.difference(lastSeen).inHours; + + String timeText; + String label; + Color cardColor; + + if (diffInMinutes < 60) { + timeText = "$diffInMinutes"; + label = "Min ago"; + cardColor = Color(0x666852D6); + } else if (diffInHours < 10) { + timeText = "$diffInHours"; + label = "Hr ago"; + cardColor = Color(0x66FFAB00); + } else { + timeText = "$diffInHours"; + label = "Hr ago"; + cardColor = Color(0x66F44649); + } + return Card( + color: cardColor, + child: Padding( + padding: EdgeInsets.all(4), + child: Column( + children: [ + Text(timeText, style: TextStyle(fontWeight: FontWeight.bold)), + Text(label, style: TextStyle(fontSize: 12)), + ], + ), + ), + ); + }, +) +``` - -*** - -#### disableSoundForMessages -This disables sound notifications for incoming messages. When activated, the application will not play an audio alert when new messages arrive. This feature is beneficial in scenarios where: +### setOptions -* Users prefer a silent messaging experience -* The app is being used in a professional or quiet environment -* Background processes need to minimize distractions +Replace the context menu / long-press actions on each conversation item. -By providing this option, the app allows users to tailor their notification preferences + + + ```dart CometChatConversations( - disableSoundForMessages: true, + setOptions: (conversation, controller, context) { + return [ + CometChatOption( + id: "delete", + title: "Delete", + icon: AssetConstants.delete, + onClick: () { + // Delete conversation + }, + ), + ]; + }, ) ``` - - -*** - -#### setCustomSoundForMessages +### addOptions -This method enables users to personalize their chat experience by setting a custom sound file for incoming message notifications. Users can choose from: +Add to the existing context menu actions without removing defaults. -* Default system sounds -* Custom sound files uploaded by the user -* Theme-based or brand-specific notification sounds - -By allowing sound customization, this feature enhances personalization and improves user engagement. + + + ```dart CometChatConversations( - customSoundForMessages: "message.mp3", -), + addOptions: (conversation, controller, context) { + return [ + CometChatOption( + id: "archive", + title: "Archive", + iconWidget: Icon(Icons.archive_outlined), + onClick: () { + // Archive conversation + }, + ), + CometChatOption( + id: "pin", + title: "Pin", + iconWidget: Icon(Icons.push_pin_outlined), + onClick: () { + // Pin conversation + }, + ), + ]; + }, +) ``` - - -*** - -#### loadingStateView +### appBarOptions -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. +Add custom widgets to the app bar. -Use cases : - -* Showing a skeleton loader for conversations while data loads -* Displaying a custom progress indicator with branding -* Providing an animated loading experience for a more engaging UI + + + ```dart CometChatConversations( - loadingStateView: (context) { - // return Loading state Widget - }, -), + showBackButton: false, + appBarOptions: [ + PopupMenuButton( + icon: CometChatAvatar( + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + itemBuilder: (context) => [ + PopupMenuItem(value: 'create', child: Text("Create Conversation")), + PopupMenuItem(value: 'logout', child: Text("Logout")), + ], + onSelected: (value) { + // Handle menu selection + }, + ), + ], +) ``` - - -*** - -#### emptyStateView +--- -Configures a custom view to be displayed when there are no conversations or messages in the list. This improves the user experience by providing meaningful content instead of an empty screen. -Use cases : +## Styling -* Displaying a message like "No conversations yet. Start a new chat!" -* Showing an illustration or animation to make the UI visually appealing -* Providing a button to start a new conversation +Set `CometChatConversationsStyle` to customize the appearance. ```dart CometChatConversations( - emptyStateView: (context) { - // return Empty state Widget - }, -), + conversationsStyle: CometChatConversationsStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFF141414), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + badgeStyle: CometChatBadgeStyle( + backgroundColor: Color(0xFFF76808), + ), + ), +) ``` - - -*** + + + -#### errorStateView +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color` | Background color of the component | +| `border` | `Border` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry` | Border radius for the widget | +| `titleTextColor` | `Color` | Color of the header title | +| `titleTextStyle` | `TextStyle` | Style for the header title | +| `backIconColor` | `Color` | Back button icon color | +| `searchBackgroundColor` | `Color` | Background color of search box | +| `searchBorder` | `BorderSide` | Border for search box | +| `searchBorderRadius` | `BorderRadius` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle` | Placeholder text style in search | +| `searchIconColor` | `Color` | Search icon color | +| `separatorColor` | `Color` | Color of list item separators | +| `separatorHeight` | `double` | Height of list item separators | +| `emptyStateTextColor` | `Color` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle` | Text style for error state subtitle | +| `itemTitleTextColor` | `Color` | Text color for conversation item title | +| `itemTitleTextStyle` | `TextStyle` | Text style for conversation item title | +| `itemSubtitleTextColor` | `Color` | Text color for conversation item subtitle | +| `itemSubtitleTextStyle` | `TextStyle` | Text style for conversation item subtitle | +| `messageTypeIconColor` | `Color` | Icon color for message type indicators | +| `avatarStyle` | `CometChatAvatarStyle` | Style for avatars | +| `badgeStyle` | `CometChatBadgeStyle` | Style for unread badges | +| `receiptStyle` | `CometChatMessageReceiptStyle` | Style for message receipts | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle` | Style for online status indicator | +| `dateStyle` | `CometChatDateStyle` | Style for date/time display | +| `typingIndicatorStyle` | `CometChatTypingIndicatorStyle` | Style for typing indicator | +| `mentionsStyle` | `CometChatMentionsStyle` | Style for @mentions | +| `deleteConversationDialogStyle` | `CometChatConfirmDialogStyle` | Style for delete confirmation dialog | +| `privateGroupIconBackground` | `Color` | Background color for private group icon | +| `protectedGroupIconBackground` | `Color` | Background color for protected group icon | +| `submitIconColor` | `Color` | Color for submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color` | Background color for selection checkbox | +| `checkBoxCheckedBackgroundColor` | `Color` | Background color when checkbox is checked | +| `checkBoxBorder` | `BorderSide` | Border for selection checkbox | +| `checkBoxBorderRadius` | `BorderRadiusGeometry` | Border radius for selection checkbox | +| `checkboxSelectedIconColor` | `Color` | Icon color when checkbox is selected | +| `listItemSelectedBackgroundColor` | `Color` | Background color for selected list items | -Defines a custom error state view that appears when an issue occurs while loading conversations or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. +--- -Use cases : +## Common Patterns -* Showing "Something went wrong. Please try again." with a retry button -* Displaying a connection issue message if the user is offline -* Providing troubleshooting steps for the error +### Custom empty state with CTA ```dart CometChatConversations( - errorStateView: (context) { - // return Error state Widget - }, -), + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("No conversations yet"), + SizedBox(height: 16), + ElevatedButton( + onPressed: () { + // Navigate to contacts + }, + child: Text("Start a conversation"), + ), + ], + ), + ); + }, +) ``` - - -*** +### Hide all chrome — minimal list -#### leadingView - -Allows setting a custom leading view element that appears at the beginning of each conversation item. This is typically used to modify profile pictures, avatars, or icons in the conversation list. + + +```dart +CometChatConversations( + receiptsVisibility: false, + usersStatusVisibility: false, + groupTypeVisibility: false, + deleteConversationOptionVisibility: false, + hideAppbar: true, +) +``` + + -Use cases : -* Displaying user avatars with online/offline status indicators -* Using initials or custom graphics instead of images +### Conversations with search ```dart CometChatConversations( - leadingView: (context, conversation) { - // return leading view - }, -), + hideSearch: false, + onSearchTap: () { + // Handle search tap - navigate to search screen + }, +) ``` - - -Demonstration +### Custom date pattern - + ```dart - - - Map typingMap = {}; - - @override - void onTypingStarted(TypingIndicator typingIndicator) { - if (userIsNotBlocked(typingIndicator.sender)) { - setTypingIndicator(typingIndicator, true); - } - } - - - @override - void onTypingEnded(TypingIndicator typingIndicator) { - if (userIsNotBlocked(typingIndicator.sender)) { - setTypingIndicator(typingIndicator, false); - } - } - - bool userIsNotBlocked(User user) { - return user.blockedByMe != true && user.hasBlockedMe != true; - } - - void setTypingIndicator( - TypingIndicator typingIndicator, bool isTypingStarted) { - if (typingIndicator.receiverType == ReceiverTypeConstants.user) { - if (isTypingStarted) { - typingMap[typingIndicator.sender.uid] = typingIndicator; - } else { - typingMap.remove(typingIndicator.sender.uid); - } - } else { - if (isTypingStarted) { - typingMap[typingIndicator.receiverId] = typingIndicator; - } else { - typingMap.remove(typingIndicator.receiverId); - } - } - setState(() {}); - } - CometChatConversations( -leadingView: (context, conversation) { - if (typingMap.containsKey( - (conversation.conversationType == "user" - ? (conversation.conversationWith as User).uid - : (conversation.conversationWith as Group).guid))) { - return Container( - decoration: BoxDecoration( - border: Border.all(color: Color(0xFFF76808), width: 2), - borderRadius: BorderRadius.circular(8), - ), - child: Image.asset( - "assets/leading_typing_icon.png", - height: 40, - width: 40, - ), - ); - } - return null; - }, + datePattern: (conversation) { + final date = conversation.lastMessage?.sentAt ?? DateTime.now(); + return DateFormat('d MMM, hh:mm a').format(date); + }, ) ``` - - -*** - -#### titleView +### Text formatters -Overrides the default title view in the conversation list with a custom layout. This is useful for branding or modifying how conversation names and details are displayed. +Configure text formatters for the conversation subtitle. See [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) for mention formatting. -Use cases : - -* Displaying conversation titles with additional metadata (e.g., last seen time) -* Custom fonts or text styles for conversation names -* Adding icons or indicators next to titles + + + ```dart CometChatConversations( - titleView: (context, conversation) { - // return title view - }, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - -Demonstration +--- - - - - - -```dart +## Props -CometChatConversations( - titleView: (context, conversation) { - return Row( - children: [ - Text( - conversation.conversationWith is User - ? (conversation.conversationWith as User).name ?? "" - : (conversation.conversationWith as Group).name ?? "", - style: TextStyle( - color: colorPalette.textPrimary, - fontSize: typography.body?.medium?.fontSize, - fontFamily: typography.body?.medium?.fontFamily, - fontWeight: typography.body?.medium?.fontWeight, - ), - ), - Text( - (conversation.conversationWith is User && - (conversation.conversationWith as User) - .statusMessage != - null) - ? ". ${(conversation.conversationWith as User).statusMessage}" - : "", - style: TextStyle( - color: colorPalette.textPrimary, - fontSize: typography.body?.medium?.fontSize, - fontFamily: typography.body?.medium?.fontFamily, - fontWeight: typography.body?.medium?.fontWeight, - ), - ), - ], - ); - }, -) -``` +All props are optional. Sorted alphabetically. - +### activateSelection - +Controls when selection mode activates. -*** +| | | +| --- | --- | +| Type | `ActivateSelection` | +| Default | `null` | -#### trailingView +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` -Customizes the trailing (end) view of a conversation item, which is typically used for action buttons or additional information. +--- -Use cases : +### addOptions -* Adding a mute/unmute button for each conversation -* Displaying the last message time in a custom format -* Showing unread message counts or notification badges +Adds to the current list of actions available on long press. - - -```dart -CometChatConversations( - trailingView: (context, conversation) { - // return tailing view - }, -) -``` +| | | +| --- | --- | +| Type | `List? Function(Conversation, CometChatConversationsController, BuildContext)` | +| Default | `null` | - +--- - +### appBarOptions -Demonstration +List of widgets to display in the app bar. - - - +| | | +| --- | --- | +| Type | `List` | +| Default | `null` | - - -```dart +--- -CometChatConversations( -trailingView: (conversation) { - int timestamp = - conversation.updatedAt?.millisecondsSinceEpoch ?? 0; - if (timestamp.toString().length == 10) { - timestamp *= - 1000; // Convert seconds to milliseconds if needed - } - - DateTime now = DateTime.now(); - DateTime lastSeen = - DateTime.fromMillisecondsSinceEpoch(timestamp); - - Duration diff = now.difference(lastSeen); - int diffInMinutes = diff.inMinutes; - int diffInHours = diff.inHours; - - String timeText; - String minText; - Color textColor; - Color cardColor; - - if (diffInMinutes == 0) { - timeText = "1"; - minText = "Min ago"; - textColor = Color(0xFF6852D6); - cardColor = Color(0x666852D6); // 40% alpha - } else if (diffInMinutes < 60) { - timeText = "$diffInMinutes"; - minText = "Min ago"; - textColor = Color(0xFF6852D6); - cardColor = Color(0x666852D6); - } else if (diffInHours < 10) { - timeText = "$diffInHours"; - minText = "Hr ago"; - textColor = Color(0xFFFFAB00); - cardColor = Color(0x66FFAB00); - } else { - timeText = "$diffInHours"; - minText = "Hr ago"; - textColor = Color(0xFFF44649); - cardColor = Color(0x66F44649); - } - return Card( - color: cardColor, - child: Padding( - padding: EdgeInsets.symmetric( - vertical: spacing.padding1 ?? 0, - horizontal: spacing.padding1 ?? 0, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - timeText, - style: TextStyle( - color: textColor, - fontSize: 16, - fontWeight: FontWeight.bold), - ), - Text( - minText, - style: TextStyle( - color: textColor, - fontSize: 16, - fontWeight: FontWeight.bold), - ), - ], - ), - ), - ); - }, -) -``` +### backButton - +Custom back button widget. - +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in back arrow | -*** +--- -#### ListItemView +### conversationsRequestBuilder -With this function, you can assign a custom ListItem view to the `CometChatConversations` Widget. +Controls which conversations load and in what order. - - -```dart -CometChatConversations( - listItemView: (conversation) { - return Placeholder(); - }, -) -``` +| | | +| --- | --- | +| Type | `ConversationsRequestBuilder` | +| Default | SDK default (30 per page) | - +Pass the builder instance, not the result of `.build()`. - +--- - - - +### conversationsStyle -**Example** +Style configuration for the component. -Here is the complete example for reference: +| | | +| --- | --- | +| Type | `CometChatConversationsStyle` | +| Default | `CometChatConversationsStyle()` | - - -```dart custom_list_item.dart -Widget getCustomListItem( - Conversation conversation, - BuildContext context - ) { - Widget? tail; - Color? statusBackgroundColor; - Widget? icon; - final lastMessageTime = conversation.lastMessage?.sentAt ?? DateTime.now(); - tail = Padding( - padding: EdgeInsets.only( - left: 8, - ), - child: CometChatDate( - date: lastMessageTime, - padding:const EdgeInsets.all(0), - style: CometChatDateStyle( - backgroundColor: Colors.transparent, - textStyle: TextStyle( - color: Color(0xFF727272), - fontSize: 12, - fontWeight: FontWeight.w400, - ), - border: - Border.all( - width: 0, - color: Colors.transparent, - ), - ), - pattern: DateTimePattern.dayDateTimeFormat, - ) - ); +--- +### customSoundForMessages - User? conversationWithUser; - Group? conversationWithGroup; - if (conversation.conversationWith is User) { - conversationWithUser = conversation.conversationWith as User; - } else { - conversationWithGroup = conversation.conversationWith as Group; - } +Path to a custom audio file for incoming message notifications. - final statusStyle = - CometChatThemeHelper.getTheme( - context: context, - defaultTheme: CometChatStatusIndicatorStyle.of); - - StatusIndicatorUtils statusIndicatorUtils = - StatusIndicatorUtils.getStatusIndicatorFromParams( - context: context, - user: conversationWithUser, - group: conversationWithGroup, - onlineStatusIndicatorColor: Color(0xFF09C26F) - ); - - statusBackgroundColor = statusIndicatorUtils.statusIndicatorColor; - icon = statusIndicatorUtils.icon; - return GestureDetector( - key: UniqueKey(), - child: CometChatListItem( - avatarHeight:48, - avatarWidth:48, - id: conversation.conversationId, - avatarName: conversationWithUser?.name ?? conversationWithGroup?.name, - avatarURL: conversationWithUser?.avatar ?? conversationWithGroup?.icon, - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFAA9EE8), - ), - title: conversationWithUser?.name ?? conversationWithGroup?.name, - key: UniqueKey(), - tailView: tail, - statusIndicatorColor: statusBackgroundColor, - statusIndicatorIcon: icon, - statusIndicatorStyle: CometChatStatusIndicatorStyle( - border: statusStyle.border ?? - Border.all( - width: 2, - color: Color(0xFFFFFFFF), - ), - backgroundColor: statusStyle.backgroundColor, - ), - hideSeparator: true, - style: ListItemStyle( - background: Colors.transparent, - titleStyle: TextStyle( - overflow: TextOverflow.ellipsis, - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414), - ), - padding: EdgeInsets.symmetric( - horizontal: 16, - vertical: 12, - ), - ), - ), - ); -} -``` +| | | +| --- | --- | +| Type | `String` | +| Default | Built-in sound | - +--- - +### datePattern - - -```dart main.dart -CometChatConversations( - listItemView: (conversation) { - return getCustomListItem( - conversation, - context - ); - }, -) -``` +Custom date format function for conversation timestamps. - +| | | +| --- | --- | +| Type | `String Function(Conversation)` | +| Default | Built-in date formatting | - +--- -*** +### deleteConversationOptionVisibility -#### TextFormatters +Controls visibility of delete option in context menu. -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | -**Example** +--- -Here is the complete example for reference: +### deliveredIcon - - -```dart -CometChatConversations( - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` +Custom icon for delivered message receipts. - +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in delivered icon | - +--- - - - +### disableSoundForMessages -*** +Disables notification sound for incoming messages. -#### AppBarOptions +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | -You can set the Custom AppBarOptions to the `CometChatConversations` widget. +--- - - - - - -```dart - CometChatConversations( - showBackButton: false, - appBarOptions: [ - PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - side: BorderSide( - color: Color(0xFFF5F5F5), - width: 1, - ), - ), - color: Color(0xFFFFFFFF), - elevation: 4, - menuPadding : EdgeInsets.zero, - padding: EdgeInsets.zero, - icon: Padding( - padding: EdgeInsets.only( - left: 12, - right: 16, - ), - child: CometChatAvatar( - width: 40, - height: 40, - image: CometChatUIKit.loggedInUser?.avatar, - name: CometChatUIKit.loggedInUser?.name, - ), - ), - onSelected: (value) { - switch (value) { - case '/Create': - setState(() { - _selectedIndex = 2; - }); - break; - case '/logout': - logout(); - break; - case '/name': - break; - case '/version': - break; - } - }, - position: PopupMenuPosition.under, - enableFeedback: false, - itemBuilder: (BuildContext context) { - return [ - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/Create', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.add_comment_outlined, - color: Color(0xFFA1A1A1), - size: 24, - ), - ), - Text( - "Create Conversation", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF141414), - ), - ), - ], - ), - ), - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/name', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.account_circle_outlined, - color: Color(0xFFA1A1A1), - size: 24, - ), - ), - Text( - CometChatUIKit.loggedInUser?.name ?? "", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF141414), - ), - ), - ], - ), - ), - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/logout', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.logout, - color: Colors.red, - size: 24, - ), - ), - Text( - "Logout", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Colors.red, - ), - ), - ], - ), - ), - PopupMenuItem( - enabled: false, - height: 44, - padding: EdgeInsets.zero, - value: '/version', - child: Container( - width: double.infinity, - decoration: BoxDecoration( - border: Border( - top: BorderSide( - color: Color(0xFFF5F5F5), - width: 1, - ), - ), - ), - child: Padding( - padding: EdgeInsets.all(16), - child: Text( - "V5.0.0_alpha1", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF727272), - ), - ), - ), - ), - ), - ]; - }, - ), - ], - onItemTap: (conversation) { - User? user; - Group? group; - if (conversation.conversationWith is User) { - user = conversation.conversationWith as User; - } else { - group = conversation.conversationWith as Group; - } - navigateToMessages(user: user, group: group); - }, - ) -``` +### emptyStateView - +Custom widget displayed when there are no conversations. - +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in empty state | -*** +--- -#### DatePattern +### errorStateView -You can modify the date pattern to your requirement using `datePattern`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. +Custom widget displayed when an error occurs. - - - +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in error state | - - -```dart -CometChatConversations( - datePattern: (conversation) => DateFormat('d MMM, hh:mm a').format(conversation.lastMessage?.sentAt ?? DateTime.now()), -) -``` +Hidden when `hideError: true`. - +--- - +### groupTypeVisibility -*** +Controls visibility of group type icon (public/private/password). -#### SubtitleView +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | -You can customize the subtitle view for each conversation item to meet your requirements +--- - - - +### hideAppbar - - -```dart -CometChatConversations( - subtitleView: (context, conversation) { - String subtitle = ""; - - if (conversation.conversationWith is User) { - User user = conversation.conversationWith as User; - final dateTime = user.lastActiveAt ?? DateTime.now(); - subtitle = "Last Active at " + DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime); - } else { - Group group = conversation.conversationWith as Group; - final dateTime = group.createdAt ?? DateTime.now(); - subtitle = "Created at " + DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime); - } - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - } -) -``` +Hides the entire app bar. - +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | - +--- + +### hideError + +Hides the default and custom error views. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search bar in the app bar. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in avatar | + +Return `null` to use the default avatar. + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(Conversation)` | +| Default | Built-in list item | + +--- + +### loadingStateView + +Custom widget displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in shimmer | + +--- + +### mentionAllLabel + +Custom label for group mentions (@channel, @everyone). + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### mentionAllLabelId + +Custom label ID for group mentions. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + + +### onBack + +Callback fired when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback` | +| Default | `null` | + +--- + +### onEmpty + +Callback fired when the conversation list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty` | +| Default | `null` | + +--- + +### onError + +Callback fired when the component encounters an error. + +| | | +| --- | --- | +| Type | `OnError` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback fired when a conversation row is long-pressed. + +| | | +| --- | --- | +| Type | `Function(Conversation)` | +| Default | `null` | + +--- + +### onItemTap + +Callback fired when a conversation row is tapped. + +| | | +| --- | --- | +| Type | `Function(Conversation)` | +| Default | `null` | + +--- + +### onLoad + +Callback fired when the conversation list is loaded. + +| | | +| --- | --- | +| Type | `OnLoad` | +| Default | `null` | + +--- + +### onSearchTap + +Callback fired when the search box is tapped. + +| | | +| --- | --- | +| Type | `GestureTapCallback` | +| Default | `null` | + +Requires `searchReadOnly: true` to work properly. + +--- + +### onSelection + +Callback fired when conversations are selected/deselected. + +| | | +| --- | --- | +| Type | `Function(List?)` | +| Default | `null` | + +Requires `selectionMode` to be set. + +--- + +### privateGroupIcon + +Custom icon for private group indicator. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### protectedGroupIcon + +Custom icon for password-protected group indicator. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### readIcon + +Custom icon for read message receipts. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in read icon | + +--- + +### receiptsVisibility + +Controls visibility of message read/delivery receipts. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + + +### scrollController + +Custom scroll controller for the list. + +| | | +| --- | --- | +| Type | `ScrollController` | +| Default | `null` | + +--- + +### searchBoxIcon + +Custom prefix icon for the search box. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in search icon | + +--- + +### searchReadOnly + +Makes the search box read-only (tap only). + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +Must pair with `onSelection` to capture selections. + +--- + +### sentIcon + +Custom icon for sent message receipts. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in sent icon | + +--- + +### setOptions + +Replaces the list of actions available on long press. + +| | | +| --- | --- | +| Type | `List? Function(Conversation, CometChatConversationsController, BuildContext)` | +| Default | `null` | + +--- + +### showBackButton + +Shows the back button in the app bar. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### subtitleView + +Custom renderer for the last message preview. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in subtitle | + +--- + +### textFormatters + +Custom text formatters for the conversation subtitle. + +| | | +| --- | --- | +| Type | `List` | +| Default | Default formatters from data source | + +See [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) for mention formatting. + +--- + +### title + +Custom title text for the app bar. + +| | | +| --- | --- | +| Type | `String` | +| Default | "Chats" | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the timestamp / badge / right section. + +| | | +| --- | --- | +| Type | `Widget? Function(Conversation)` | +| Default | Built-in trailing view | + +--- + +### typingIndicatorText + +Custom text shown when a user is typing. + +| | | +| --- | --- | +| Type | `String` | +| Default | "typing..." | + +--- + +### usersStatusVisibility + +Controls visibility of online/offline status indicator. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### avatarHeight + +Height for user/group avatars. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### avatarWidth + +Width for user/group avatars. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### avatarPadding + +Padding for user/group avatars. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### avatarMargin + +Margin for user/group avatars. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### badgeWidth + +Width for unread message badge. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### badgeHeight + +Height for unread message badge. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### badgePadding + +Padding for unread message badge. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### controllerTag + +Tag for controller management. When passed, parent is responsible for closing. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### dateBackgroundIsTransparent + +Controls whether the date background is transparent. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `null` | + +--- + +### dateHeight + +Height for the conversation date display. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### datePadding + +Padding for the conversation date display. + +| | | +| --- | --- | +| Type | `EdgeInsets` | +| Default | `null` | + +--- + +### dateTimeFormatterCallback + +Callback for custom date and time formatting. + +| | | +| --- | --- | +| Type | `DateTimeFormatterCallback` | +| Default | `null` | + +--- + +### dateWidth + +Width for the conversation date display. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### listItemStyle + +Style configuration for list items. + +| | | +| --- | --- | +| Type | `ListItemStyle` | +| Default | `null` | + +--- + +### searchContentPadding + +Padding for search box content. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### searchPadding + +Padding for the search box. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### statusIndicatorBorderRadius + +Border radius for the status indicator. + +| | | +| --- | --- | +| Type | `BorderRadiusGeometry` | +| Default | `null` | + +--- + +### statusIndicatorHeight + +Height for the status indicator. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### statusIndicatorWidth + +Width for the status indicator. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### submitIcon + +Custom submit icon for selection mode. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in check icon | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatConversationEvents.ccConversationDeleted` | `Conversation` | Conversation deleted from list | + +Subscribe using `CometChatConversationEvents.addConversationListListener()` and unsubscribe with `removeConversationListListener()`. + +--- + +## Customization Matrix -*** +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Widget props | `on` callbacks | `onItemTap: (c) => setActive(c)` | +| Filter which conversations appear | Widget props | `conversationsRequestBuilder` | `conversationsRequestBuilder: ConversationsRequestBuilder()..limit = 10` | +| Toggle visibility of UI elements | Widget props | `Visibility` boolean props | `receiptsVisibility: false` | +| Replace a section of the list item | Widget props | `View` render props | `listItemView: (conversation) => CustomWidget()` | +| Change colors, fonts, spacing | Widget props | `conversationsStyle` | `conversationsStyle: CometChatConversationsStyle(backgroundColor: Colors.white)` | From f485affa16092081120d6c0e39d91a0c01091ee7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:57:35 +0530 Subject: [PATCH 11/32] Update conversations.mdx --- ui-kit/flutter/conversations.mdx | 339 +++++++++++++++++++++++++++++-- 1 file changed, 322 insertions(+), 17 deletions(-) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index 239fda8b6..d71e86706 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -82,22 +82,37 @@ description: "Scrollable list of recent one-on-one and group conversations for t "name": "CometChatConversationEvents.ccConversationDeleted", "payload": "Conversation", "description": "Conversation deleted from list" + }, + { + "name": "CometChatConversationEvents.ccUpdateConversation", + "payload": "Conversation", + "description": "Conversation updated" } ], "sdkListeners": [ "onTextMessageReceived", "onMediaMessageReceived", "onCustomMessageReceived", + "onFormMessageReceived", + "onCardMessageReceived", + "onCustomInteractiveMessageReceived", + "onSchedulerMessageReceived", "onTypingStarted", "onTypingEnded", "onMessagesDelivered", "onMessagesRead", + "onMessagesDeliveredToAll", + "onMessagesReadByAll", + "onMessageEdited", + "onMessageDeleted", "onUserOnline", "onUserOffline", "onGroupMemberJoined", "onGroupMemberLeft", "onGroupMemberKicked", "onGroupMemberBanned", + "onGroupMemberUnbanned", + "onGroupMemberScopeChanged", "onMemberAddedToGroup" ], "compositionExample": { @@ -264,9 +279,27 @@ CometChatConversations( | Limit to 10 per page | `ConversationsRequestBuilder()..limit = 10` | | With specific tags | `ConversationsRequestBuilder()..tags = ["vip"]` | | With user and group tags | `ConversationsRequestBuilder()..withUserAndGroupTags = true` | +| Include blocked users | `ConversationsRequestBuilder()..includeBlockedUsers = true` | +| Search conversations | `ConversationsRequestBuilder()..searchKeyword = "hello"` | +| Unread only | `ConversationsRequestBuilder()..unread = true` | Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. +### ConversationsRequestBuilder Properties + +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of conversations to fetch per request. Maximum 50. | `..limit = 30` | +| `conversationType` | Filter by conversation type: `"user"` or `"group"`. If not set, returns both. | `..conversationType = "user"` | +| `withTags` | Include tags associated with conversations. Default `false`. | `..withTags = true` | +| `tags` | Filter conversations by specific tags. | `..tags = ["archived", "vip"]` | +| `withUserAndGroupTags` | Include user/group tags in the Conversation object. Default `false`. | `..withUserAndGroupTags = true` | +| `includeBlockedUsers` | Include conversations with blocked users. Default `false`. | `..includeBlockedUsers = true` | +| `withBlockedInfo` | Include blocked info in the ConversationWith object. Default `false`. | `..withBlockedInfo = true` | +| `searchKeyword` | Search conversations by user or group name. Requires Advanced plan. | `..searchKeyword = "John"` | +| `unread` | Fetch only unread conversations. Requires Advanced plan. | `..unread = true` | +| `build()` | Builds and returns a `ConversationsRequest` object. | `.build()` | + Refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations) for the full builder API. --- @@ -493,6 +526,81 @@ CometChatConversations( +For a more complete custom list item with status indicator and date: + + + +```dart +Widget getCustomListItem(Conversation conversation, BuildContext context) { + User? conversationWithUser; + Group? conversationWithGroup; + + if (conversation.conversationWith is User) { + conversationWithUser = conversation.conversationWith as User; + } else { + conversationWithGroup = conversation.conversationWith as Group; + } + + // Get status indicator + StatusIndicatorUtils statusIndicatorUtils = StatusIndicatorUtils.getStatusIndicatorFromParams( + context: context, + user: conversationWithUser, + group: conversationWithGroup, + onlineStatusIndicatorColor: Color(0xFF09C26F), + ); + + // Build tail view with date + final lastMessageTime = conversation.lastMessage?.sentAt ?? DateTime.now(); + Widget tail = CometChatDate( + date: lastMessageTime, + padding: EdgeInsets.zero, + style: CometChatDateStyle( + backgroundColor: Colors.transparent, + textStyle: TextStyle(color: Color(0xFF727272), fontSize: 12), + border: Border.all(width: 0, color: Colors.transparent), + ), + pattern: DateTimePattern.dayDateTimeFormat, + ); + + return CometChatListItem( + avatarHeight: 48, + avatarWidth: 48, + id: conversation.conversationId, + avatarName: conversationWithUser?.name ?? conversationWithGroup?.name, + avatarURL: conversationWithUser?.avatar ?? conversationWithGroup?.icon, + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFAA9EE8), + ), + title: conversationWithUser?.name ?? conversationWithGroup?.name, + tailView: tail, + statusIndicatorColor: statusIndicatorUtils.statusIndicatorColor, + statusIndicatorIcon: statusIndicatorUtils.icon, + statusIndicatorStyle: CometChatStatusIndicatorStyle( + border: Border.all(width: 2, color: Colors.white), + ), + hideSeparator: true, + style: ListItemStyle( + background: Colors.transparent, + titleStyle: TextStyle( + overflow: TextOverflow.ellipsis, + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF141414), + ), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + ); +} + +// Usage: +CometChatConversations( + listItemView: (conversation) => getCustomListItem(conversation, context), +) +``` + + + ### leadingView Replace the avatar / left section. Typing-aware avatar example. @@ -504,25 +612,67 @@ Replace the avatar / left section. Typing-aware avatar example. ```dart -Map typingMap = {}; +// In your StatefulWidget, use the MessageListener mixin: +class _ConversationsScreenState extends State with MessageListener { + Map typingMap = {}; -CometChatConversations( - leadingView: (context, conversation) { - final entity = conversation.conversationWith; - final id = entity is User ? entity.uid : (entity as Group).guid; + @override + void initState() { + super.initState(); + CometChat.addMessageListener("typing_listener", this); + } + + @override + void dispose() { + CometChat.removeMessageListener("typing_listener"); + super.dispose(); + } + + @override + void onTypingStarted(TypingIndicator typingIndicator) { + setTypingIndicator(typingIndicator, true); + } + + @override + void onTypingEnded(TypingIndicator typingIndicator) { + setTypingIndicator(typingIndicator, false); + } + + void setTypingIndicator(TypingIndicator typingIndicator, bool isTypingStarted) { + final id = typingIndicator.receiverType == ReceiverTypeConstants.user + ? typingIndicator.sender.uid + : typingIndicator.receiverId; - if (typingMap.containsKey(id)) { - return Container( - decoration: BoxDecoration( - border: Border.all(color: Color(0xFFF76808), width: 2), - borderRadius: BorderRadius.circular(8), - ), - child: Image.asset("assets/typing_icon.png", height: 40, width: 40), - ); - } - return null; // Use default avatar - }, -) + setState(() { + if (isTypingStarted) { + typingMap[id] = typingIndicator; + } else { + typingMap.remove(id); + } + }); + } + + @override + Widget build(BuildContext context) { + return CometChatConversations( + leadingView: (context, conversation) { + final entity = conversation.conversationWith; + final id = entity is User ? entity.uid : (entity as Group).guid; + + if (typingMap.containsKey(id)) { + return Container( + decoration: BoxDecoration( + border: Border.all(color: Color(0xFFF76808), width: 2), + borderRadius: BorderRadius.circular(8), + ), + child: Image.asset("assets/typing_icon.png", height: 40, width: 40), + ); + } + return null; // Use default avatar + }, + ); + } +} ``` @@ -704,6 +854,14 @@ CometChatConversations( // Pin conversation }, ), + CometChatOption( + id: "mark_unread", + title: "Mark as unread", + iconWidget: Icon(Icons.mark_chat_unread_outlined), + onClick: () { + // Mark conversation as unread + }, + ), ]; }, ) @@ -744,6 +902,106 @@ CometChatConversations( +For a more complete popup menu with styling: + + + +```dart +CometChatConversations( + showBackButton: false, + appBarOptions: [ + PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: Color(0xFFF5F5F5), width: 1), + ), + color: Colors.white, + elevation: 4, + menuPadding: EdgeInsets.zero, + padding: EdgeInsets.zero, + icon: Padding( + padding: EdgeInsets.only(left: 12, right: 16), + child: CometChatAvatar( + width: 40, + height: 40, + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + ), + onSelected: (value) { + switch (value) { + case '/create': + // Navigate to create conversation + break; + case '/logout': + CometChatUIKit.logout(); + break; + } + }, + position: PopupMenuPosition.under, + itemBuilder: (BuildContext context) { + return [ + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/create', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.add_comment_outlined, color: Color(0xFFA1A1A1), size: 24), + ), + Text("Create Conversation", style: TextStyle(fontSize: 14, color: Color(0xFF141414))), + ], + ), + ), + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/name', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.account_circle_outlined, color: Color(0xFFA1A1A1), size: 24), + ), + Text(CometChatUIKit.loggedInUser?.name ?? "", style: TextStyle(fontSize: 14, color: Color(0xFF141414))), + ], + ), + ), + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/logout', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.logout, color: Colors.red, size: 24), + ), + Text("Logout", style: TextStyle(fontSize: 14, color: Colors.red)), + ], + ), + ), + ]; + }, + ), + ], + onItemTap: (conversation) { + User? user; + Group? group; + if (conversation.conversationWith is User) { + user = conversation.conversationWith as User; + } else { + group = conversation.conversationWith as Group; + } + // Navigate to messages + }, +) +``` + + + --- @@ -937,6 +1195,17 @@ CometChatConversations( --- +## Accessibility + +The component renders a scrollable list of interactive items. Each conversation row is tappable and responds to both tap and long-press gestures. The context menu (options) is accessible via long-press. The unread badge count is exposed as text content. Avatar images include the conversation name for accessibility. + +For screen readers, the conversation list is rendered as a semantic list using Flutter's built-in accessibility features. Status indicators (online/offline, group type icons) use visual icons — consider providing custom `Semantics` widgets via `leadingView` if screen reader descriptions are needed for these visual indicators. + +When using selection mode, checkboxes are rendered with proper accessibility labels. The component respects system accessibility settings including text scaling and high contrast modes. + +--- + + ## Props All props are optional. Sorted alphabetically. @@ -1000,6 +1269,19 @@ Pass the builder instance, not the result of `.build()`. --- +### conversationsProtocol + +Custom protocol for fetching conversations. + +| | | +| --- | --- | +| Type | `ConversationsBuilderProtocol` | +| Default | `null` | + +Use this for advanced customization of how conversations are fetched. + +--- + ### conversationsStyle Style configuration for the component. @@ -1352,6 +1634,28 @@ Custom prefix icon for the search box. --- +### searchContentPadding + +Padding for search box content. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### searchPadding + +Padding for the search box. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + ### searchReadOnly Makes the search box read-only (tap only). @@ -1715,6 +2019,7 @@ Custom submit icon for selection mode. | Event | Payload | Fires when | | --- | --- | --- | | `CometChatConversationEvents.ccConversationDeleted` | `Conversation` | Conversation deleted from list | +| `CometChatConversationEvents.ccUpdateConversation` | `Conversation` | Conversation updated (last message change, metadata update) | Subscribe using `CometChatConversationEvents.addConversationListListener()` and unsubscribe with `removeConversationListListener()`. From d306c56aa6cf2befaf1d5ec39fb0c9d533568a94 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 09:50:50 +0530 Subject: [PATCH 12/32] updates components --- ui-kit/flutter/ai-assistant-chat-history.mdx | 561 +++--- ui-kit/flutter/components-overview.mdx | 194 ++- ui-kit/flutter/conversations.mdx | 181 +- ui-kit/flutter/group-members.mdx | 1330 +++++++------- ui-kit/flutter/groups.mdx | 1631 +++++++++++++----- ui-kit/flutter/message-composer.mdx | 823 ++++----- ui-kit/flutter/message-list.mdx | 1193 +++++-------- ui-kit/flutter/search.mdx | 628 ++++--- ui-kit/flutter/threaded-messages-header.mdx | 396 +++-- ui-kit/flutter/users.mdx | 1585 ++++++++++++----- 10 files changed, 5091 insertions(+), 3431 deletions(-) diff --git a/ui-kit/flutter/ai-assistant-chat-history.mdx b/ui-kit/flutter/ai-assistant-chat-history.mdx index f01aa81dc..1b2961c0f 100644 --- a/ui-kit/flutter/ai-assistant-chat-history.mdx +++ b/ui-kit/flutter/ai-assistant-chat-history.mdx @@ -1,42 +1,130 @@ --- title: "AI Assistant Chat History" +description: "A widget that displays conversation history between users and an AI assistant" --- -## Overview + +```json +{ + "component": "CometChatAIAssistantChatHistory", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that displays the conversation history between users and an AI assistant with date separators and new chat functionality", + "primaryOutput": { + "prop": "onMessageClicked", + "type": "void Function(BaseMessage? message)?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message list (one of user/group required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message list (one of user/group required)" + }, + "messagesRequestBuilder": { + "type": "MessagesRequestBuilder?", + "default": "null", + "note": "Custom request builder passed to CometChat's SDK" + } + }, + "callbacks": { + "onMessageClicked": "void Function(BaseMessage? message)?", + "onNewChatButtonClicked": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onClose": "VoidCallback?" + }, + "visibility": { + "hideStickyDate": { + "type": "bool?", + "default": "null" + }, + "hideDateSeparator": { + "type": "bool?", + "default": "null" + } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "backButton": "Widget?" + }, + "formatting": { + "dateSeparatorPattern": { + "type": "String Function(DateTime)?", + "default": "null" + }, + "dateTimeFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatAIAssistantChatHistory is typically used within AI assistant features to show past conversations", + "components": ["CometChatMessageList", "CometChatMessageComposer"], + "flow": "User opens chat history → Past messages displayed → User clicks message or starts new chat" + }, + "types": {} +} +``` + -The `AI Assistant Chat History` widget is a pre-built user interface widget designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. +## Where It Fits + +CometChatAIAssistantChatHistory is a pre-built user interface widget designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. -## Usage - -### Integration +## Minimal Render -You can launch `CometChatAIAssistantChatHistory` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatAIAssistantChatHistory` +The simplest way to render CometChatAIAssistantChatHistory: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatAIAssistantChatHistory())); // A user or group object is required to launch this widget. -``` +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +CometChatAIAssistantChatHistory( + user: user, // Required: User or Group object +) +``` - - Simply adding the `CometChatAIAssistantChatHistory` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. - -*** +You can also launch it using Navigator: -##### 2. Embedding `ChatHistory` as a Widget in the build Method + + +```dart +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatAIAssistantChatHistory( + user: user, // A user or group object is required + ), + ), +); +``` + + + +Or embed it as a widget: @@ -52,194 +140,203 @@ class ChatHistory extends StatefulWidget { } class _ChatHistoryState extends State { - @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatAIAssistantChatHistory() // A user or group object is required to launch this widget. - ) + body: SafeArea( + child: CometChatAIAssistantChatHistory( + user: user, // A user or group object is required + ), + ), ); } } ``` - - -*** - -### Actions +## Filtering -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### onNewChatButtonClicked - -`onNewChatButtonClicked` is triggered when you click on the new chat button. The `onNewChatButtonClicked` action doesn't have a predefined behavior. You can override this action using the following code snippet. +You can adjust the `MessagesRequestBuilder` to customize the message list. Numerous options are available to alter the builder to meet your specific needs. ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - onNewChatButtonClicked: () { - // TODO("Not yet implemented") - }, + user: user, + messagesRequestBuilder: MessagesRequestBuilder() + ..uid = user.uid, ) ``` - - -*** + +The following parameters in messageRequestBuilder will always be altered inside the list: +1. UID +2. GUID +3. types +4. categories + -##### onMessageClicked +For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). -You can customize this behavior by using the provided code snippet to override the `onMessageClicked`. +## Actions and Events + +### Callback Props + +Component-level callbacks that fire on specific user interactions: + +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onMessageClicked` | `void Function(BaseMessage? message)?` | User clicks a message | +| `onNewChatButtonClicked` | `VoidCallback?` | User clicks the new chat button | +| `onError` | `OnError?` | An error occurs while fetching messages | +| `onLoad` | `OnLoad?` | List is successfully loaded | +| `onEmpty` | `OnEmpty?` | List is empty | +| `onClose` | `VoidCallback?` | User clicks the back/close button | ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. + user: user, + onNewChatButtonClicked: () { + // Start a new chat session + print('New chat initiated'); + }, onMessageClicked: (message) { - // TODO("Not yet implemented") + // Navigate to the message context + print('Message clicked: ${message?.id}'); + }, + onError: (e) { + print('Error: $e'); + }, + onLoad: (list) { + print('Messages loaded: ${list.length}'); + }, + onEmpty: () { + print('No messages found'); + }, + onClose: () { + Navigator.pop(context); }, ) ``` - - -*** +### Global UI Events + +The CometChatAIAssistantChatHistory component does not produce any global UI events. -##### onError +## Custom View Slots -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Customize the appearance of CometChatAIAssistantChatHistory by replacing default views with your own widgets. + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `backButton` | `Widget?` | Back/close button | + +### Example: Custom Back Button ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") - }, + user: user, + backButton: IconButton( + icon: const Icon( + Icons.arrow_back, + color: Colors.red, + ), + onPressed: () { + Navigator.pop(context); + }, + ), ) ``` - - -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +### Example: Custom Loading State ```dart CometChatAIAssistantChatHistory( - onLoad: (list) { - // print("messages loaded: ${list.length}"); - }, + user: user, + loadingStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text('Fetching history...'), + ], + ), + ); + }, ) ``` - - -*** - -##### onEmpty - -Called when the list is empty, enabling custom handling such as showing a placeholder message. +### Example: Custom Empty State ```dart CometChatAIAssistantChatHistory( - onEmpty: () { - // print("Groups empty"); - }, + user: user, + emptyStateView: (context) { + return Center( + child: Text('No history yet. Start a new conversation!'), + ); + }, ) ``` - - -*** - -### Filters - -You can adjust the `MessagesRequestBuilder` in the CometChatAIAssistantChatHistory Widget to customize your list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). +### Date Separator Pattern -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +You can modify the date pattern of the chat history date separator using `dateSeparatorPattern`: ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - messagesRequestBuilder: MessagesRequestBuilder() - ..uid = user.uid + user: user, + dateSeparatorPattern: (DateTime dateTime) { + return DateFormat("dd/MM/yyyy").format(dateTime); + }, ) ``` - - - - -The following parameters in messageRequestBuilder will always be altered inside the list - -1. UID -2. GUID -3. types -4. categories - - - -*** - -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The CometChatAIAssistantChatHistory Widget does not emit any events of its own. +## Styling -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. CometChatAIAssistantChatHistoryStyle - -You can set the `style` to the `CometChatAIAssistantChatHistory` Widget to customize the styling. +Customize the appearance of CometChatAIAssistantChatHistory using `CometChatAIAssistantChatHistoryStyle`. ```dart final ccColor = CometChatThemeHelper.getColorPalette(context); + CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. + user: user, style: CometChatAIAssistantChatHistoryStyle( backgroundColor: const Color(0xFFFFFAF6), headerBackgroundColor: const Color(0xFFFFFAF6), headerTitleTextColor: ccColor.textPrimary, headerTitleTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + fontFamily: 'TimesNewRoman', ), newChatIconColor: ccColor.iconSecondary, newChatTextColor: ccColor.textPrimary, @@ -258,176 +355,84 @@ CometChatAIAssistantChatHistory( ), itemTextColor: ccColor.textPrimary, ), -), +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - -```dart -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - backButton: IconButton( - icon: const Icon( - Icons.ac_unit, - color: Colors.red, - ), - onPressed: () { - // TODO: Implement back button action - }, - ), -), -``` - - - - - -## CometChatMessageList Properties - -Below is a list of customizations along with corresponding code snippets: - -| Property | Data Type | Description | -| --------------------------- | --------------------------------------- | ------------------------------------------------------------- | -| `user` | `User?` | User object for the user message list. | -| `group` | `Group?` | Group object for the group message list. | -| `messagesRequestBuilder` | `MessagesRequestBuilder?` | Custom request builder passed to CometChat's SDK. | -| `loadingStateView` | `WidgetBuilder?` | View for the loading state. | -| `emptyStateView` | `WidgetBuilder?` | View for the empty state. | -| `errorStateView` | `WidgetBuilder?` | View for the error state behind the dialog. | -| `onMessageClicked` | `void Function(BaseMessage? message)?` | Callback triggered when a message is clicked. | -| `onError` | `OnError?` | Callback triggered when an error occurs while fetching users. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `onNewChatButtonClicked` | `VoidCallback?` | Callback triggered when the new chat button is clicked. | -| `style` | `CometChatAIAssistantChatHistoryStyle?` | Sets the style for the AI Assistant chat history. | -| `dateSeparatorPattern` | `String Function(DateTime dateTime)?` | Custom pattern for the date separator. | -| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | Callback to format the date and time. | -| `emptyStateText` | `String?` | Text to display when the list is empty. | -| `emptyStateSubtitleText` | `String?` | Subtitle text to display when the list is empty. | -| `errorStateText` | `String?` | Text to display when an error occurs. | -| `errorStateSubtitleText` | `String?` | Subtitle text to display when an error occurs. | -| `onClose` | `VoidCallback?` | Callback triggered when the back button is pressed. | -| `backButton` | `Widget?` | Custom widget for the back button. | -| `width` | `double?` | Sets the width of the list. | -| `height` | `double?` | Sets the height of the list. | -| `hideStickyDate` | `bool?` | Hide the sticky date separator. | -| `hideDateSeparator` | `bool?` | Hide the date separator. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### DateSeparatorPattern - -You can modify the date pattern of the chat history date separator to your requirement using `dateSeparatorPattern`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - -**Example** - -Here is the complete example for reference: - - - -```dart -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - dateSeparatorPattern: (DateTime dateTime) { - return DateFormat("dd/MM/yyyy").format(dateTime); - }, -) -``` - - - - - -*** - -#### loadingStateView - -Customizes the loading indicator when messages are being fetched. - -Use Cases: - -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching history..." text. - - - -```dart -CometChatAIAssistantChatHistory( - loadingStateView: (context) { - // return leading view - }, -) -``` - - - - - -*** - -#### emptyStateView - -Defines a custom view to be displayed when no messages are available. - -Use Cases: - -* Show a friendly message like "No history yet.". - - - -```dart -CometChatAIAssistantChatHistory( - emptyStateView: (context) { - // return empty view - }, -) -``` - - - - - -*** - -#### errorStateView - -Custom error state view displayed when fetching history fails. - -Use Cases: - -* Show a retry button when an error occurs. -* Display a friendly message like "Couldn't load history. Check your connection.". - - - -```dart -CometChatAIAssistantChatHistory( - errorStateView: (context) { - // return error view - }, -) -``` - - - - - -*** \ No newline at end of file +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message list | +| `border` | `BoxBorder?` | Border of the message list | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message list | +| `emptyStateTextStyle` | `TextStyle?` | Style of empty state text | +| `emptyStateTextColor` | `Color?` | Color of empty state text | +| `emptyStateSubtitleStyle` | `TextStyle?` | Style of empty state subtitle | +| `emptyStateSubtitleColor` | `Color?` | Color of empty state subtitle | +| `errorStateTextStyle` | `TextStyle?` | Style of error state text | +| `errorStateTextColor` | `Color?` | Color of error state text | +| `errorStateSubtitleStyle` | `TextStyle?` | Style of error state subtitle | +| `errorStateSubtitleColor` | `Color?` | Color of error state subtitle | +| `dateSeparatorStyle` | `CometChatDateStyle?` | Style for date separator | +| `newChatIconColor` | `Color?` | Color of new chat icon | +| `newChaTitleStyle` | `TextStyle?` | Style of new chat title | +| `newChatTextColor` | `Color?` | Color of new chat text | +| `itemTextStyle` | `TextStyle?` | Style of item text | +| `itemTextColor` | `Color?` | Color of item text | +| `headerBackgroundColor` | `Color?` | Background color of header | +| `headerTitleTextStyle` | `TextStyle?` | Style of header title text | +| `headerTitleTextColor` | `Color?` | Color of header title text | +| `closeIconColor` | `Color?` | Color of close icon | +| `separatorHeight` | `double?` | Height of separator | +| `separatorColor` | `Color?` | Color of separator | +| `deleteChatHistoryDialogStyle` | `CometChatConfirmDialogStyle?` | Style for delete dialog | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for user message list | +| `group` | `Group?` | `null` | Group object for group message list | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Custom request builder | +| `loadingStateView` | `WidgetBuilder?` | `null` | Custom loading view | +| `emptyStateView` | `WidgetBuilder?` | `null` | Custom empty view | +| `errorStateView` | `WidgetBuilder?` | `null` | Custom error view | +| `onMessageClicked` | `void Function(BaseMessage?)?` | `null` | Message click callback | +| `onError` | `OnError?` | `null` | Error callback | +| `onLoad` | `OnLoad?` | `null` | Load callback | +| `onEmpty` | `OnEmpty?` | `null` | Empty callback | +| `onNewChatButtonClicked` | `VoidCallback?` | `null` | New chat button callback | +| `style` | `CometChatAIAssistantChatHistoryStyle?` | `null` | Style configuration | +| `dateSeparatorPattern` | `String Function(DateTime)?` | `null` | Date separator pattern | +| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Date/time formatter | +| `emptyStateText` | `String?` | `null` | Empty state text | +| `emptyStateSubtitleText` | `String?` | `null` | Empty state subtitle | +| `errorStateText` | `String?` | `null` | Error state text | +| `errorStateSubtitleText` | `String?` | `null` | Error state subtitle | +| `onClose` | `VoidCallback?` | `null` | Close callback | +| `backButton` | `Widget?` | `null` | Custom back button | +| `width` | `double?` | `null` | Widget width | +| `height` | `double?` | `null` | Widget height | +| `hideStickyDate` | `bool?` | `null` | Hide sticky date separator | +| `hideDateSeparator` | `bool?` | `null` | Hide date separator | + + + + Display messages in a conversation + + + Compose and send messages + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/components-overview.mdx b/ui-kit/flutter/components-overview.mdx index d379c3615..f549bf175 100644 --- a/ui-kit/flutter/components-overview.mdx +++ b/ui-kit/flutter/components-overview.mdx @@ -1,47 +1,207 @@ --- title: "Overview" +description: "Browse all prebuilt UI components in the CometChat Flutter UI Kit — conversations, messages, users, groups, search, and AI." --- -CometChat's **UI Kit** is a set of pre-built UI Widget that allows you to easily craft an in-app chat with all the essential messaging features. + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init()` + `CometChatUIKit.login()` before rendering any component | +| Callback actions | `on: (param) { }` | +| Data filtering | `RequestBuilder: RequestBuilder()` | +| Toggle features | `hide: true` or `show: true` | +| Custom rendering | `View: (context, entity) => Widget` | +| Style overrides | `style: CometChatStyle(...)` | + + + +## Architecture + +The UI Kit is a set of independent widgets that compose into chat layouts. A typical two-panel layout uses four core components: + +- **CometChatConversations** — sidebar listing recent conversations (users and groups) +- **CometChatMessageHeader** — toolbar showing avatar, name, online status, and typing indicator +- **CometChatMessageList** — scrollable message feed with reactions, receipts, and threads +- **CometChatMessageComposer** — rich text input with attachments, mentions, and voice notes + +Data flow: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. + +Components communicate through a publish/subscribe event bus (`CometChatMessageEvents`, `CometChatConversationEvents`, `CometChatGroupEvents`, etc.). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/flutter/events) for the full list. + +Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and style class overrides via `CometChatStyle`. + +--- ## Type of Widget -UI Widget based on the behaviour and functionality can be categorized into three types: Base Widget, Widget, and Composite Widget. +UI Widgets based on behavior and functionality can be categorized into three types: Base Widget, Widget, and Composite Widget. ### Base Widget -Base Widget form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These Widget provide the foundational appearance and behavior for your UI. +Base Widgets form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These widgets provide the foundational appearance and behavior for your UI. ### Widget -Widget build upon Base Widget by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Widget essential for creating dynamic and interactive UIs. +Widgets build upon Base Widgets by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Widgets essential for creating dynamic and interactive UIs. ### Composite Widget -Composite Widget are advanced UI elements that combine multiple Widget or other Composite Widget to achieve complex functionality. By layering Widget together, Composite Widget offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. +Composite Widgets are advanced UI elements that combine multiple Widgets or other Composite Widgets to achieve complex functionality. By layering widgets together, Composite Widgets offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. + +--- -## Actions +## Component Catalog -Actions direct the operational behavior of a component. They are split into two categories: Predefined Actions and User-Defined Actions. +All components are imported from `cometchat_chat_uikit`. -### Predefined Actions +### Conversations and Lists -These are actions that are inherently programmed into a UI component. They are ingrained in the component itself by default, and they execute automatically in response to user interaction,without needing any additional user input. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatConversations | Scrollable list of recent conversations | `conversationsRequestBuilder`, `onItemTap`, `onError` | [Conversations](/ui-kit/flutter/conversations) | +| CometChatUsers | Scrollable list of users | `usersRequestBuilder`, `onItemTap`, `onError` | [Users](/ui-kit/flutter/users) | +| CometChatGroups | Scrollable list of groups | `groupsRequestBuilder`, `onItemTap`, `onError` | [Groups](/ui-kit/flutter/groups) | +| CometChatGroupMembers | Scrollable list of group members | `group`, `groupMemberRequestBuilder`, `onItemTap` | [Group Members](/ui-kit/flutter/group-members) | -### User-Defined Actions +### Messages -These are actions that must be explicitly specified by the user. They are not innately part of the component like predefined actions. Instead, they must be developed based on the unique needs of the user or the application. User-defined actions provide adaptability and allow for the creation of custom behaviors that align with the individual needs of the application. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatMessageHeader | Toolbar with avatar, name, status, typing indicator | `user`, `group`, `backButton`, `hideBackButton` | [Message Header](/ui-kit/flutter/message-header) | +| CometChatMessageList | Scrollable message list with reactions, receipts, threads | `user`, `group`, `messagesRequestBuilder`, `scrollToBottomOnNewMessages` | [Message List](/ui-kit/flutter/message-list) | +| CometChatMessageComposer | Rich text input with attachments, mentions, voice notes | `user`, `group`, `onSendButtonTap`, `placeholderText` | [Message Composer](/ui-kit/flutter/message-composer) | +| CometChatThreadedHeader | Parent message bubble and reply count for threaded view | `parentMessage`, `onClose`, `hideReceipts` | [Threaded Header](/ui-kit/flutter/threaded-messages-header) | -To customize the behavior of a component, actions must be overridden by the user. This provides the user with control over how the component responds to specific events or interactions. +### Search and AI -Both Widget and Composite Widget expose actions to the user, which means that users can interact with these types of Widget through predefined or user-defined actions. On the other hand, Base Widget do not expose actions to the user as they are the foundational building blocks mainly responsible for rendering the user interface and do not carry any business logic or actions. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatSearch | Real-time search input field | `onSearch`, `placeholder`, `style` | [Search](/ui-kit/flutter/search) | +| CometChatAIAssistantChatHistory | AI assistant conversation history display | `user`, `group`, `style` | [AI Assistant Chat History](/ui-kit/flutter/ai-assistant-chat-history) | -## Events +--- -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +## Component API Pattern + +All components share a consistent API surface. + +### Actions + +Actions control component behavior. They split into two categories: + +**Predefined Actions** are built into the component and execute automatically on user interaction (e.g., tapping send dispatches the message). No configuration needed. + +**User-Defined Actions** are callback props that fire on specific events. Override them to customize behavior: + + + +```dart +CometChatMessageList( + user: chatUser, + onThreadRepliesClick: (message, context, {bubbleView}) { + openThreadPanel(message); + }, + onError: (error) { + logError(error); + }, +) +``` + + + +### Events + +Events enable decoupled communication between components. A component emits events that other parts of the application can subscribe to without direct references. + + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Subscribe to message sent events +CometChatMessageEvents.onMessageSent.listen((message) { + // react to sent message +}); +``` + + + +Each component page documents its emitted events in the Events section. + +### Filters + +List-based components accept `RequestBuilder` props to control which data loads: + + + +```dart +CometChatMessageList( + user: chatUser, + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 20, +) +``` + + + +### Custom View Slots + +Components expose named view slots to replace sections of the default UI: + + + +```dart +CometChatMessageHeader( + user: chatUser, + titleView: (context, user, group) => CustomTitle(), + subtitleView: (context, user, group) => CustomSubtitle(), + leadingView: (context, user, group) => CustomAvatar(), +) +``` + + + +### Styling + +Every component accepts a style class for customization: + + + +```dart +CometChatMessageList( + user: chatUser, + style: CometChatMessageListStyle( + backgroundColor: Colors.white, + borderRadius: 8, + ), +) +``` + + -Both Widget and Composite Widget have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these Widget allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +--- ## Configurations -Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple Widget, each of these Widget will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. +Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple Widgets, each of these Widgets will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. + +--- + +## Next Steps + + + + Set up the Flutter UI Kit in your project + + + Customize colors, fonts, and styles + + + Add-on features like polls, stickers, and translation + + + Task-oriented tutorials for common patterns + + diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index d71e86706..be2091653 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -17,64 +17,134 @@ description: "Scrollable list of recent one-on-one and group conversations for t "props": { "data": { "conversationsRequestBuilder": { - "type": "ConversationsRequestBuilder", + "type": "ConversationsRequestBuilder?", "default": "SDK default (30 per page)", "note": "Pass the builder, not the result of .build()" + }, + "conversationsProtocol": { + "type": "ConversationsBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching conversations" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Chats", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "mentionAllLabel": { + "type": "String?", + "default": "null", + "note": "Custom label for @all mentions" + }, + "mentionAllLabelId": { + "type": "String?", + "default": "null", + "note": "Custom label ID for @all mentions" } }, "callbacks": { - "onItemTap": "Function(Conversation conversation)", - "onItemLongPress": "Function(Conversation conversation)", - "onSelection": "Function(List? list)", - "onBack": "VoidCallback", - "onError": "OnError", - "onLoad": "OnLoad", - "onEmpty": "OnEmpty", - "onSearchTap": "GestureTapCallback" + "onItemTap": "Function(Conversation conversation)?", + "onItemLongPress": "Function(Conversation conversation)?", + "onSelection": "Function(List? list)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onSearchTap": "GestureTapCallback?", + "datePattern": "String Function(Conversation conversation)?", + "dateTimeFormatterCallback": "DateTimeFormatterCallback?" }, "visibility": { - "receiptsVisibility": { "type": "bool", "default": true }, - "usersStatusVisibility": { "type": "bool", "default": true }, - "groupTypeVisibility": { "type": "bool", "default": true }, - "deleteConversationOptionVisibility": { "type": "bool", "default": true }, - "hideAppbar": { "type": "bool", "default": false }, - "hideError": { "type": "bool", "default": false }, - "hideSearch": { "type": "bool", "default": false }, - "showBackButton": { "type": "bool", "default": false } + "receiptsVisibility": { "type": "bool?", "default": true }, + "usersStatusVisibility": { "type": "bool?", "default": true }, + "groupTypeVisibility": { "type": "bool?", "default": true }, + "deleteConversationOptionVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideError": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool?", "default": false }, + "showBackButton": { "type": "bool", "default": false }, + "dateBackgroundIsTransparent": { "type": "bool?", "default": null }, + "searchReadOnly": { "type": "bool", "default": false } }, "sound": { - "disableSoundForMessages": { "type": "bool", "default": false }, - "customSoundForMessages": { "type": "String", "default": "built-in" } + "disableSoundForMessages": { "type": "bool?", "default": false }, + "customSoundForMessages": { "type": "String?", "default": "built-in" } }, "selection": { "selectionMode": { - "type": "SelectionMode", + "type": "SelectionMode?", "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], "default": "null" }, "activateSelection": { - "type": "ActivateSelection", + "type": "ActivateSelection?", "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], "default": "null" } }, "viewSlots": { - "listItemView": "Widget Function(Conversation conversation)", - "leadingView": "Widget? Function(BuildContext context, Conversation conversation)", - "titleView": "Widget? Function(BuildContext context, Conversation conversation)", - "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)", - "trailingView": "Widget? Function(Conversation conversation)", - "loadingStateView": "WidgetBuilder", - "emptyStateView": "WidgetBuilder", - "errorStateView": "WidgetBuilder", - "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)", - "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)" + "listItemView": "Widget Function(Conversation conversation)?", + "leadingView": "Widget? Function(BuildContext context, Conversation conversation)?", + "titleView": "Widget? Function(BuildContext context, Conversation conversation)?", + "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)?", + "trailingView": "Widget? Function(Conversation conversation)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)?", + "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)?" }, "formatting": { "textFormatters": { - "type": "List", + "type": "List?", "default": "default formatters from data source" + }, + "typingIndicatorText": { + "type": "String?", + "default": "typing..." } + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "protectedGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "privateGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "readIcon": { "type": "Widget?", "default": "built-in read icon" }, + "deliveredIcon": { "type": "Widget?", "default": "built-in delivered icon" }, + "sentIcon": { "type": "Widget?", "default": "built-in sent icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" } + }, + "layout": { + "datePadding": { "type": "EdgeInsets?", "default": "null" }, + "dateHeight": { "type": "double?", "default": "null" }, + "dateWidth": { "type": "double?", "default": "null" }, + "badgeWidth": { "type": "double?", "default": "null" }, + "badgeHeight": { "type": "double?", "default": "null" }, + "badgePadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "avatarWidth": { "type": "double?", "default": "null" }, + "avatarHeight": { "type": "double?", "default": "null" }, + "avatarPadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "avatarMargin": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "statusIndicatorWidth": { "type": "double?", "default": "null" }, + "statusIndicatorHeight": { "type": "double?", "default": "null" }, + "statusIndicatorBorderRadius": { "type": "BorderRadiusGeometry?", "default": "null" }, + "searchPadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "searchContentPadding": { "type": "EdgeInsetsGeometry?", "default": "null" } + }, + "style": { + "conversationsStyle": { "type": "CometChatConversationsStyle", "default": "CometChatConversationsStyle()" }, + "listItemStyle": { "type": "ListItemStyle?", "default": "null" }, + "appBarOptions": { "type": "List?", "default": "null" } } }, "events": [ @@ -87,6 +157,16 @@ description: "Scrollable list of recent one-on-one and group conversations for t "name": "CometChatConversationEvents.ccUpdateConversation", "payload": "Conversation", "description": "Conversation updated" + }, + { + "name": "CometChatConversationEvents.ccMessageRead", + "payload": "BaseMessage", + "description": "Message marked as read" + }, + { + "name": "CometChatConversationEvents.ccMessageSent", + "payload": "BaseMessage, MessageStatus", + "description": "Message sent" } ], "sdkListeners": [ @@ -107,23 +187,35 @@ description: "Scrollable list of recent one-on-one and group conversations for t "onMessageDeleted", "onUserOnline", "onUserOffline", + "ccUserBlocked", "onGroupMemberJoined", "onGroupMemberLeft", "onGroupMemberKicked", "onGroupMemberBanned", "onGroupMemberUnbanned", "onGroupMemberScopeChanged", - "onMemberAddedToGroup" + "onMemberAddedToGroup", + "ccOwnershipChanged", + "ccGroupLeft", + "ccGroupDeleted", + "ccGroupMemberAdded", + "onIncomingCallReceived", + "onOutgoingCallAccepted", + "onOutgoingCallRejected", + "onIncomingCallCancelled", + "onCallEndedMessageReceived", + "onConnected" ], "compositionExample": { "description": "Sidebar conversations wired to message view", "components": [ "CometChatConversations", + "CometChatMessages", "CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer" ], - "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to MessageHeader, MessageList, MessageComposer" + "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to CometChatMessages or individual MessageHeader, MessageList, MessageComposer" }, "types": { "CometChatOption": { @@ -137,6 +229,10 @@ description: "Scrollable list of recent one-on-one and group conversations for t "single": "SelectionMode.single", "multiple": "SelectionMode.multiple", "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" } } } @@ -2034,3 +2130,20 @@ Subscribe using `CometChatConversationEvents.addConversationListListener()` and | Toggle visibility of UI elements | Widget props | `Visibility` boolean props | `receiptsVisibility: false` | | Replace a section of the list item | Widget props | `View` render props | `listItemView: (conversation) => CustomWidget()` | | Change colors, fonts, spacing | Widget props | `conversationsStyle` | `conversationsStyle: CometChatConversationsStyle(backgroundColor: Colors.white)` | + +--- + + + + Display and select from a list of users + + + Display and select from a list of groups + + + Display messages in a conversation + + + Customize the look and feel of components + + diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index 693396536..b5beb1fb3 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -1,987 +1,1103 @@ --- title: "Group Members" +description: "Displays all members of a group in a searchable, scrollable list with member scope badges and management actions." --- -## Overview + +```json +{ + "component": "CometChatGroupMembers", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Displays all members of a group in a searchable, scrollable list with member scope badges and management actions.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(GroupMember groupMember)?" + }, + "props": { + "data": { + "group": { + "type": "Group", + "default": "required", + "note": "The group object to fetch members from" + }, + "groupMembersRequestBuilder": { + "type": "GroupMembersRequestBuilder?", + "default": "null", + "note": "Custom request builder for filtering members" + }, + "groupMembersProtocol": { + "type": "GroupMembersBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching group members" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + } + }, + "callbacks": { + "onItemTap": "Function(GroupMember groupMember)?", + "onItemLongPress": "Function(GroupMember groupMember)?", + "onSelection": "Function(List?)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "stateCallBack": "Function(CometChatGroupMembersController controller)?" + }, + "visibility": { + "showBackButton": { "type": "bool", "default": true }, + "hideSearch": { "type": "bool", "default": false }, + "hideSeparator": { "type": "bool?", "default": null }, + "hideError": { "type": "bool?", "default": null }, + "hideAppbar": { "type": "bool?", "default": null }, + "usersStatusVisibility": { "type": "bool?", "default": true }, + "hideKickMemberOption": { "type": "bool?", "default": null }, + "hideBanMemberOption": { "type": "bool?", "default": null }, + "hideScopeChangeOption": { "type": "bool?", "default": null } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(GroupMember)?", + "leadingView": "Widget? Function(BuildContext, GroupMember)?", + "titleView": "Widget? Function(BuildContext, GroupMember)?", + "subtitleView": "Widget? Function(BuildContext, GroupMember)?", + "trailingView": "Function(BuildContext, GroupMember)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?", + "addOptions": "List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?", + "appBarOptions": "List?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "selectIcon": { "type": "Widget?", "default": "built-in selection icon" } + }, + "formatting": { + "searchPlaceholder": { "type": "String?", "default": "null" }, + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "style": { + "style": { "type": "CometChatGroupMembersStyle?", "default": "null" } + } + }, + "events": [ + { "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", "payload": "Action, GroupMember, String newScope, String oldScope, Group", "description": "Member scope changed" }, + { "name": "CometChatGroupEvents.ccGroupMemberBanned", "payload": "Action, GroupMember, User bannedBy, Group", "description": "Member banned from group" }, + { "name": "CometChatGroupEvents.ccGroupMemberKicked", "payload": "Action, GroupMember, User kickedBy, Group", "description": "Member kicked from group" } + ], + "sdkListeners": [ + "onGroupMemberScopeChanged", + "onGroupMemberKicked", + "onGroupMemberLeft", + "onGroupMemberBanned", + "onGroupMemberJoined", + "onMemberAddedToGroup", + "onUserOnline", + "onUserOffline" + ], + "compositionExample": { + "description": "Group member list wired to group details or member actions", + "components": [ + "CometChatGroupMembers", + "CometChatGroups", + "CometChatMessages" + ], + "flow": "CometChatGroups emits Group -> pass to CometChatGroupMembers -> onItemTap emits GroupMember for actions" + }, + "types": { + "GroupMember": { + "uid": "String", + "name": "String", + "avatar": "String?", + "scope": "String (owner/admin/moderator/participant)", + "joinedAt": "DateTime?" + }, + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + } + } +} +``` + -`CometChatGroupMembers` is a versatile [Widget](/ui-kit/flutter/components-overview#components) designed to showcase all users who are either added to or invited to a group, thereby enabling them to participate in group discussions, access shared content, and engage in collaborative activities. `CometChatGroupMembers` have the capability to communicate in real-time through messaging, voice and video calls, and various other interactions. Additionally, they can interact with each other, share files, and join calls based on the permissions established by the group administrator or owner. - - - +## Where It Fits -The `CometChatGroupMembers` widget is composed of the following BaseWidgets: - -| Widgets | Description | -| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [CometChatListBase](/ui-kit/flutter/list-base) | `CometChatListBase` serves as a container widget equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list widget. | -| [CometChatListItem](/ui-kit/flutter/list-item) | This widget renders information extracted from a `User` object onto a tile, featuring a title, subtitle, leading widget, and trailing widget. experience, facilitating seamless navigation and interaction within the widget. | +`CometChatGroupMembers` displays all members of a group with their roles (owner, admin, moderator, participant). It provides member management actions like kick, ban, and scope change. Wire it to `CometChatGroups` to show members when a group is selected. -*** + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -## Usage +class GroupMembersScreen extends StatelessWidget { + final Group group; -### Integration + const GroupMembersScreen({super.key, required this.group}); -`CometChatGroupMembers` , as a Composite Widget, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: CometChatGroupMembers( + group: group, + onItemTap: (groupMember) { + // Handle member tap - show profile or actions + print("Tapped: ${groupMember.name}"); + }, + ), + ), + ); + } +} +``` + + -You can launch `CometChatGroupMembers` directly using `Navigator.push` , or you can define it as a widget within the `build` method of your `State` class. + + + -##### 1. Using Navigator to Launch `CometChatGroupMembers` +The `CometChatGroupMembers` widget is composed of the following BaseWidgets: - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatGroupMembers(group: Group(guid: "", name: "", type: "")))); // A group object is required to launch this widget. -``` +| Widgets | Description | +| --- | --- | +| [CometChatListBase](/ui-kit/flutter/list-base) | Container widget with title, search functionality, and background settings | +| [CometChatListItem](/ui-kit/flutter/list-item) | Renders member information with title, subtitle, leading, and trailing widgets | - +--- - -##### 2. Embedding `CometChatGroupMembers` as a Widget in the build Method +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class GroupMembers extends StatefulWidget { - const GroupMembers({super.key}); +class GroupMembersDemo extends StatelessWidget { + final Group group; - @override - State createState() => _GroupMembersState(); -} + const GroupMembersDemo({super.key, required this.group}); -class _GroupMembersState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), - ) // A group object is required to launch this widget. - ) + body: SafeArea( + child: CometChatGroupMembers( + group: group, + ), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatGroupMembers( + group: Group(guid: "group_id", name: "Group Name", type: GroupTypeConstants.public), + ), + ), +); +``` -##### 1. onItemTap +--- -This method proves valuable when users seek to override onItemClick functionality within `CometChatGroupMembers` , empowering them with greater control and customization options. +## Filtering Group Members -The `onItemTap` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `GroupMembersRequestBuilder` to `groupMembersRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onItemTap: (groupMember) { - // TODO("Not yet implemented") - }, + group: group, + groupMembersRequestBuilder: GroupMembersRequestBuilder(group.guid) + ..limit = 10, ) ``` - - -*** +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Limit to 10 per page | `GroupMembersRequestBuilder(guid)..limit = 10` | +| Search by keyword | `GroupMembersRequestBuilder(guid)..searchKeyword = "john"` | +| Filter by scopes | `GroupMembersRequestBuilder(guid)..scopes = ["admin", "moderator"]` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + -##### 2. onItemLongPress +### GroupMembersRequestBuilder Properties -This method becomes invaluable when users seek to override long-click functionality within `CometChatGroupMembers` , offering them enhanced control and flexibility in their interactions. +| Property | Description | Code | +| --- | --- | --- | +| `guid` | Group ID (required) | `GroupMembersRequestBuilder("group_id")` | +| `limit` | Number of members to fetch per request | `..limit = 30` | +| `searchKeyword` | Search members by name | `..searchKeyword = "John"` | +| `scopes` | Filter by member scopes | `..scopes = ["admin"]` | +| `build()` | Builds and returns a `GroupMembersRequest` object | `.build()` | -The `onItemLongPress` action doesn't have a predefined behavior. You can override this action using the following code snippet. +### Custom Protocol Builder + +Use `GroupMembersBuilderProtocol` to customize both the initial list and search results: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +class CustomProtocolBuilder extends GroupMembersBuilderProtocol { + const CustomProtocolBuilder(super.builder); + + @override + GroupMembersRequest getRequest() { + return requestBuilder.build(); + } + + @override + GroupMembersRequest getSearchRequest(String val) { + requestBuilder.searchKeyword = val; + return requestBuilder.build(); + } +} + +// Usage CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onItemLongPress: (groupMember) { - // TODO("Not yet implemented") - }, + group: group, + groupMembersProtocol: CustomProtocolBuilder( + GroupMembersRequestBuilder(group.guid)..scopes = ["admin", "moderator"], + ), ) ``` - - -*** +--- + + +## Actions and Events + +### Callback Props -##### 3. onBack +#### onItemTap -Enhance your application's functionality by leveraging the `onBack` feature. This capability allows you to customize the behavior associated with navigating back within your app. Utilize the provided code snippet to override default behaviors and tailor the user experience according to your specific requirements. +Fires when a member row is tapped. Use for showing member profile or custom actions. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onBack: () { - // TODO("Not yet implemented") + group: group, + onItemTap: (groupMember) { + print("Selected: ${groupMember.name}"); }, ) ``` - - -*** +#### onItemLongPress -##### 4. onError - -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Fires when a member row is long-pressed. Useful for showing context menus. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") + group: group, + onItemLongPress: (groupMember) { + // Show custom context menu }, ) ``` - - -*** - -##### 5. onSelection - -When the `onSelection` event is triggered, it furnishes the list of selected members. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected members. +#### onSelection -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Fires when members are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. + group: group, selectionMode: SelectionMode.multiple, activateSelection: ActivateSelection.onClick, - onSelection: (groupMembersList) { - // TODO("Not yet implemented") + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} members"); }, ) ``` - - -*** - -##### onLoad +#### onError -Invoked when the list is successfully fetched and loaded, helping track component readiness.. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatGroupMembers( - onLoad: (list) { - // print("members loaded: ${list.length}"); - }, + group: group, + onError: (error) { + print("CometChatGroupMembers error: $error"); + }, ) ``` - - -*** -##### onEmpty +#### onBack -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the back button is pressed. ```dart CometChatGroupMembers( - onEmpty: () { - // print("Group Members empty"); - }, + group: group, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Widget` . You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. - -##### 1. GroupMembersRequestBuilder +#### onLoad -| Property | Description | Code | -| ------------------ | -------------------------------------------------------- | ------------------------ | -| **GUID** | Group ID for the group whose members are to be fetched. | `guid: String` | -| **Limit** | Number of results to limit the query. | `limit: int?` | -| **Search Keyword** | Keyword for searching members within the group. | `searchKeyword: String?` | -| **Scopes** | List of scopes for filtering members (e.g., moderators). | `scopes: List?` | - -**Example** - -In the example below, we are applying a filter to the Group List based on limit and scope. +Fires when the member list is successfully loaded. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - groupMembersRequestBuilder: GroupMembersRequestBuilder("") - ..limit = 10 + group: group, + onLoad: (list) { + print("Loaded ${list.length} members"); + }, ) ``` - - -##### 2. GroupMembersProtocol - -The `GroupMembersProtocol` uses [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) enables you to filter and customize the search list based on available parameters in GroupsRequestBuilder. - -This feature allows you to keep uniformity between the displayed Group Members List and Searched Group Members List. - -Here is the complete example for reference: - -**Example** - - - -```dart custom_protocol_builder.dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -class CustomProtocolBuilder extends GroupMembersBuilderProtocol { - const CustomProtocolBuilder(super.builder); - - @override - GroupMembersRequest getRequest() { - return requestBuilder.build(); - } - - @override - GroupMembersRequest getSearchRequest(String val) { - requestBuilder.searchKeyword = val; - return requestBuilder.build(); - } -} -``` - - +#### onEmpty - +Fires when the member list is empty. -```dart main.dart +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - groupMembersProtocol: CustomProtocolBuilder(GroupMembersRequestBuilder("")..searchKeyword = "searchKeyword"), + group: group, + onEmpty: () { + print("No members found"); + }, ) ``` - - -*** - -### Events +### Global UI Events -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget` . By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +`CometChatGroupEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -Events emitted by the Join Group widget is as follows. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupMemberScopeChanged` | A member's scope is changed | `Action, User, String scopeChangedTo, String scopeChangedFrom, Group` | +| `ccGroupMemberBanned` | A member is banned | `Action, User, User bannedBy, Group` | +| `ccGroupMemberKicked` | A member is kicked | `Action, User, User kickedBy, Group` | -| Event | Description | -| ----------------------------- | ----------------------------------------------------------------- | -| **ccGroupMemberBanned** | Triggers when the group member banned from the group successfully | -| **ccGroupMemberKicked** | Triggers when the group member kicked from the group successfully | -| **ccGroupMemberScopeChanged** | Triggers when the group member scope is changed in the group | +When to use: sync external UI with member changes. For example, update a member count badge when a member is kicked. -**Example** -```dart your_screen.dart +```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_sdk/models/action.dart' as cc; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatGroupEventListener { @override void initState() { super.initState(); - CometChatGroupEvents.addGroupsListener("listenerId", this); // Add the listener + CometChatGroupEvents.addGroupsListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatGroupEvents.removeGroupsListener("listenerId"); super.dispose(); - CometChatGroupEvents.removeGroupsListener("listenerId"); // Remove the listener } @override void ccGroupMemberScopeChanged(cc.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // TODO("Not yet implemented") + print("${updatedUser.name} scope changed to $scopeChangedTo"); } @override void ccGroupMemberBanned(cc.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // TODO("Not yet implemented") + print("${bannedUser.name} was banned from ${bannedFrom.name}"); } @override void ccGroupMemberKicked(cc.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // TODO("Not yet implemented") + print("${kickedUser.name} was kicked from ${kickedFrom.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** +### SDK Events (Real-Time, Automatic) -## Customization +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -To fit your app's design requirements, you can customize the appearance of the Groups widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberScopeChanged` | Updates member scope badge | +| `onGroupMemberKicked` | Removes member from list | +| `onGroupMemberLeft` | Removes member from list | +| `onGroupMemberBanned` | Removes member from list | +| `onGroupMemberJoined` | Adds new member to list | +| `onMemberAddedToGroup` | Adds new member to list | +| `onUserOnline` | Updates online status indicator | +| `onUserOffline` | Updates offline status indicator | -### Style - -You can set the `CometChatGroupMembersStyle` to the `CometChatGroupMembers` Widget to customize the styling. - - - -```dart -CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - style: CometChatGroupMembersStyle( - titleStyle: TextStyle(color: Color(0xFFF76808)), - separatorColor: Color(0xFFF76808), - ownerMemberScopeBackgroundColor: Color(0xFFF76808), - adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), - adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), - adminMemberScopeTextColor: Color(0xFFF76808), - moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), - moderatorMemberScopeTextColor: Color(0xFFF76808), - backIconColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a member parameter receive the `GroupMember` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(GroupMember)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, GroupMember)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, GroupMember)` | Member name | +| `subtitleView` | `Widget? Function(BuildContext, GroupMember)` | Secondary text | +| `trailingView` | `Function(BuildContext, GroupMember)` | Scope badge / right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Group, GroupMember, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Group, GroupMember, Controller, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - hideSeparator: true, - hideSearch: true, - showBackButton: false + group: group, + listItemView: (groupMember) { + return ListTile( + leading: CometChatAvatar( + image: groupMember.avatar, + name: groupMember.name, + ), + title: Text(groupMember.name ?? ''), + subtitle: Text(groupMember.scope ?? 'participant'), + trailing: Icon(Icons.chevron_right), + ); + }, ) ``` - - -## List of properties exposed by `CometChatGroupMembers` - -| Property | Data Type | Description | -| ---------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -| `groupMembersProtocol` | `GroupMembersBuilderProtocol?` | Custom request builder protocol for fetching group members. | -| `groupMembersRequestBuilder` | `GroupMembersRequestBuilder?` | Custom request builder for fetching group members. | -| `subtitleView` | `Widget? Function(BuildContext, GroupMember)?` | Widget to set subtitle for each group member. | -| `hideSeparator` | `bool?` | Toggle visibility of separator. | -| `listItemView` | `Widget Function(GroupMember)?` | Custom view for each group member item. | -| `style` | `CometChatGroupMembersStyle?` | Sets style for \[CometChatGroupMembers]. | -| `controller` | `ScrollController?` | Sets controller for the list. | -| `options` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | Options visible at the slide of each group member. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Specifies mode group members module is opening in. | -| `onSelection` | `Function(List?)?` | Callback for handling group member selection. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `hideError` | `bool?` | Toggle visibility of error dialog. | -| `stateCallBack` | `Function(CometChatGroupMembersController)?` | Callback to access controller functions from the parent. | -| `appBarOptions` | `List?` | Options available in the app bar. | -| `group` | `Group` | Group object passed to fetch members. | -| `trailingView` | `Function(BuildContext, GroupMember)?` | Custom widget for the trailing section of the group member list item. | -| `submitIcon` | `Widget?` | Widget for the submit icon. | -| `selectIcon` | `Widget?` | Widget for the selection icon. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(GroupMember)?` | Callback triggered when tapping a group member item. | -| `onItemLongPress` | `Function(GroupMember)?` | Callback triggered on long press of a group member item. | -| `activateSelection` | `ActivateSelection?` | Lets the widget know if group members can be selected. | -| `onError` | `OnError?` | Callback for handling errors. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `controllerTag` | `String?` | Tag for accessing the widget's GetXController. | -| `hideAppbar` | `bool?` | Flag to hide the app bar. | -| `searchKeyword` | `String?` | Keyword to fetch the initial list with. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `leadingStateView` | `Widget? Function(BuildContext, GroupMember)?` | Widget for the leading section of each group member. | -| `titleView` | `Widget? Function(BuildContext, GroupMember)?` | Custom title view for each group member. | -| `usersStatusVisibility` | `bool?` | Controls visibility of the user status indicator on the avatar (default: true). | -| `hideBanMemberOption` | `bool?` | Flag to hide the ban member option. | -| `hideKickMemberOption` | `bool?` | Flag to hide the kick member option. | -| `hideScopeChangeOption` | `bool?` | Flag to hide the scope change option. | -| `setOptions` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | List of actions available on long press of group member item. | -| `addOptions` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | Adds to the current list of actions on long press of a group member item. | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widgets and then incorporate those into the widget. - -The `CometChatGroupMembers` widget does not provide additional functionalities beyond this level of customization. - -#### setOptions - -Defines a set of available actions that users can perform when they interact with a group member item. - -* Provide actions like "View Profile", "Send Message", "Remove from Group". -* Restrict certain actions to admins (e.g., "Promote to Admin", "Ban User"). - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. Online status indicator example. ```dart CometChatGroupMembers( - setOptions: (group, groupMember, controller, context) { - // return options + group: group, + leadingView: (context, groupMember) { + return Stack( + children: [ + CometChatAvatar( + image: groupMember.avatar, + name: groupMember.name, + style: CometChatAvatarStyle(borderRadius: BorderRadius.circular(20)), + ), + Positioned( + bottom: 0, + right: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: groupMember.status == "online" ? Color(0xFF09C26F) : Colors.grey, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + ), + ), + ), + ], + ); }, ) ``` - - -*** - -#### addOptions +### titleView -Adds custom actions to the existing options available when interacting with a group member. - -* Extend functionality by adding "Block User", "Report User", or "View Activity". -* Customize actions based on member roles. +Replace the member name. Role badge inline example. ```dart CometChatGroupMembers( - addOptions: (group, groupMember, controller, context) { - // return options + group: group, + titleView: (context, groupMember) { + return Row( + children: [ + Text( + groupMember.name ?? '', + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + if (groupMember.scope == GroupMemberScope.owner) ...[ + SizedBox(width: 4), + Icon(Icons.star, size: 16, color: Color(0xFFF76808)), + ], + ], + ); }, ) ``` - - -*** -#### loadingStateView +### subtitleView -Displays a custom loading view while group members are being fetched. +Replace the secondary text. Join date example. -* Show a loading spinner with "Fetching group members...". -* Implement a skeleton loader for a smoother UI experience. + + + ```dart CometChatGroupMembers( - loadingStateView: (context) { - // return loading view + group: group, + subtitleView: (context, groupMember) { + final dateTime = groupMember.joinedAt ?? DateTime.now(); + return Text( + "Joined ${DateFormat('dd/MM/yyyy').format(dateTime)}", + style: TextStyle(color: Color(0xFF727272), fontSize: 14), + ); }, ) ``` - - -*** - -#### emptyStateView +### trailingView -Configures a view to be displayed when no group members are found. +Replace the scope badge / right section. Custom scope badge example. -* Display a message like "No members in this group yet.". -* Show a button to Invite Members. + + + ```dart CometChatGroupMembers( - emptyStateView: (context) { - // return empty view + group: group, + trailingView: (context, groupMember) { + Color backgroundColor = Color(0xFFEDEAFA); + Color textColor = Color(0xFF6852D6); + String scope = groupMember.scope ?? GroupMemberScope.participant; + + if (groupMember.uid == group.owner) { + scope = GroupMemberScope.owner; + backgroundColor = Color(0xFF6852D6); + textColor = Colors.white; + } + + return Container( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(1000), + ), + child: Text( + scope.capitalizeFirst ?? "", + style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w400), + ), + ); }, ) ``` - - -*** -#### errorStateView +### setOptions -Defines a custom error state view when there is an issue loading group members. - -* Display a retry button with "Failed to load members. Tap to retry.". -* Show an illustration for a better user experience. +Replace the context menu / long-press actions on each member item. ```dart CometChatGroupMembers( - errorStateView: (context) { - // return error view + group: group, + setOptions: (group, groupMember, controller, context) { + return [ + CometChatOption( + id: "view_profile", + title: "View Profile", + iconWidget: Icon(Icons.person_outline), + onClick: () { + // Navigate to member profile + }, + ), + CometChatOption( + id: "message", + title: "Send Message", + iconWidget: Icon(Icons.message_outlined), + onClick: () { + // Start direct message + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView - -Sets a custom leading view for each group member item, usually used for profile images or avatars. +### addOptions -* Show a circular avatar with an online/offline indicator. -* Add a role-based badge (Admin, Moderator, Member). +Add to the existing context menu actions without removing defaults. ```dart CometChatGroupMembers( - leadingView: (context, groupMember) { - // return leading view - }, + group: group, + addOptions: (group, groupMember, controller, context) { + return [ + CometChatOption( + id: "report", + title: "Report User", + iconWidget: Icon(Icons.flag_outlined), + onClick: () { + // Report user logic + }, + ), + ]; + }, ) ``` - - -*** - -#### titleView +### appBarOptions -Customizes the title view, typically displaying the member's name. +Add custom widgets to the app bar. -* Customize fonts, colors, or styles for usernames. -* Add role-specific indicators like "(Group Admin)". + + + ```dart CometChatGroupMembers( - titleView: (context, groupMember) { - // return title view - }, + group: group, + appBarOptions: [ + IconButton( + onPressed: () { + // Navigate to add members + }, + icon: Icon(Icons.person_add_alt_1, color: Color(0xFF6852D6)), + ), + ], ) ``` - - -*** -#### ListItemView +### loadingStateView -With this function, you can assign a custom ListItem to the `CometChatGroupMembers` Widget. +Custom view displayed while members are being fetched. -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - listItemView: (groupMember) { - return Placeholder(); // Replace this placeholder with your custom widget. + group: group, + loadingStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text("Loading members..."), + ], + ), + ); }, ) ``` - - -Here is the complete example for reference: - -**Example** +### emptyStateView -You can indeed create a custom widget named `custom_list_item.dart` for more complex or unique list items. +Custom view displayed when no members are found. -```dart custom_list_item.dart - Widget _getTailView(GroupMember groupMember, Group group) { - Color? backgroundColor; - BoxBorder? border; - String scope = groupMember.scope ?? GroupMemberScope.participant; - Color? textColor; - TextStyle? textStyle; - - if (groupMember.uid == group.owner) { - scope = GroupMemberScope.owner; - backgroundColor = Color(0xFF6852D6); - textColor = Colors.white; - } else if (scope == GroupMemberScope.admin) { - backgroundColor = Color(0xFFEDEAFA); - border = Border.all(color: Color(0xFF6852D6), width: 1); - textColor = Color(0xFF6852D6); - } else if (scope == GroupMemberScope.moderator) { - backgroundColor = Color(0xFFEDEAFA); - textColor = Color(0xFF6852D6); - } else { - return const SizedBox(); - } - - return Container( - alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4 ?? 0), - decoration: BoxDecoration( - color: backgroundColor, - border: border, - borderRadius: BorderRadius.circular(1000), - ), - child: Text( - scope.capitalizeFirst ?? "", - style: TextStyle( - fontSize: 12, fontWeight: FontWeight.w400, color: textColor) - .merge(textStyle) - .copyWith(color: textColor), +```dart +CometChatGroupMembers( + group: group, + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No members found"), + ], ), ); - } - - Widget getCustomListItemView( - GroupMember member, - Group group, - BuildContext context, - ) { - Widget? subtitle; - Widget? tail; - Color? backgroundColor; - Widget? icon; - - tail = _getTailView(member, group); - - StatusIndicatorUtils statusIndicatorUtils = - StatusIndicatorUtils.getStatusIndicatorFromParams( - context: context, - groupMember: member, - onlineStatusIndicatorColor: Color(0xFF09C26F), - usersStatusVisibility: true, - ); - - backgroundColor = statusIndicatorUtils.statusIndicatorColor; - icon = statusIndicatorUtils.icon; - - return Padding( - padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16), - child: CometChatListItem( - id: member.uid, - avatarName: member.name, - avatarURL: member.avatar, - title: member.name, - key: UniqueKey(), - subtitleView: subtitle, - tailView: tail, - avatarStyle: const CometChatAvatarStyle( - borderRadius: BorderRadius.all(Radius.circular(12)), - ), - avatarHeight: 40, - avatarWidth: 40, - statusIndicatorColor: backgroundColor, - statusIndicatorIcon: icon, - hideSeparator: true, - style: ListItemStyle( - background: Colors.transparent, - titleStyle: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414)), - )), - ); - } -``` - - - - - - - -```dart main.dart -CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - listItemView: (member) { - return getCustomListItemView(member, controller.group!, context); - }, + }, ) ``` - - - - - - -*** +### errorStateView -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +Custom view displayed when an error occurs. -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - subtitleView: (context, groupMember) { - return Placeholder(); // Replace this placeholder with your custom widget. + group: group, + errorStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error_outline, size: 64, color: Colors.red), + SizedBox(height: 16), + Text("Failed to load members"), + ElevatedButton( + onPressed: () { + // Retry logic + }, + child: Text("Retry"), + ), + ], + ), + ); }, ) ``` - - -Here is the complete example for reference: +--- + + +## Styling -**Example** +Set `CometChatGroupMembersStyle` to customize the appearance. -```dart main.dart +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - subtitleView: (context, member) { - String subtitle = ""; - - final dateTime = member.joinedAt ?? DateTime.now(); - subtitle = "Joined at ${DateFormat('dd/MM/yyyy').format(dateTime)}"; - - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - }, + group: group, + style: CometChatGroupMembersStyle( + titleStyle: TextStyle(color: Color(0xFFF76808)), + separatorColor: Color(0xFFF76808), + ownerMemberScopeBackgroundColor: Color(0xFFF76808), + adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), + adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), + adminMemberScopeTextColor: Color(0xFFF76808), + moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), + moderatorMemberScopeTextColor: Color(0xFFF76808), + backIconColor: Color(0xFFF76808), + ), ) ``` - - - + -*** +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the component | +| `border` | `BoxBorder?` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the widget | +| `titleStyle` | `TextStyle?` | Style for the header title | +| `backIconColor` | `Color?` | Back button icon color | +| `searchBackground` | `Color?` | Background color of search box | +| `searchBorderRadius` | `BorderRadius?` | Border radius for search box | +| `searchTextStyle` | `TextStyle?` | Style for search input text | +| `searchPlaceholderStyle` | `TextStyle?` | Style for search placeholder | +| `searchIconColor` | `Color?` | Search icon color | +| `loadingIconColor` | `Color?` | Loading indicator color | +| `emptyStateTextStyle` | `TextStyle?` | Style for empty state title | +| `emptyStateSubtitleTextStyle` | `TextStyle?` | Style for empty state subtitle | +| `errorStateTextStyle` | `TextStyle?` | Style for error state title | +| `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | +| `onlineStatusColor` | `Color?` | Online status indicator color | +| `separatorColor` | `Color?` | Color of list item separators | +| `separatorHeight` | `double?` | Height of list item separators | +| `listPadding` | `EdgeInsetsGeometry?` | Padding for the list | +| `ownerMemberScopeBackgroundColor` | `Color?` | Background color for owner scope badge | +| `ownerMemberScopeTextColor` | `Color?` | Text color for owner scope badge | +| `ownerMemberScopeBorder` | `BoxBorder?` | Border for owner scope badge | +| `ownerMemberScopeTextStyle` | `TextStyle?` | Text style for owner scope badge | +| `adminMemberScopeBackgroundColor` | `Color?` | Background color for admin scope badge | +| `adminMemberScopeTextColor` | `Color?` | Text color for admin scope badge | +| `adminMemberScopeBorder` | `BoxBorder?` | Border for admin scope badge | +| `adminMemberScopeTextStyle` | `TextStyle?` | Text style for admin scope badge | +| `moderatorMemberScopeBackgroundColor` | `Color?` | Background color for moderator scope badge | +| `moderatorMemberScopeTextColor` | `Color?` | Text color for moderator scope badge | +| `moderatorMemberScopeBorder` | `BoxBorder?` | Border for moderator scope badge | +| `moderatorMemberScopeTextStyle` | `TextStyle?` | Text style for moderator scope badge | +| `checkboxCheckedBackgroundColor` | `Color?` | Background color for checked checkbox | +| `checkboxBackgroundColor` | `Color?` | Background color for unchecked checkbox | +| `checkboxSelectedIconColor` | `Color?` | Color for checkbox icon when selected | +| `checkboxBorder` | `BorderSide?` | Border for checkbox | +| `checkboxBorderRadius` | `BorderRadiusGeometry?` | Border radius for checkbox | +| `listItemSelectedBackgroundColor` | `Color?` | Background color for selected list item | +| `submitIconColor` | `Color?` | Color for submit icon | +| `retryButtonBackgroundColor` | `Color?` | Background color for retry button | +| `retryButtonTextColor` | `Color?` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle?` | Text style for retry button | +| `retryButtonBorder` | `BorderSide?` | Border for retry button | +| `retryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius for retry button | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for member avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicators | +| `listItemStyle` | `ListItemStyle?` | Style for list items | +| `confirmDialogStyle` | `CometChatConfirmDialogStyle?` | Style for confirmation dialogs | +| `changeScopeStyle` | `CometChatChangeScopeStyle?` | Style for change scope dialog | +| `optionsBackgroundColor` | `Color?` | Background color for options menu | +| `optionsIconColor` | `Color?` | Color for options icon | +| `optionsTextStyle` | `TextStyle?` | Text style for options | + +--- + -#### AppBarOptions +## Common Patterns -You can set the Custom `appBarOptions` to the `CometChatGroupMembers` widget. +### Hide member management options -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - appBarOptions: [ - Placeholder(), - Placeholder(), - Placeholder() - ] // Replace this list of placeholder widgets with your list of custom widgets. + group: group, + hideKickMemberOption: true, + hideBanMemberOption: true, + hideScopeChangeOption: true, ) ``` - - -Here is the complete example for reference: - -**Example** +### Multi-select with selection callback ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - appBarOptions: [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.person_add_alt_1, - color: Color(0xFF6852D6), - ), - ), - ], // Replaced the list of placeholder widgets with a list of custom widgets. + group: group, + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedMembers) { + if (selectedMembers != null && selectedMembers.isNotEmpty) { + print("Selected ${selectedMembers.length} members"); + // Perform batch action on selected members + } + }, ) ``` - - - - - - -*** - -#### trailingView - -Used to generate a custom trailing widget for the `CometChatGroupMembers` widget. You can add a Tail widget using the following method. +### Hide all chrome — minimal list -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - trailingView: (context, groupMembers) { - return Placeholder(); // Replace this placeholder with your custom widget. - }, + group: group, + hideSearch: true, + hideAppbar: true, + hideSeparator: true, ) ``` - - -Here is the complete example for reference: - -**Example** +### Filter admins and moderators only -```dart main.dart - CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - trailingView: (context, groupMember) { - Color? backgroundColor = Color(0xFFEDEAFA); - BoxBorder? border = Border.all(color: Color(0xFF6852D6), width: 1); - String scope = groupMember.scope ?? GroupMemberScope.participant; - Color? textColor = Color(0xFF6852D6); - - if (groupMember.uid == group.owner){ - scope = GroupMemberScope.owner; - } - - return Container( - alignment: Alignment.center, - padding: EdgeInsets.symmetric( - horizontal: 12, vertical:4 ?? 0), - decoration: BoxDecoration( - color: backgroundColor, - border: border, - borderRadius: - BorderRadius.circular(1000), - ), - child: Text( - scope.capitalizeFirst ?? "", - style:TextStyle( - fontSize: 12, - fontWeight: FontWeight.w400, - color: textColor) - ), - ); - }, - ); +```dart +CometChatGroupMembers( + group: group, + groupMembersRequestBuilder: GroupMembersRequestBuilder(group.guid) + ..scopes = [GroupMemberScope.admin, GroupMemberScope.moderator], +) ``` - - - - - +--- + + +## Props Reference + +| Prop | Type | Default | Description | +| --- | --- | --- | --- | +| `group` | `Group` | **required** | The group object to fetch members from | +| `groupMembersProtocol` | `GroupMembersBuilderProtocol?` | `null` | Custom request builder protocol | +| `groupMembersRequestBuilder` | `GroupMembersRequestBuilder?` | `null` | Custom request builder for filtering members | +| `searchKeyword` | `String?` | `null` | Pre-fills search and filters list | +| `controllerTag` | `String?` | `null` | Tag for controller management | +| `onSelection` | `Function(List?)?` | `null` | Callback when members are selected | +| `onItemTap` | `Function(GroupMember)?` | `null` | Callback on tapping a member item | +| `onItemLongPress` | `Function(GroupMember)?` | `null` | Callback on long pressing a member item | +| `onBack` | `VoidCallback?` | `null` | Callback on closing this screen | +| `onError` | `OnError?` | `null` | Callback in case any error occurs | +| `onLoad` | `OnLoad?` | `null` | Callback when list is fetched and loaded | +| `onEmpty` | `OnEmpty?` | `null` | Callback when the list is empty | +| `stateCallBack` | `Function(CometChatGroupMembersController)?` | `null` | Access controller functions from parent | +| `showBackButton` | `bool` | `true` | Show/hide back button | +| `hideSearch` | `bool` | `false` | Show/hide search input | +| `hideSeparator` | `bool?` | `null` | Toggle visibility of separator | +| `hideError` | `bool?` | `null` | Toggle visibility of error dialog | +| `hideAppbar` | `bool?` | `null` | Hides the appbar | +| `usersStatusVisibility` | `bool?` | `true` | Hide status indicator on avatar | +| `hideKickMemberOption` | `bool?` | `null` | Hide kick member option | +| `hideBanMemberOption` | `bool?` | `null` | Hide ban member option | +| `hideScopeChangeOption` | `bool?` | `null` | Hide scope change option | +| `selectionMode` | `SelectionMode?` | `null` | Selection mode (single/multiple/none) | +| `activateSelection` | `ActivateSelection?` | `null` | When to activate selection | +| `subtitleView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom subtitle for each member | +| `listItemView` | `Widget Function(GroupMember)?` | `null` | Custom view for each member | +| `trailingView` | `Function(BuildContext, GroupMember)?` | `null` | Custom trailing widget | +| `leadingView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom leading view | +| `titleView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom title view | +| `loadingStateView` | `WidgetBuilder?` | `null` | View for loading state | +| `emptyStateView` | `WidgetBuilder?` | `null` | View for empty state | +| `errorStateView` | `WidgetBuilder?` | `null` | View for error state | +| `backButton` | `Widget?` | `null` | Custom back button widget | +| `searchBoxIcon` | `Widget?` | `null` | Custom search icon | +| `selectIcon` | `Widget?` | `null` | Custom selection icon | +| `submitIcon` | `Widget?` | `null` | Custom selection complete icon | +| `appBarOptions` | `List?` | `null` | App bar options | +| `options` | `List? Function(...)?` | `null` | Options visible at slide of each member | +| `setOptions` | `List? Function(...)?` | `null` | Replace default long press actions | +| `addOptions` | `List? Function(...)?` | `null` | Add to default long press actions | +| `searchPlaceholder` | `String?` | `null` | Placeholder text of search input | +| `height` | `double?` | `null` | Height of the widget | +| `width` | `double?` | `null` | Width of the widget | +| `style` | `CometChatGroupMembersStyle?` | `null` | Style for the component | +| `controller` | `ScrollController?` | `null` | Scroll controller for the list | + +--- + -*** + + + Display and manage available groups + + + Add new members to a group + + + View and manage banned members + + + Learn how to customize the look and feel + + \ No newline at end of file diff --git a/ui-kit/flutter/groups.mdx b/ui-kit/flutter/groups.mdx index a613f6f0f..6c79bfe4c 100644 --- a/ui-kit/flutter/groups.mdx +++ b/ui-kit/flutter/groups.mdx @@ -1,169 +1,347 @@ --- title: "Groups" +description: "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator." --- -## Overview - -`CometChatGroups` functions as a standalone [Widget](/ui-kit/flutter/components-overview#components) designed to create a screen displaying a list of groups, with the added functionality of enabling users to search for specific groups. Acting as a container widget, `CometChatGroups` encapsulates and formats the `CometChatListBase` and `CometChatGroupList` widgets without introducing any additional behavior of its own. - - - - + +```json +{ + "component": "CometChatGroups", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(BuildContext context, Group group)?" + }, + "props": { + "data": { + "groupsRequestBuilder": { + "type": "GroupsRequestBuilder?", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "groupsProtocol": { + "type": "GroupsBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching groups" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Groups", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "searchPlaceholder": { + "type": "String?", + "default": "null", + "note": "Placeholder text for search input" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "height": { + "type": "double?", + "default": "null" + }, + "width": { + "type": "double?", + "default": "null" + } + }, + "callbacks": { + "onItemTap": "Function(BuildContext context, Group group)?", + "onItemLongPress": "Function(BuildContext context, Group group)?", + "onSelection": "Function(List?)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "stateCallBack": "Function(CometChatGroupsController controller)?" + }, + "visibility": { + "groupTypeVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideError": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": true } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(Group group)?", + "leadingView": "Widget? Function(BuildContext context, Group group)?", + "titleView": "Widget? Function(BuildContext context, Group group)?", + "subtitleView": "Widget? Function(BuildContext context, Group group)?", + "trailingView": "Widget? Function(BuildContext context, Group group)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Group, CometChatGroupsController, BuildContext)?", + "addOptions": "List? Function(Group, CometChatGroupsController, BuildContext)?", + "appBarOptions": "List Function(BuildContext context)?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "passwordGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "privateGroupIcon": { "type": "Widget?", "default": "built-in shield icon" } + }, + "style": { + "groupsStyle": { "type": "CometChatGroupsStyle?", "default": "null" } + } + }, + "events": [ + { "name": "CometChatGroupEvents.ccGroupCreated", "payload": "Group", "description": "Group created" }, + { "name": "CometChatGroupEvents.ccGroupDeleted", "payload": "Group", "description": "Group deleted" }, + { "name": "CometChatGroupEvents.ccGroupLeft", "payload": "Action, User, Group", "description": "User left group" }, + { "name": "CometChatGroupEvents.ccGroupMemberJoined", "payload": "User, Group", "description": "User joined group" }, + { "name": "CometChatGroupEvents.ccGroupMemberAdded", "payload": "List, List, Group, User", "description": "Members added" }, + { "name": "CometChatGroupEvents.ccGroupMemberKicked", "payload": "Action, User, User, Group", "description": "Member kicked" }, + { "name": "CometChatGroupEvents.ccGroupMemberBanned", "payload": "Action, User, User, Group", "description": "Member banned" }, + { "name": "CometChatGroupEvents.ccGroupMemberUnbanned", "payload": "Action, User, User, Group", "description": "Member unbanned" }, + { "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", "payload": "Action, User, String, String, Group", "description": "Member scope changed" }, + { "name": "CometChatGroupEvents.ccOwnershipChanged", "payload": "Group, GroupMember", "description": "Ownership transferred" } + ], + "sdkListeners": [ + "onGroupMemberJoined", + "onGroupMemberLeft", + "onMemberAddedToGroup", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberScopeChanged", + "onConnected" + ], + "compositionExample": { + "description": "Group directory wired to message view", + "components": [ + "CometChatGroups", + "CometChatMessages", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits Group -> pass to CometChatMessages or individual message components" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" + } + } +} +``` + -The `CometChatGroups` widget is composed of the following BaseWidget: -| Widgets | Description | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [CometChatListBase](/ui-kit/flutter/list-base) | `CometChatListBase` serves as a container widget equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list view. | -| [CometChatListItem](/ui-kit/flutter/list-item) | This widget renders information extracted from a `Group` object onto a tile, featuring a title, subtitle, leading view, and trailing view. | +## Where It Fits -## Usage +`CometChatGroups` is a directory list widget. It renders available groups and emits the selected `Group` via `onItemTap`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a group chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatGroups` is a custom **widget**, it can be launched directly by user actions such as button clicks or other interactions. +class GroupChatApp extends StatefulWidget { + const GroupChatApp({super.key}); -You can launch `CometChatGroups` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _GroupChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatGroups` +class _GroupChatAppState extends State { + Group? selectedGroup; - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatGroups())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatGroups( + onItemTap: (context, group) { + setState(() { + selectedGroup = group; + }); + }, + ), + ), + Expanded( + child: selectedGroup != null + ? CometChatMessages(group: selectedGroup) + : const Center(child: Text('Select a group')), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatGroups` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Groups extends StatefulWidget { - const Groups({super.key}); - - @override - State createState() => _GroupsState(); -} - -class _GroupsState extends State { +class GroupsDemo extends StatelessWidget { + const GroupsDemo({super.key}); @override Widget build(BuildContext context) { return const Scaffold( - body: SafeArea( - child: CometChatGroups() - ) + body: SafeArea( + child: CometChatGroups(), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatGroups()) +); +``` -##### 1. onItemTap +--- -This method proves valuable when users seek to override onItemTap functionality within CometChatGroups, empowering them with greater control and customization options. +## Filtering Groups -The `onItemTap` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `GroupsRequestBuilder` to `groupsRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatGroups( - onItemTap: (context, group) { - // TODO("Not yet implemented") - }, + groupsRequestBuilder: GroupsRequestBuilder() + ..joinedOnly = true + ..limit = 10, ) ``` - - -*** +### Filter Recipes -##### 2. onBack +| Recipe | Code | +| --- | --- | +| Joined groups only | `GroupsRequestBuilder()..joinedOnly = true` | +| Limit to 10 per page | `GroupsRequestBuilder()..limit = 10` | +| Search by keyword | `GroupsRequestBuilder()..searchKeyword = "design"` | +| Filter by tags | `GroupsRequestBuilder()..tags = ["vip"]` | +| With tags data | `GroupsRequestBuilder()..withTags = true` | -Enhance your application's functionality by leveraging the `onBack` feature. This capability allows you to customize the behavior associated with navigating back within your app. Utilize the provided code snippet to override default behaviors and tailor the user experience according to your specific requirements. +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. - - -```dart -CometChatGroups( - onBack: () { - // TODO("Not yet implemented") - }, -) -``` - +### GroupsRequestBuilder Properties - +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of groups to fetch per request. | `..limit = 30` | +| `searchKeyword` | Search groups by name. | `..searchKeyword = "Team"` | +| `joinedOnly` | Fetch only joined groups. Default `false`. | `..joinedOnly = true` | +| `tags` | Filter groups by specific tags. | `..tags = ["vip"]` | +| `withTags` | Include tags in the Group object. Default `false`. | `..withTags = true` | +| `build()` | Builds and returns a `GroupsRequest` object. | `.build()` | -*** +Refer to [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) for the full builder API. -##### 3. onError +--- + +## Actions and Events + +### Callback Props + +#### onItemTap -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Fires when a group row is tapped. Primary navigation hook — set the active group and render the message view. ```dart CometChatGroups( - onError: (e) { - // TODO("Not yet implemented") + onItemTap: (context, group) { + print("Selected: ${group.name}"); }, ) ``` - - -*** - -##### 4. onItemLongPress +#### onItemLongPress -This method becomes invaluable when users seek to override long-click functionality within CometChatGroups, offering them enhanced control and flexibility in their interactions. - -The `onItemLongPress` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Fires when a group row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatGroups( onItemLongPress: (context, group) { - // TODO("Not yet implemented") + // Show custom context menu }, ) ``` - - -*** - -##### 5. onSelection +#### onSelection -When the `onSelection` event is triggered, it furnishes the list of selected groups. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected groups. - -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Fires when groups are selected in multi-select mode. Requires `selectionMode` to be set. @@ -171,648 +349,1149 @@ This action does not come with any predefined behavior. However, you have the fl CometChatGroups( selectionMode: SelectionMode.multiple, activateSelection: ActivateSelection.onClick, - onSelection: (groupList) { - // TODO("Not yet implemented") - } + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} groups"); + }, ) ``` - - -*** -##### onLoad +#### onError -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatGroups( - onLoad: (list) { - // print("Groups loaded: ${list.length}"); - }, + onError: (error) { + print("CometChatGroups error: $error"); + }, ) ``` - - -*** - -##### onEmpty +#### onBack -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the back button is pressed. ```dart CometChatGroups( - onEmpty: () { - // print("Groups empty"); - }, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** +#### onLoad -### Filters +Fires when the group list is successfully loaded. -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. + + +```dart +CometChatGroups( + onLoad: (list) { + print("Loaded ${list.length} groups"); + }, +) +``` + + -##### 1. GroupsRequestBuilder +#### onEmpty -The [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) enables you to filter and customize the group list based on available parameters in GroupsRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) +Fires when the group list is empty. ```dart CometChatGroups( - groupsRequestBuilder: GroupsRequestBuilder() - ..limit = 10 + onEmpty: () { + print("No groups found"); + }, ) ``` - - -| Property | Description | Code | -| ------------------ | --------------------------------------------------------- | ----------------------- | -| **Joined Only** | Flag to include only joined groups. Defaults to `false`. | `joinedOnly: bool` | -| **Limit** | Number of results to limit the query. | `limit: int` | -| **Search Keyword** | Keyword for searching groups. | `searchKeyword: String` | -| **Tags** | Tags for filtering groups. | `tags: List` | -| **With Tags** | Flag to include tags in the results. Defaults to `false`. | `withTags: bool` | - -*** +### Global UI Events -### Events +`CometChatGroupEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `CometChatGroups` Widget. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupCreated` | A new group is created | `Group` | +| `ccGroupDeleted` | A group is deleted | `Group` | +| `ccGroupLeft` | A user leaves a group | `Action, User, Group` | +| `ccGroupMemberJoined` | A user joins a group | `User, Group` | +| `ccGroupMemberAdded` | Members are added to a group | `List, List, Group, User` | +| `ccGroupMemberKicked` | A member is kicked | `Action, User, User, Group` | +| `ccGroupMemberBanned` | A member is banned | `Action, User, User, Group` | +| `ccGroupMemberUnbanned` | A member is unbanned | `Action, User, User, Group` | +| `ccGroupMemberScopeChanged` | A member's scope changes | `Action, User, String, String, Group` | +| `ccOwnershipChanged` | Group ownership is transferred | `Group, GroupMember` | -The list of events emitted by the `CometChatGroups` widget is as follows. +When to use: sync external UI with group state changes. For example, update a group count badge when a group is created or deleted. -| Events | Description | -| --------------------------- | -------------------------------------------------------------------------------------------------------- | -| `ccGroupCreated` | This gets triggered when the logged in user creates a group. | -| `ccGroupDeleted` | This gets triggered when the logged in user deletes a group. | -| `ccGroupLeft` | This gets triggered when the logged in user leaves a group. | -| `ccGroupMemberScopeChanged` | This gets triggered when the logged in user changes the scope of another group member. | -| `ccGroupMemberBanned` | This gets triggered when the logged in user bans a group member from the group. | -| `ccGroupMemberKicked` | This gets triggered when the logged in user kicks another group member from the group. | -| `ccGroupMemberUnbanned` | This gets triggered when the logged in user unbans a user banned from the group. | -| `ccGroupMemberJoined` | This gets triggered when the logged in user joins a group. | -| `ccGroupMemberAdded` | This gets triggered when the logged in user adds new members to the group. | -| `ccOwnershipChanged` | This gets triggered when the logged in user transfers the ownership of their group to some other member. | -```dart your_screen.dart +```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_sdk/models/action.dart' as cc; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatGroupEventListener { @override void initState() { super.initState(); - CometChatGroupEvents.addGroupsListener("listenerId", this); // Add the listener + CometChatGroupEvents.addGroupsListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatGroupEvents.removeGroupsListener("listenerId"); super.dispose(); - CometChatGroupEvents.removeGroupsListener("listenerId"); // Remove the listener } - @override void ccGroupCreated(Group group) { - // TODO("Not yet implemented") + print("Group created: ${group.name}"); } @override void ccGroupDeleted(Group group) { - // TODO("Not yet implemented") + print("Group deleted: ${group.name}"); } @override void ccGroupLeft(cc.Action message, User leftUser, Group leftGroup) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberScopeChanged(cc.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberBanned(cc.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberKicked(cc.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberUnbanned(cc.Action message, User unbannedUser, User unbannedBy, Group unbannedFrom) { - // TODO("Not yet implemented") + print("User ${leftUser.name} left ${leftGroup.name}"); } @override void ccGroupMemberJoined(User joinedUser, Group joinedGroup) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberAdded(List messages, List usersAdded, Group groupAddedIn, User addedBy) { - // TODO("Not yet implemented") + print("User ${joinedUser.name} joined ${joinedGroup.name}"); } @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - // TODO("Not yet implemented") + print("Ownership of ${group.name} transferred to ${newOwner.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To fit your app's design requirements, you can customize the appearance of the groups widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Updates member count, sets `hasJoined` if current user joined | +| `onGroupMemberLeft` | Updates member count | +| `onMemberAddedToGroup` | Updates member count, adds group to list if current user was added | +| `onGroupMemberKicked` | Updates member count | +| `onGroupMemberBanned` | Updates member count | +| `onGroupMemberScopeChanged` | Updates member scope | -Enhance your `CometChatGroups` Widget by setting the `CometChatGroupsStyle` to customize its appearance. +Automatic: group membership changes, member count updates. - - -```dart -CometChatGroups( - groupsStyle: CometChatGroupsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a group parameter receive the `Group` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(Group)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, Group)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, Group)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, Group)` | Member count subtitle | +| `trailingView` | `Widget? Function(BuildContext, Group)` | Right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Group, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Group, Controller, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List Function(BuildContext)` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart CometChatGroups( - title: "Your Title", - backButton: Icon(Icons.add_alert, color: Color(0xFF6851D6)), - searchPlaceholder: "Search Group", + listItemView: (group) { + return ListTile( + title: Text( + group.name, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), + ), + subtitle: Text( + "${group.membersCount} Members • ${group.description}", + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: Color(0xFF727272)), + ), + trailing: ElevatedButton( + onPressed: () { + CometChat.joinGroup( + group.guid, + group.type, + onSuccess: (group) { + // Handle success + }, + onError: (error) { + // Handle error + }, + ); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Color(0xFFEDEAFA), + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(1000)), + ), + child: Text("JOIN", style: TextStyle(color: Color(0xFF6852D6), fontSize: 12)), + ), + ); + }, ) ``` - - -## List of properties exposed by `CometChatGroups` - -| Property | Data Type | Description | -| ---------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------- | -| `groupsProtocol` | `GroupsBuilderProtocol?` | Custom groups request builder protocol. | -| `groupsRequestBuilder` | `GroupsRequestBuilder?` | Custom request builder for fetching groups. | -| `subtitleView` | `Widget? Function(BuildContext, Group)?` | Widget to set subtitle for each group item. | -| `listItemView` | `Widget Function(Group)?` | Custom view for each group item. | -| `groupsStyle` | `CometChatGroupsStyle?` | Styling options for the groups list. | -| `scrollController` | `ScrollController?` | Controller for scrolling the list. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input box. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Mode defining how groups can be selected. | -| `onSelection` | `Function(List?)?` | Callback for handling group selection. | -| `title` | `String?` | Title of the widget. | -| `stateCallBack` | `Function(CometChatGroupsController)?` | Callback to access controller functions. | -| `hideError` | `bool?` | Toggle visibility of error dialog. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `appBarOptions` | `List Function(BuildContext)?` | Options available in the app bar. | -| `passwordGroupIcon` | `Widget?` | Widget for password-protected group icon. | -| `privateGroupIcon` | `Widget?` | Widget for private group icon. | -| `activateSelection` | `ActivateSelection?` | Controls whether selection is allowed. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(BuildContext, Group)?` | Callback triggered when tapping a group. | -| `onItemLongPress` | `Function(BuildContext, Group)?` | Callback triggered on long press of a group. | -| `onError` | `OnError?` | Callback for handling errors. | -| `submitIcon` | `Widget?` | Widget for displaying the submit icon. | -| `hideAppbar` | `bool` | Flag to show/hide the app bar. | -| `controllerTag` | `String?` | Identifier tag for controller management. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `searchKeyword` | `String?` | Keyword used to fetch initial group list. | -| `onLoad` | `OnLoad?` | Callback triggered when the list loads. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `groupTypeVisibility` | `bool` | Hide the group type icon visible on the group icon. | -| `setOptions` | `List? Function(Group, CometChatGroupsController, BuildContext)?` | Actions available on long-press of a group. | -| `addOptions` | `List? Function(Group, CometChatGroupsController, BuildContext)?` | Additional long-press actions for groups. | -| `titleView` | `Widget? Function(BuildContext, Group)?` | Custom title view for each group. | -| `leadingView` | `Widget? Function(BuildContext, Group)?` | Widget for the leading section of each group. | -| `trailingView` | `Widget? Function(BuildContext, Group)?` | Widget for the trailing section of each group. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -*** - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: - -* Enable actions like "Mute Notifications", "Leave Group", "Pin Group". -* Provide admin-only actions like "Manage Members", "Delete Group". - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. Joined status badge example. ```dart CometChatGroups( - setOptions: (group, controller, context) { - // return options + leadingView: (context, group) { + return Stack( + children: [ + CometChatAvatar( + image: group.icon, + name: group.name, + style: CometChatAvatarStyle(borderRadius: BorderRadius.circular(8)), + ), + if (group.hasJoined) + Positioned( + bottom: -2, + left: 0, + right: 0, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2), + decoration: BoxDecoration(color: Color(0xFF09C26F)), + child: Text( + "Joined", + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ), + ], + ); }, ) ``` - - -*** - -#### addOptions - -This method extends the existing set of actions available when users long press a group item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: - -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" +### titleView -This method provides flexibility in modifying user interaction capabilities. +Replace the name / title text. Group type badge inline example. ```dart CometChatGroups( - addOptions: (group, controller, context) { - // return options + titleView: (context, group) { + return Row( + children: [ + Text( + group.name, + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + SizedBox(width: 4), + Container( + padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2), + decoration: BoxDecoration( + color: group.type == GroupTypeConstants.public + ? Color(0xFF0B7BEA) + : Color(0xFF09C26F), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + group.type, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ], + ); }, ) ``` - - -*** - -#### loadingStateView +### subtitleView -Configures a custom loading view displayed while groups are being fetched. +Replace the member count subtitle text. -* Show a spinner with "Loading groups..." text. -* Display a skeleton loader for a smooth UI experience. + + + ```dart CometChatGroups( - loadingStateView: (context) { - // return loading view + subtitleView: (context, group) { + return Text( + "${group.membersCount} Members • ${group.description ?? 'No description'}", + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: Color(0xFF727272)), + ); }, ) ``` - - -*** - -#### emptyStateView -Defines a view that appears when no groups are available. +### trailingView -* Show a message like "No groups found, create one now!". -* Display an illustration with a "Create New Group" button. +Replace the right section. Join status button example. ```dart CometChatGroups( - emptyStateView: (context) { - // return empty view + trailingView: (context, group) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: Color(0xFFEDEAFA), + borderRadius: BorderRadius.circular(1000), + ), + child: Text( + group.hasJoined ? "JOINED" : "+ JOIN", + style: TextStyle(color: Color(0xFF6852D6), fontSize: 12, fontWeight: FontWeight.w700), + ), + ); }, ) ``` - - -*** - -#### errorStateView +### setOptions -Configures the UI when an error occurs while fetching groups. - -* Display a retry button with "Failed to load groups, try again.". -* Show a friendly error illustration. +Replace the context menu / long-press actions on each group item. ```dart CometChatGroups( - errorStateView: (context) { - // return error view + setOptions: (group, controller, context) { + return [ + CometChatOption( + id: "leave", + title: "Leave Group", + icon: AssetConstants.close, + onClick: () { + CometChat.leaveGroup(group.guid, onSuccess: (response) { + print("Left group"); + }, onError: (error) { + print("Error: $error"); + }); + }, + ), + CometChatOption( + id: "view_members", + title: "View Members", + iconWidget: Icon(Icons.people_outline), + onClick: () { + // Navigate to group members + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView - -Sets a custom leading view that appears at the start of each group item. +### addOptions -* Display the group profile picture. -* Add an icon indicating Public or Private groups. +Add to the existing context menu actions without removing defaults. ```dart CometChatGroups( - leadingView: (context, group) { - // return leading view - }, + addOptions: (group, controller, context) { + return [ + CometChatOption( + id: "mute", + title: "Mute Notifications", + iconWidget: Icon(Icons.notifications_off_outlined), + onClick: () { + // Mute notifications logic + }, + ), + CometChatOption( + id: "pin", + title: "Pin Group", + iconWidget: Icon(Icons.push_pin_outlined), + onClick: () { + // Pin group logic + }, + ), + ]; + }, ) ``` - - -*** -#### titleView +### appBarOptions -Customizes the title view of each group item, which typically displays the group name. +Add custom widgets to the app bar. -* Style group names with custom fonts and colors. -* Show a verified badge for official groups. + + + ```dart CometChatGroups( - titleView: (context, group) { - // return title view - }, + appBarOptions: (context) => [ + IconButton( + onPressed: () { + // Navigate to create group + }, + icon: Icon(Icons.group_add, color: Color(0xFF6852D6)), + ), + ], ) ``` - - -*** - -#### trailingView +--- -Allows custom elements to be added at the end of each group item, such as buttons or indicators. +## Styling -* Show unread message counts. -* Add a quick Join or Leave button. +Set `CometChatGroupsStyle` to customize the appearance. ```dart CometChatGroups( - trailingView: (context, group) { - // return trailing view - }, + groupsStyle: CometChatGroupsStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + ), ) ``` - - -*** + + + + +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color` | Background color of the component | +| `border` | `Border` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry` | Border radius for the widget | +| `titleTextColor` | `Color` | Color of the header title | +| `titleTextStyle` | `TextStyle` | Style for the header title | +| `backIconColor` | `Color` | Back button icon color | +| `searchBackgroundColor` | `Color` | Background color of search box | +| `searchBorder` | `BorderSide` | Border for search box | +| `searchBorderRadius` | `BorderRadius` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle` | Placeholder text style in search | +| `searchIconColor` | `Color` | Search icon color | +| `searchInputTextColor` | `Color` | Search input text color | +| `searchInputTextStyle` | `TextStyle` | Search input text style | +| `separatorColor` | `Color` | Color of list item separators | +| `separatorHeight` | `double` | Height of list item separators | +| `itemTitleTextColor` | `Color` | Color of group name in list items | +| `itemTitleTextStyle` | `TextStyle` | Style for group name in list items | +| `itemSubtitleTextColor` | `Color` | Color of member count subtitle | +| `itemSubtitleTextStyle` | `TextStyle` | Style for member count subtitle | +| `listItemSelectedBackgroundColor` | `Color` | Background color for selected items | +| `privateGroupIconBackground` | `Color` | Background color for private group icon | +| `protectedGroupIconBackground` | `Color` | Background color for password group icon | +| `emptyStateTextColor` | `Color` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle` | Text style for error state subtitle | +| `retryButtonBackgroundColor` | `Color` | Background color for retry button | +| `retryButtonBorderRadius` | `BorderRadius` | Border radius for retry button | +| `retryButtonBorder` | `BorderSide` | Border for retry button | +| `retryButtonTextColor` | `Color` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle` | Text style for retry button | +| `submitIconColor` | `Color` | Color of submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color` | Background color of unchecked checkbox | +| `checkBoxCheckedBackgroundColor` | `Color` | Background color of checked checkbox | +| `checkboxSelectedIconColor` | `Color` | Color of checkmark icon | +| `checkBoxBorderRadius` | `BorderRadius` | Border radius for checkbox | +| `checkBoxBorder` | `BorderSide` | Border for checkbox | +| `avatarStyle` | `CometChatAvatarStyle` | Style for group avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle` | Style for group type indicators | + +--- + -#### ListItemView +## Common Patterns -With this function, you can assign a custom ListItem to the `CometChatGroups` Widget. +### Custom empty state with CTA ```dart CometChatGroups( - listItemView: (group) { - return Placeholder(); // Replace this placeholder with your custom widget. + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.group_outlined, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No groups found", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)), + SizedBox(height: 8), + ElevatedButton( + onPressed: () { + // Navigate to create group + }, + child: Text("Create a Group"), + ), + ], + ), + ); }, ) ``` - - -**Example** - -Here is the complete example for reference: +### Joined groups only ```dart - CometChatGroups( - listItemView: (group) { - return ListTile( - title: Text( - group.name, - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - ), - ), - subtitle: Text( - "${group.membersCount} Members • ${group.description}", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - color: Color(0XFF727272), - ), - ), - trailing: ElevatedButton( - onPressed: () { - CometChat.joinGroup( - group.guid, - group.type, - onSuccess: (group) { - //handle success, for example, show a toast or navigate to a new screen - }, - onError: (excep) { - //handle exception, for example, show an error toast or dialog - }, - ); - }, - child: Text( - "JOIN", - style: TextStyle( - color: Color(0xFF6852D6), - fontSize: 12, - fontWeight: FontWeight.w500, - letterSpacing: 0), - ), - style: ElevatedButton.styleFrom( - backgroundColor: Color(0xFFEDEAFA), - elevation: 0, - padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), - visualDensity: VisualDensity.compact, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(1000), - ), - )), - ); - }, - ); +CometChatGroups( + groupsRequestBuilder: GroupsRequestBuilder() + ..joinedOnly = true, +) ``` - - - - - - -*** - -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +### Multi-select with selection callback ```dart CometChatGroups( - subtitleView: (context, group) { - return Text( - "${group.membersCount} Members • ${group.description}", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - color: Color(0XFF727272), - ), - ); + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedGroups) { + if (selectedGroups != null && selectedGroups.isNotEmpty) { + print("Selected ${selectedGroups.length} groups"); + // Perform batch action on selected groups + } }, ) ``` - - - - - - -*** - -#### AppBarOptions - -You can set the Custom `appBarOptions` to the `CometChatGroups` widget. +### Hide all chrome — minimal list ```dart CometChatGroups( - appBarOptions: (context) { - return [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.group_add, - color: Color(0xFF6852D6), - ), - ), - ]; - }, + hideSearch: true, + hideAppbar: true, + groupTypeVisibility: false, ) ``` - - - - - +--- + +## Accessibility + +The component renders a scrollable list of interactive items. Each group row supports: + +- Tap gesture for selection/navigation +- Long-press gesture for context menu actions +- Checkbox selection in multi-select mode with proper touch targets +- Group type indicators (public/private/password) with visual icons + +For screen readers: +- Group names are readable as list item titles +- Group type indicators use icons — consider adding `Semantics` widgets via `leadingView` if screen reader descriptions are needed +- Selection state is communicated through checkbox widgets + +The component respects system accessibility settings including text scaling and high contrast modes. + +--- + + +## Props + +All props are optional unless noted. + +### activateSelection + +Controls when selection mode activates. + +| | | +| --- | --- | +| Type | `ActivateSelection` | +| Default | `null` | + +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` + +--- + +### addOptions + +Adds additional context menu actions to the default options. + +| | | +| --- | --- | +| Type | `List? Function(Group, CometChatGroupsController, BuildContext)` | +| Default | `null` | + +--- + +### appBarOptions + +Custom widgets to display in the app bar. + +| | | +| --- | --- | +| Type | `List Function(BuildContext context)` | +| Default | `null` | + +--- + +### backButton + +Custom back button widget. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in back arrow | + +--- + +### controllerTag + +Identifier tag for controller management. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### emptyStateView + +Custom view displayed when there are no groups. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in empty state | + +--- + +### errorStateView + +Custom view displayed when an error occurs. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in error state | + +--- + +### groupsProtocol + +Custom protocol for fetching groups. + +| | | +| --- | --- | +| Type | `GroupsBuilderProtocol` | +| Default | `null` | + +--- + + +### groupsRequestBuilder + +Controls which groups load and in what order. + +| | | +| --- | --- | +| Type | `GroupsRequestBuilder` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### groupsStyle + +Styling options for the groups list. + +| | | +| --- | --- | +| Type | `CometChatGroupsStyle` | +| Default | `null` | + +--- + +### groupTypeVisibility + +Shows or hides the group type icon (public/private/password) on group avatars. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### height + +Height of the widget. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### hideAppbar + +Hides the app bar including title and search. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideError + +Hides the error state view. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search input box. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in avatar | + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(Group group)` | +| Default | Built-in list item | + +--- + + +### loadingStateView + +Custom view displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in shimmer | + +--- + +### onBack + +Callback triggered when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback` | +| Default | `null` | + +--- + +### onEmpty + +Callback triggered when the group list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty` | +| Default | `null` | + +--- + +### onError + +Callback triggered when an error occurs. + +| | | +| --- | --- | +| Type | `OnError` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback triggered on long press of a group item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### onItemTap + +Callback triggered when tapping a group item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### onLoad + +Callback triggered when the list is successfully loaded. + +| | | +| --- | --- | +| Type | `OnLoad` | +| Default | `null` | + +--- + +### onSelection + +Callback triggered when groups are selected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `Function(List? list)` | +| Default | `null` | + +--- + +### passwordGroupIcon + +Custom icon widget for password-protected groups. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### privateGroupIcon + +Custom icon widget for private groups. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in shield icon | + +--- + + +### scrollController + +Controller for scrolling the list. + +| | | +| --- | --- | +| Type | `ScrollController` | +| Default | `null` | + +--- + +### searchBoxIcon + +Custom search box icon widget. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in search icon | + +--- + +### searchKeyword + +Pre-fills the search and filters the group list. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### searchPlaceholder + +Placeholder text for the search input box. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +--- + +### setOptions + +Replaces the default context menu actions. + +| | | +| --- | --- | +| Type | `List? Function(Group, CometChatGroupsController, BuildContext)` | +| Default | `null` | + +--- + +### showBackButton + +Shows or hides the back button. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### stateCallBack + +Callback to access controller functions from parent. + +| | | +| --- | --- | +| Type | `Function(CometChatGroupsController controller)` | +| Default | `null` | + +--- + +### submitIcon + +Custom submit icon widget for selection mode. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in check icon | + +--- + +### subtitleView + +Custom renderer for the member count subtitle. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in member count | + +--- + +### title + +Title text displayed in the app bar. + +| | | +| --- | --- | +| Type | `String` | +| Default | `"Groups"` | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### width + +Width of the widget. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + + +## Events + +`CometChatGroups` subscribes to `CometChatGroupEvents`: + +| Event | Payload | Internal behavior | +| --- | --- | --- | +| `ccGroupCreated` | `Group` | Adds new group to list | +| `ccGroupDeleted` | `Group` | Removes group from list | +| `ccGroupLeft` | `Action, User, Group` | Removes private group or updates hasJoined | +| `ccGroupMemberJoined` | `User, Group` | Updates group in list | +| `ccGroupMemberAdded` | `List, List, Group, User` | Updates group in list | +| `ccGroupMemberKicked` | `Action, User, User, Group` | Updates group in list | +| `ccGroupMemberBanned` | `Action, User, User, Group` | Updates group in list | +| `ccOwnershipChanged` | `Group, GroupMember` | Updates group in list | + +--- + +## Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on group interaction | Component props | `on` callbacks | `onItemTap: (ctx, group) => setActive(group)` | +| Filter which groups appear | Component props | `groupsRequestBuilder` | `groupsRequestBuilder: GroupsRequestBuilder()..joinedOnly = true` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideSearch: true` | +| Replace a section of the list item | Component props | `View` render props | `listItemView: (group) => CustomWidget()` | +| Change colors, fonts, spacing | Component props | `groupsStyle` | `groupsStyle: CometChatGroupsStyle(titleTextColor: Colors.red)` | + + +--- -*** + + + Display and manage user contacts + + + Display recent one-on-one and group conversations + + + Display and manage members of a group + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/message-composer.mdx b/ui-kit/flutter/message-composer.mdx index 201a42ddb..206701160 100644 --- a/ui-kit/flutter/message-composer.mdx +++ b/ui-kit/flutter/message-composer.mdx @@ -1,8 +1,95 @@ --- title: "Message Composer" +description: "A widget that enables users to write and send messages with attachments and reactions" --- -## Overview + +```json +{ + "component": "CometChatMessageComposer", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that enables users to write and send a variety of messages, including text, image, video, and custom messages. Features such as Live Reaction, Attachments, and Message Editing are also supported.", + "primaryOutput": { + "prop": "onSendButtonTap", + "type": "Function(BuildContext, BaseMessage, PreviewMessageMode?)?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for the message composer (one of user or group is required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for the message composer (one of user or group is required)" + }, + "text": { + "type": "String?", + "default": "null", + "note": "Initial text for the input field" + }, + "parentMessageId": { + "type": "int", + "default": "0", + "note": "ID of the parent message for threaded replies" + } + }, + "callbacks": { + "onChange": "Function(String)?", + "onSendButtonTap": "Function(BuildContext, BaseMessage, PreviewMessageMode?)?", + "onError": "OnError?" + }, + "visibility": { + "hideVoiceRecordingButton": { "type": "bool?", "default": null }, + "hideSendButton": { "type": "bool?", "default": null }, + "hideAttachmentButton": { "type": "bool?", "default": null }, + "hideStickersButton": { "type": "bool?", "default": null }, + "disableMentions": { "type": "bool?", "default": null }, + "disableTypingEvents": { "type": "bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool", "default": false }, + "customSoundForMessage": { "type": "String?", "default": null } + }, + "viewSlots": { + "auxiliaryButtonView": "ComposerWidgetBuilder?", + "secondaryButtonView": "ComposerWidgetBuilder?", + "sendButtonView": "Widget?", + "headerView": "ComposerWidgetBuilder?", + "footerView": "ComposerWidgetBuilder?" + }, + "formatting": { + "placeholderText": { "type": "String?", "default": null }, + "maxLine": { "type": "int?", "default": null }, + "padding": { "type": "EdgeInsetsGeometry?", "default": null } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatMessageComposer is typically used at the bottom of a messaging screen, paired with CometChatMessageHeader and CometChatMessageList", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessages"], + "flow": "User types message → Composer sends message → MessageList updates" + }, + "types": { + "CometChatMessageComposerStyle": { + "backgroundColor": "Color?", + "border": "BoxBorder?", + "borderRadius": "BorderRadiusGeometry?", + "sendButtonIconColor": "Color?", + "sendButtonIconBackgroundColor": "Color?", + "textStyle": "TextStyle?", + "placeHolderTextStyle": "TextStyle?" + } + } +} +``` + + +## Where It Fits `CometChatMessageComposer` is a [Widget](/ui-kit/flutter/components-overview#components) that enables users to write and send a variety of messages, including text, image, video, and custom messages. @@ -14,368 +101,258 @@ Features such as **Live Reaction**, **Attachments**, and **Message Editing** are `CometChatMessageComposer` is comprised of the following [Base Widgets](/ui-kit/flutter/components-overview#base-components): -| Base Widgets | Description | -| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| [MessageInput](/ui-kit/flutter/message-input) | This provides a basic layout for the contents of this component, such as the TextField and buttons | -| [ActionSheet](/ui-kit/flutter/action-sheet) | The ActionSheet widget presents a list of options in either a list or grid mode, depending on the user's preference | - -## Usage - -### Integration - -You can launch `CometChatMessageComposer` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatMessageComposer` - - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatMessageComposer())); // A user or group object is required to launch this widget. -``` - - - - - -##### 2. Embedding `CometChatMessageComposer` as a Widget in the build Method +| Base Widgets | Description | +| ------------ | ----------- | +| [MessageInput](/ui-kit/flutter/message-input) | This provides a basic layout for the contents of this component, such as the TextField and buttons | +| [ActionSheet](/ui-kit/flutter/action-sheet) | The ActionSheet widget presents a list of options in either a list or grid mode | ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class MessageComposer extends StatefulWidget { - const MessageComposer({super.key}); - - @override - State createState() => _MessageComposerState(); -} -class _MessageComposerState extends State { +// CometChatMessageComposer is typically used at the bottom of a messaging screen +class MessagingScreen extends StatelessWidget { + final User user; + + const MessagingScreen({required this.user}); @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: Column( - children: [ - const Spacer(), - CometChatMessageComposer() - ], - ) // A user or group object is required to launch this widget. - ) + body: Column( + children: [ + CometChatMessageHeader(user: user), + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], + ), ); } } ``` - - -*** +## Minimal Render -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### 1. OnSendButtonClick - -The `OnSendButtonClick` event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer `EditText`. However, you can overide this action with the following code snippet. +The simplest way to render `CometChatMessageComposer`: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// For a user conversation CometChatMessageComposer( user: user, - onSendButtonTap: (BuildContext context, BaseMessage baseMessage, PreviewMessageMode? previewMessageMode) { - // TODO("Not yet implemented") - }, ) -``` +// For a group conversation +CometChatMessageComposer( + group: group, +) +``` - -*** -##### 2. onChange +## Actions and Events + +### Callback Props + +Component-level callbacks that fire on specific user interactions: -This action handles changes in the value of text in the input field of the CometChatMessageComposer widget. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | User taps the send button | +| `onChange` | `Function(String)?` | Text in the input field changes | +| `onError` | `OnError?` | An error occurs | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Access controller functions | ```dart CometChatMessageComposer( user: user, + onSendButtonTap: (BuildContext context, BaseMessage baseMessage, PreviewMessageMode? previewMessageMode) { + // Handle send button tap + }, onChange: (String? text) { - // TODO("Not yet implemented") + // Handle text change + }, + onError: (e) { + // Handle error }, ) ``` - - -*** +## Custom View Slots + +Customize the appearance of `CometChatMessageComposer` by replacing default views with your own widgets. -##### 3. onError +| Slot | Signature | Replaces | +|------|-----------|----------| +| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | Auxiliary button area (AI, stickers) | +| `secondaryButtonView` | `ComposerWidgetBuilder?` | Secondary button area (attachment, voice) | +| `sendButtonView` | `Widget?` | Send button | +| `headerView` | `ComposerWidgetBuilder?` | Header section above input | +| `footerView` | `ComposerWidgetBuilder?` | Footer section below input | +| `attachmentOptions` | `ComposerActionsBuilder?` | Attachment options list | -This action doesn't change the behavior of the widget but rather listens for any errors that occur in the MessageList widget. +### Example: Custom Auxiliary Button View ```dart CometChatMessageComposer( user: user, - onError: (e) { - // TODO("Not yet implemented") + auxiliaryButtonView: (context, user, group, id) { + final existingAuxiliaryOptions = CometChatUIKit.getDataSource() + .getAuxiliaryOptions(user, group, context, id, Color(0xFFA1A1A1)); + return Row( + children: [ + existingAuxiliaryOptions, + Icon( + Icons.location_pin, + color: Color(0xFF6852D6), + ), + ], + ); }, ) ``` - - -*** - -### Filters - -`CometChatMessageComposer` widget does not have any available filters. - -*** - -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The `CometChatMessageComposer` Widget does not emit any events of its own. - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the `CometChatMessageComposer` widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. CometChatMessageComposerStyle + + + -To modify the styling, you can apply the `CometChatMessageComposerStyle` to the `CometChatMessageComposer` Widget using the `messageComposerStyle` property. +### Example: Custom Secondary Button View ```dart CometChatMessageComposer( user: user, - messageComposerStyle: CometChatMessageComposerStyle( - sendButtonIconBackgroundColor: Color(0xFFF76808), - secondaryButtonIconColor: Color(0xFFF76808), - auxiliaryButtonIconColor: Color(0xFFF76808) - ) + secondaryButtonView: (context, user, group, id) { + return Icon( + Icons.attach_file, + color: Color(0xFF6852D6), + ); + }, ) ``` - - - + -##### 2. MediaRecorder Style - -To customize the styles of the MediaRecorder widget within the `CometChatMessageComposer` Widget, use the `mediaRecorderStyle` property. For more details, please refer to [MediaRecorder](/ui-kit/flutter/component-styling#media-recorder) styles. +### Example: Custom Send Button View ```dart CometChatMessageComposer( user: user, - messageComposerStyle: CometChatMessageComposerStyle( - mediaRecorderStyle: CometChatMediaRecorderStyle( - recordIndicatorBackgroundColor: Color(0xFFF44649), - recordIndicatorBorderRadius: BorderRadius.circular(20), - pauseButtonBorderRadius: BorderRadius.circular(8), - deleteButtonBorderRadius: BorderRadius.circular(8), - stopButtonBorderRadius: BorderRadius.circular(8), - ), + sendButtonView: IconButton( + onPressed: () {}, + padding: EdgeInsets.all(4), + style: IconButton.styleFrom( + alignment: Alignment.center, + backgroundColor: Color(0xFFEDEAFA), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(4), + ), + ), + icon: Transform.rotate( + angle: 150, + child: Icon( + Icons.send, + size: 20, + color: Color(0xFF6852D6), + ), + ), ), ) ``` - - - + -*** - -##### 3. AI Options Style - -To customize the styles of the AI Options widget within the `CometChatMessageComposer` Widget, use the `aiOptionStyle`. +### Example: Custom Header View ```dart CometChatMessageComposer( user: user, -messageComposerStyle: CometChatMessageComposerStyle( - aiOptionStyle: AIOptionsStyle( - backgroundColor: Color(0xFFE4EBF5), - border: Border.all(width: 3, color: Colors.red), - ) - ), + headerView: (context, user, group, id) { + return Container( + margin: EdgeInsets.only(bottom: 2, left: 8, right: 8), + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + color: Color(0xFFEDEAFA), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Icon(Icons.volume_off, size: 20, color: Color(0xFF6852D6)), + Text( + "User has paused their notifications", + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400), + ), + ], + ), + ); + }, ) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - + +### Example: Custom Footer View + ```dart CometChatMessageComposer( user: user, - placeholderText: "Type a message...", - disableMentions: true, + footerView: (context, user, group, id) { + return Container( + width: MediaQuery.of(context).size.width / 1.08, + color: Colors.yellow, + padding: const EdgeInsets.all(8), + child: const Center(child: Text("Your Footer Widget")), + ); + }, ) ``` - - -Below is a list of customizations along with corresponding code snippets - -## Message Composer Properties - -| Property | Data Type | Description | -| ----------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | -| `user` | `User?` | Sets user for the message composer. | -| `group` | `Group?` | Sets group for the message composer. | -| `messageComposerStyle` | `CometChatMessageComposerStyle?` | Sets style for the message composer. | -| `placeholderText` | `String?` | Hint text for the input field. | -| `text` | `String?` | Initial text for the input field. | -| `onChange` | `Function(String text)?` | Callback triggered when text changes. | -| `textEditingController` | `TextEditingController?` | Controls the state of the text field. | -| `maxLine` | `int?` | Maximum number of lines allowed in the input field. | -| `disableMentions` | `bool?` | Disables mentions in the composer. | -| `disableTypingEvents` | `bool` | Disables typing events. | -| `disableSoundForMessages` | `bool` | Disables sound for sent messages. | -| `customSoundForMessage` | `String?` | URL for custom sound when a message is sent. | -| `customSoundForMessagePackage` | `String?` | Package name for the custom sound. | -| `parentMessageId` | `int` | ID of the parent message (default is 0). | -| `padding` | `EdgeInsetsGeometry?` | Sets padding for the message composer. | -| `messageInputPadding` | `EdgeInsetsGeometry?` | Sets padding for the message input field. | -| `sendButtonView` | `Widget?` | Custom send button widget. | -| `attachmentIcon` | `Widget?` | Custom attachment icon. | -| `attachmentIconURL` | `String?` | URL of the attachment icon. | -| `voiceRecordingIcon` | `Widget?` | Custom voice recording icon. | -| `aiIcon` | `Widget?` | Custom AI button icon. | -| `aiIconURL` | `String?` | URL for the AI button icon. | -| `aiIconPackageName` | `String?` | Package name for the AI icon. | -| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | UI component forwarded to message input as auxiliary button. | -| `secondaryButtonView` | `ComposerWidgetBuilder?` | UI component forwarded to message input as secondary button. | -| `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | Controls position of auxiliary button view. | -| `hideVoiceRecordingButton` | `bool?` | Option to hide the voice recording button. | -| `recorderStartButtonIcon` | `Widget?` | Custom start button icon for the recorder. | -| `recorderPauseButtonIcon` | `Widget?` | Custom pause button icon for the recorder. | -| `recorderDeleteButtonIcon` | `Widget?` | Custom delete button icon for the recorder. | -| `recorderStopButtonIcon` | `Widget?` | Custom stop button icon for the recorder. | -| `recorderSendButtonIcon` | `Widget?` | Custom send button icon for the recorder. | -| `attachmentOptions` | `ComposerActionsBuilder?` | Provides options for file attachments. | -| `hideAttachmentButton` | `bool?` | Hide/display attachment button. | -| `hideImageAttachmentOption` | `bool?` | Hide/display image attachment option. | -| `hideVideoAttachmentOption` | `bool?` | Hide/display video attachment option. | -| `hideAudioAttachmentOption` | `bool?` | Hide/display audio attachment option. | -| `hideFileAttachmentOption` | `bool?` | Hide/display file attachment option. | -| `hidePollsOption` | `bool?` | Hide/display polls option. | -| `hideCollaborativeDocumentOption` | `bool?` | Hide/display collaborative document option. | -| `hideCollaborativeWhiteboardOption` | `bool?` | Hide/display collaborative whiteboard option. | -| `hideTakePhotoOption` | `bool?` | Hide/display take photo option. | -| `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | Callback triggered when the send button is tapped. | -| `onError` | `OnError?` | Callback to handle errors. | -| `stateCallBack` | `Function(CometChatMessageComposerController controller)?` | Callback to manage state of the message composer. | -| `hideSendButton` | `bool?` | Hide/display the send button. | -| `hideStickersButton` | `bool?` | Hide/display the sticker button. | -| `sendButtonIcon` | `Widget?` | Custom send button icon. | -| `disableMentionAll` | `bool?` | Controls whether group mentions like @all appear in suggestions. | -| `mentionAllLabelId` | `String?` | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | -| `mentionAllLabel` | `String?` | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your widgets and then incorporate those into the widget. - -*** - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) - -**Example** - -Here is the complete example for reference: - - -```dart -CometChatMessageComposer( - user: user, - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` - + +![Image](/images/046c76af-message_composer_footer_view_cometchat_screens-5812a879cc6949aa04be485821255e0a.png) + + +![Image](/images/e57c8a15-message_composer_footer_view_cometchat_screens-49ac543fd44c8879b857da46340db0fe.png) - - - - - -*** - -#### AttachmentOptions - -By using `attachmentOptions`, you can set a list of custom `MessageComposerActions` for the `CometChatMessageComposer` Widget. This will override the existing list of `MessageComposerActions`. - -**Example** - -Here is the complete example for reference: +### Example: Custom Attachment Options @@ -383,263 +360,213 @@ Here is the complete example for reference: CometChatMessageComposer( user: user, attachmentOptions: (context, user, group, id) { - return [ - CometChatMessageComposerAction( - id: "Custom Option 1", - title: "Custom Option 1", - icon: Icon( - Icons.play_circle, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 2", - title: "Custom Option 2", - icon: Icon( - Icons.add_box, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 3", - title: "Custom Option 3", - icon: Icon( - Icons.change_circle, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 4", - title: "Custom Option 4", - icon: Icon( - Icons.sunny, - color: Colors.black, - ), - ) - ]; - }, + return [ + CometChatMessageComposerAction( + id: "Custom Option 1", + title: "Custom Option 1", + icon: Icon(Icons.play_circle, color: Colors.black), + ), + CometChatMessageComposerAction( + id: "Custom Option 2", + title: "Custom Option 2", + icon: Icon(Icons.add_box, color: Colors.black), + ), + ]; + }, ) ``` - - -*** -#### AuxiliaryButton Widget - -You can insert a custom widget into the `CometChatMessageComposer` widget to add additional functionality using the `auxiliaryButtonView` property. - -**Example** - -Here is the complete example for reference: +## Styling + +Customize the appearance of `CometChatMessageComposer` using `CometChatMessageComposerStyle`. + +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message composer | +| `border` | `BoxBorder?` | Border of the message composer | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message composer | +| `closeIconTint` | `Color?` | Color for the close icon | +| `dividerColor` | `Color?` | Color of the divider | +| `dividerHeight` | `double?` | Height of the divider | +| `sendButtonIconColor` | `Color?` | Color of the send button icon | +| `sendButtonIconBackgroundColor` | `Color?` | Background color of the send button | +| `sendButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the send button | +| `secondaryButtonIconColor` | `Color?` | Color of the secondary button icon | +| `secondaryButtonIconBackgroundColor` | `Color?` | Background color of the secondary button | +| `auxiliaryButtonIconColor` | `Color?` | Color of the auxiliary button icon | +| `auxiliaryButtonIconBackgroundColor` | `Color?` | Background color of the auxiliary button | +| `textStyle` | `TextStyle?` | Style of the text | +| `textColor` | `Color?` | Color of the text | +| `placeHolderTextStyle` | `TextStyle?` | Style of the placeholder text | +| `placeHolderTextColor` | `Color?` | Color of the placeholder text | +| `filledColor` | `Color?` | Background color of the text input | +| `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `mediaRecorderStyle` | `CometChatMediaRecorderStyle?` | Style for media recorder | +| `aiOptionStyle` | `AIOptionsStyle?` | Style for AI options | + +### Example: Custom Styling ```dart CometChatMessageComposer( - user: user, - auxiliaryButtonView: (context, user, group, id) { - final existingAuxiliaryOptions = CometChatUIKit.getDataSource() - .getAuxiliaryOptions(user, group, context, id, Color(0xFFA1A1A1)); - return Row( - children: [ - existingAuxiliaryOptions, - Icon( - Icons.location_pin, - color: Color(0xFF6852D6), - ), - ], - ); - }, + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + sendButtonIconBackgroundColor: Color(0xFFF76808), + secondaryButtonIconColor: Color(0xFFF76808), + auxiliaryButtonIconColor: Color(0xFFF76808), + ), ) ``` - - - + -*** - -#### SecondaryButton Widget - -You can add a custom widget into the SecondaryButton widget for additional functionality using the `secondaryButtonView` property. - -**Example** - -Here is the complete example for reference: +### Example: Custom Media Recorder Style ```dart CometChatMessageComposer( - user: user, - secondaryButtonView: (context, user, group, id) { - return Icon( - Icons.attach_file, - color: Color(0xFF6852D6), - ); - } + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + mediaRecorderStyle: CometChatMediaRecorderStyle( + recordIndicatorBackgroundColor: Color(0xFFF44649), + recordIndicatorBorderRadius: BorderRadius.circular(20), + pauseButtonBorderRadius: BorderRadius.circular(8), + deleteButtonBorderRadius: BorderRadius.circular(8), + stopButtonBorderRadius: BorderRadius.circular(8), + ), + ), ) ``` - - - - - -*** - -#### SendButton Widget - -You can set a custom widget in place of the already existing send button widget. Using the `sendButtonView` property. - -**Example** - -Here is the complete example for reference: - - - -```dart - CometChatMessageComposer( - user: user, - sendButtonView: IconButton( - onPressed: () {}, - padding: EdgeInsets.all(4), - style: IconButton.styleFrom( - alignment: Alignment.center, - backgroundColor: Color(0xFFEDEAFA), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(4), - )), - icon: Transform.rotate( - angle: 150, - child: Icon( - Icons.send, - size: 20, - color: Color(0xFF6852D6), - ), - ) - ), - ) -``` - - - - - - - + -*** - -#### Header Widget - -You can set custom headerView to the `CometChatMessageComposer` widget using the `headerView` property - -**Example** - -Here is the complete example for reference: +### Example: Custom AI Options Style ```dart CometChatMessageComposer( - user: user, - headerView: (context, user, group, id) { - return Container( - margin: EdgeInsets.only( - bottom: 2, - left: 8, - right: 8), - padding: EdgeInsets.all(8), - decoration: BoxDecoration( - color: Color(0xFFEDEAFA), - borderRadius: BorderRadius.circular(8), - ), - child: Row( - children: [ - Icon( - Icons.volume_off, - size: 20, - color: Color(0xFF6852D6), - ), - Text( - "User has paused their notifications", - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ), - ], - ), - ); - }, - ) + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + aiOptionStyle: AIOptionsStyle( + backgroundColor: Color(0xFFE4EBF5), + border: Border.all(width: 3, color: Colors.red), + ), + ), +) ``` - - - - - - -*** - -#### Footer Widget +## Advanced -You can set a custom footer widget to the `CometChatMessageComposer` widget using the `footerView` property: +### Text Formatters -**Example** - -Here is the complete example for reference: +Assigns the list of text formatters. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide). ```dart CometChatMessageComposer( user: user, - footerView: (context, user, group, id) { - return Container( - width: MediaQuery.of(context).size.width/1.08, - color: Colors.yellow, - padding: const EdgeInsets.all(8), - child: const Center(child: Text("Your Footer Widget")), - ); - }, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - - - -![Image](/images/046c76af-message_composer_footer_view_cometchat_screens-5812a879cc6949aa04be485821255e0a.png) - - - - -![Image](/images/e57c8a15-message_composer_footer_view_cometchat_screens-49ac543fd44c8879b857da46340db0fe.png) - - - - + + + -*** +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for the message composer | +| `group` | `Group?` | `null` | Group object for the message composer | +| `messageComposerStyle` | `CometChatMessageComposerStyle?` | - | Sets style for the message composer | +| `placeholderText` | `String?` | - | Hint text for the input field | +| `text` | `String?` | - | Initial text for the input field | +| `onChange` | `Function(String)?` | - | Callback triggered when text changes | +| `textEditingController` | `TextEditingController?` | - | Controls the state of the text field | +| `maxLine` | `int?` | - | Maximum number of lines allowed | +| `disableMentions` | `bool?` | `null` | Disables mentions in the composer | +| `disableTypingEvents` | `bool` | `false` | Disables typing events | +| `disableSoundForMessages` | `bool` | `false` | Disables sound for sent messages | +| `customSoundForMessage` | `String?` | - | URL for custom sound | +| `parentMessageId` | `int` | `0` | ID of the parent message | +| `padding` | `EdgeInsetsGeometry?` | - | Sets padding for the message composer | +| `messageInputPadding` | `EdgeInsetsGeometry?` | - | Sets padding for the message input field | +| `sendButtonView` | `Widget?` | - | Custom send button widget | +| `attachmentIcon` | `Widget?` | - | Custom attachment icon | +| `voiceRecordingIcon` | `Widget?` | - | Custom voice recording icon | +| `aiIcon` | `Widget?` | - | Custom AI button icon | +| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for auxiliary button | +| `secondaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for secondary button | +| `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | - | Controls position of auxiliary button view | +| `hideVoiceRecordingButton` | `bool?` | `null` | Hide/display voice recording button | +| `attachmentOptions` | `ComposerActionsBuilder?` | - | Provides options for file attachments | +| `hideAttachmentButton` | `bool?` | `null` | Hide/display attachment button | +| `hideImageAttachmentOption` | `bool?` | `null` | Hide/display image attachment option | +| `hideVideoAttachmentOption` | `bool?` | `null` | Hide/display video attachment option | +| `hideAudioAttachmentOption` | `bool?` | `null` | Hide/display audio attachment option | +| `hideFileAttachmentOption` | `bool?` | `null` | Hide/display file attachment option | +| `hidePollsOption` | `bool?` | `null` | Hide/display polls option | +| `hideCollaborativeDocumentOption` | `bool?` | `null` | Hide/display collaborative document option | +| `hideCollaborativeWhiteboardOption` | `bool?` | `null` | Hide/display collaborative whiteboard option | +| `hideTakePhotoOption` | `bool?` | `null` | Hide/display take photo option | +| `onSendButtonTap` | `Function(...)?` | - | Callback when send button is tapped | +| `onError` | `OnError?` | - | Callback to handle errors | +| `hideSendButton` | `bool?` | `null` | Hide/display the send button | +| `hideStickersButton` | `bool?` | `null` | Hide/display the sticker button | +| `sendButtonIcon` | `Widget?` | - | Custom send button icon | +| `disableMentionAll` | `bool` | `false` | Disables @all mentions in groups | +| `mentionAllLabel` | `String?` | - | Custom label for group mentions | +| `mentionAllLabelId` | `String?` | - | Custom label ID for group mentions | +| `headerView` | `ComposerWidgetBuilder?` | - | Custom header view | +| `footerView` | `ComposerWidgetBuilder?` | - | Custom footer view | +| `textFormatters` | `List?` | - | List of text formatters | + + + + Display user or group details in the header + + + Display messages in a conversation + + + Configure mentions look and feel + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index aaf056e49..41a73db4c 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -1,493 +1,500 @@ --- title: "Message List" +description: "A composite widget that displays a list of messages with real-time operations" --- -## Overview + +```json +{ + "component": "CometChatMessageList", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A composite widget that displays a list of messages with real-time operations. Includes various message types such as Text Messages, Media Messages, Stickers, and more.", + "primaryOutput": { + "prop": "onThreadRepliesClick", + "type": "void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message list (one of user or group is required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message list (one of user or group is required)" + }, + "messagesRequestBuilder": { + "type": "MessagesRequestBuilder?", + "default": "null", + "note": "Custom request builder for filtering messages" + }, + "templates": { + "type": "List?", + "default": "null", + "note": "Message templates for the list" + } + }, + "callbacks": { + "onThreadRepliesClick": "void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onReactionClick": "Function(String?, BaseMessage)?", + "onReactionLongPress": "Function(String?, BaseMessage)?", + "onReactionListItemClick": "Function(String?, BaseMessage?)?" + }, + "visibility": { + "hideTimestamp": { "type": "bool?", "default": null }, + "avatarVisibility": { "type": "bool?", "default": true }, + "receiptsVisibility": { "type": "bool?", "default": true }, + "disableReactions": { "type": "bool?", "default": false }, + "hideStickyDate": { "type": "bool?", "default": false }, + "hideReplyInThreadOption": { "type": "bool?", "default": false }, + "hideEditMessageOption": { "type": "bool?", "default": false }, + "hideDeleteMessageOption": { "type": "bool?", "default": false }, + "hideGroupActionMessages": { "type": "bool?", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool?", "default": null }, + "customSoundForMessages": { "type": "String?", "default": null } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "headerView": "Widget? Function(BuildContext, {User?, Group?, int?})?", + "footerView": "Widget? Function(BuildContext, {User?, Group?, int?})?" + }, + "formatting": { + "alignment": { "type": "ChatAlignment", "default": "ChatAlignment.standard" }, + "datePattern": { "type": "String Function(BaseMessage)?", "default": null }, + "dateSeparatorPattern": { "type": "String Function(DateTime)?", "default": null } + } + }, + "events": [], + "sdkListeners": [ + "onMessageReceived", + "onMessageEdited", + "onMessageDeleted", + "onTypingStarted", + "onTypingEnded" + ], + "compositionExample": { + "description": "CometChatMessageList is typically used within CometChatMessages, paired with CometChatMessageHeader and CometChatMessageComposer", + "components": ["CometChatMessageHeader", "CometChatMessageComposer", "CometChatMessages"], + "flow": "User/Group → MessageList displays messages → Real-time updates via SDK listeners" + }, + "types": { + "CometChatMessageListStyle": { + "backgroundColor": "Color?", + "border": "BoxBorder?", + "borderRadius": "BorderRadiusGeometry?", + "incomingMessageBubbleStyle": "CometChatIncomingMessageBubbleStyle?", + "outgoingMessageBubbleStyle": "CometChatOutgoingMessageBubbleStyle?", + "avatarStyle": "CometChatAvatarStyle?" + } + } +} +``` + -`MessageList` is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. +## Where It Fits -`MessageList` is primarily a list of the base widget [MessageBubble](/ui-kit/flutter/message-bubble-styling). The MessageBubble Widget is utilized to create different types of chat bubbles depending on the message type. +`CometChatMessageList` is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. + +`CometChatMessageList` is primarily a list of the base widget [MessageBubble](/ui-kit/flutter/message-bubble-styling). The MessageBubble Widget is utilized to create different types of chat bubbles depending on the message type. -## Usage - -### Integration - -You can launch `CometChatMessageList` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatMessageList` - - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatMessageList())); // A user or group object is required to launch this widget. -``` - - - - - - - -Simply adding the `MessageList` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. - - - -*** - -##### 2. Embedding `CometChatMessageList` as a Widget in the build Method - ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class MessageList extends StatefulWidget { - const MessageList({super.key}); - @override - State createState() => _MessageListState(); -} - -class _MessageListState extends State { +// CometChatMessageList is typically used within CometChatMessages +// or as part of a custom messaging screen +class MessagingScreen extends StatelessWidget { + final User user; + + const MessagingScreen({required this.user}); @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatMessageList() // A user or group object is required to launch this widget. - ) + body: Column( + children: [ + CometChatMessageHeader(user: user), + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], + ), ); } } ``` - - -*** - -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### onThreadRepliesClick +## Minimal Render -`onThreadRepliesClick` is triggered when you click on the threaded message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +The simplest way to render `CometChatMessageList`: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// For a user conversation CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - onThreadRepliesClick: (message, context, {template}) { { - // TODO("Not yet implemented") - }, + user: user, ) -``` +// For a group conversation +CometChatMessageList( + group: group, +) +``` - -*** + +Simply adding the `MessageList` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. + + + +## Filtering CometChatMessageList -##### onError +Use the `messagesRequestBuilder` prop to filter which messages appear in the list. -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +### Filter Recipes + +| Recipe | Code | +|--------|------| +| Limit messages | `MessagesRequestBuilder()..limit = 30` | +| Search messages | `MessagesRequestBuilder()..searchKeyword = "keyword"` | +| Filter by type | `MessagesRequestBuilder()..types = ["text"]` | +| Filter by category | `MessagesRequestBuilder()..categories = ["message"]` | ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") - }, + user: user, + messagesRequestBuilder: MessagesRequestBuilder() + ..uid = user.uid + ..searchKeyword = "searchKeyword" + ..limit = 30, ) ``` - - -*** + +The following parameters in messageRequestBuilder will always be altered inside the message list: +1. UID +2. GUID +3. types +4. categories + + +For the full MessagesRequestBuilder API, see the [SDK documentation](/sdk/flutter/additional-message-filtering). + +## Actions and Events + +### Callback Props -##### onLoad +Component-level callbacks that fire on specific user interactions: -Invoked when the list is successfully fetched and loaded, helping track component readiness. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onThreadRepliesClick` | `void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?` | User clicks on thread indicator | +| `onError` | `OnError?` | An error occurs while fetching messages | +| `onLoad` | `OnLoad?` | List is successfully fetched and loaded | +| `onEmpty` | `OnEmpty?` | List is empty | +| `onReactionClick` | `Function(String?, BaseMessage)?` | User clicks on a reaction pill | +| `onReactionLongPress` | `Function(String?, BaseMessage)?` | User long presses on a reaction pill | +| `onReactionListItemClick` | `Function(String?, BaseMessage?)?` | User clicks on a reaction list item | +| `addMoreReactionTap` | `Function(BaseMessage)?` | User clicks "Add More Reactions" button | ```dart CometChatMessageList( - onLoad: (list) { - // print("messages loaded: ${list.length}"); - }, + user: user, + onThreadRepliesClick: (message, context, {template}) { + // Handle thread replies click + }, + onError: (e) { + // Handle error + }, + onLoad: (list) { + print("Messages loaded: ${list.length}"); + }, + onEmpty: () { + print("No messages"); + }, + onReactionClick: (emoji, message) { + // Handle reaction click + }, ) ``` - - -*** - -##### onEmpty +### SDK Events (Real-Time, Automatic) -Called when the list is empty, enabling custom handling such as showing a placeholder message. - - - -```dart -CometChatMessageList( - onEmpty: () { - // print("Groups empty"); - }, -) -``` +The component automatically handles these SDK listeners for real-time updates: - +| SDK Listener | Handled Automatically | +|--------------|----------------------| +| `onMessageReceived` | Adds new message to the list | +| `onMessageEdited` | Updates edited message in the list | +| `onMessageDeleted` | Removes deleted message from the list | +| `onTypingStarted` | Shows typing indicator | +| `onTypingEnded` | Hides typing indicator | - +## Custom View Slots -*** +Customize the appearance of `CometChatMessageList` by replacing default views with your own widgets. -##### onReactionLongPress +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `headerView` | `Widget? Function(BuildContext, {User?, Group?, int?})?` | Header section | +| `footerView` | `Widget? Function(BuildContext, {User?, Group?, int?})?` | Footer section | +| `emptyChatGreetingView` | `WidgetBuilder?` | Empty chat greeting for AI | +| `newMessageIndicatorView` | `WidgetBuilder?` | New message indicator | -Function triggered when a user long presses on a reaction pill, allowing developers to override the default behavior. +### Example: Custom Header View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionLongPress: (emoji, message) { - // print("onReactionClick"); + user: user, + headerView: (context, {group, parentMessageId, user}) { + return Container( + width: double.maxFinite, + color: Color(0xFFEDEAFA), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Icon(Icons.notes_outlined, color: Color(0xFF6852D6)), + SizedBox(width: 8), + Text('Notes', style: TextStyle(color: Color(0xFF6852D6))), + ], + ), + ); }, ) ``` - - -*** - -##### addMoreReactionTap + + + -Function triggered when a user clicks on the 'Add More Reactions' button, allowing developers to handle this action. +### Example: Custom Footer View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - addMoreReactionTap: (message) { - // print("addMoreReactionTap"); + user: user, + footerView: (context, {group, parentMessageId, user}) { + return Container( + width: double.maxFinite, + color: Color(0xFFEDEAFA), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Icon(Icons.sunny, color: Color(0xFF6852D6)), + SizedBox(width: 8), + Text('Ice Breakers', style: TextStyle(color: Color(0xFF6852D6))), + ], + ), + ); }, ) ``` - - -*** - -##### onReactionClick + + + -The listener to be set for reacting to a message.Pass a non-null instance of onReactionClick to enable it. +### Example: Custom Loading State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionClick: (emoji, message) { - // print("onReactionClick"); + user: user, + loadingStateView: (context) { + return Center( + child: CircularProgressIndicator(), + ); }, ) ``` - - -*** - -##### onReactionListItemClick - -Function triggered when a reaction list item is clicked, allowing developers to override its behavior in CometChatReactionsList. +### Example: Custom Empty State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionListItemClick: (reaction, message) { - // print("onReactionListItemClick"); + user: user, + emptyStateView: (context) { + return Center( + child: Text("No messages yet. Start the conversation!"), + ); }, ) ``` - - -*** - -### Filters - -You can adjust the `MessagesRequestBuilder` in the MessageList Widget to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). - -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +### Example: Custom Error State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - messagesRequestBuilder: MessagesRequestBuilder() - ..uid = user.uid - ..searchKeyword = "searchKeyword" + user: user, + errorStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("Couldn't load messages"), + ElevatedButton( + onPressed: () { + // Retry logic + }, + child: Text("Retry"), + ), + ], + ), + ); + }, ) ``` - - - -The following parameters in messageRequestBuilder will always be altered inside the message list +## Styling -1. UID -2. GUID -3. types -4. categories +Customize the appearance of `CometChatMessageList` using `CometChatMessageListStyle`. - +### Style Properties -*** +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message list | +| `border` | `BoxBorder?` | Border of the message list | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message list | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for avatar in message bubble | +| `emptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `emptyStateTextColor` | `Color?` | Color for empty state text | +| `errorStateTextStyle` | `TextStyle?` | Style for error state text | +| `errorStateTextColor` | `Color?` | Color for error state text | +| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | +| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | +| `messageInformationStyle` | `CometChatMessageInformationStyle?` | Style for message information | +| `messageOptionSheetStyle` | `CometChatMessageOptionSheetStyle?` | Style for message option sheet | +| `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `reactionsStyle` | `CometChatReactionsStyle?` | Style for reactions | +| `aiSmartRepliesStyle` | `CometChatAISmartRepliesStyle?` | Style for smart replies | -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The MessageList Widget does not emit any events of its own. - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. MessageList Style - -You can set the `style` to the `CometChatMessageList` Widget to customize the styling. +### Example: Custom Styling ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, style: CometChatMessageListStyle( - backgroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808), - ) - ) + backgroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + ), ) ``` - - -*** - -##### 2. Avatar Style - -To apply customized styles to the `Avatar` widget in the `CometChatGroups` widget, you can use the following code snippet. For further insights on `Avatar` Styles [refer](/ui-kit/flutter/component-styling#avatar) +### Example: Custom Avatar Style ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - style: CometChatMessageListStyle( - avatarStyle: CometChatAvatarStyle( - border: Border.all(width: 5), - borderRadius: 20, - backgroundColor: Colors.red - ), - ), - ), + user: user, + style: CometChatMessageListStyle( + avatarStyle: CometChatAvatarStyle( + border: Border.all(width: 5), + borderRadius: 20, + backgroundColor: Colors.red, + ), + ), +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - - +### Example: Custom Mentions Style ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - readIcon: Icon(Icons.mark_chat_read, color: Colors.white), + user: user, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - -## CometChatMessageList Properties - -Below is a list of customizations along with corresponding code snippets: - -| Property | Data Type | Description | -| ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------- | -| `user` | `User?` | User object for the user message list. | -| `group` | `Group?` | Group object for the group message list. | -| `messagesRequestBuilder` | `MessagesRequestBuilder?` | Custom request builder passed to CometChat's SDK. | -| `style` | `CometChatMessageListStyle?` | Sets style for the message list. | -| `scrollController` | `ScrollController?` | Controller for the message list. | -| `emptyStateText` | `String?` | Text to display when the list is empty. | -| `errorStateText` | `String?` | Text to display when an error occurs. | -| `loadingStateView` | `WidgetBuilder?` | View for the loading state. | -| `emptyStateView` | `WidgetBuilder?` | View for the empty state. | -| `errorStateView` | `WidgetBuilder?` | View for the error state behind the dialog. | -| `stateCallBack` | `Function(CometChatMessageListController controller)?` | Access controller functions from the parent. | -| `disableSoundForMessages` | `bool?` | Disables sound for sent/received messages. | -| `customSoundForMessages` | `String?` | URL for the custom sound for outgoing messages. | -| `customSoundForMessagePackage` | `String?` | Package name if the sound URL is from another package. | -| `readIcon` | `Widget?` | Custom read icon for message receipt. | -| `deliveredIcon` | `Widget?` | Custom delivered icon for message receipt. | -| `sentIcon` | `Widget?` | Custom sent icon for message receipt. | -| `waitIcon` | `Widget?` | Custom wait icon for message receipt. | -| `alignment` | `ChatAlignment` | Chat alignment setting. | -| `avatarVisibility` | `bool?` | Toggle visibility of avatars. | -| `datePattern` | `String Function(BaseMessage message)?` | Custom date pattern visible in message receipts. | -| `hideTimestamp` | `bool?` | Toggle visibility of timestamps. | -| `templates` | `List?` | Templates for the message list. | -| `onThreadRepliesClick` | `ThreadRepliesClick?` | Callback for clicking on the thread indicator. | -| `headerView` | `Widget? Function(BuildContext, {User? user, Group? group, int? parentMessageId})?` | Custom header view. | -| `footerView` | `Widget? Function(BuildContext, {User? user, Group? group, int? parentMessageId})?` | Custom footer view. | -| `dateSeparatorPattern` | `String Function(DateTime)?` | Pattern for the date separator. | -| `onError` | `OnError?` | Callback triggered when an error occurs. | -| `receiptsVisibility` | `bool?` | Controls visibility of read receipts. | -| `dateSeparatorStyle` | `CometChatDateStyle?` | Style for the date separator. | -| `disableReactions` | `bool?` | Toggle visibility of reactions. | -| `addReactionIcon` | `Widget?` | Custom icon for adding a reaction. | -| `addMoreReactionTap` | `Function(BaseMessage message)?` | Custom `onTap` for adding reactions. | -| `favoriteReactions` | `List?` | List of frequently used reactions. | -| `textFormatters` | `List?` | List of text formatters for text messages. | -| `disableMentions` | `bool?` | Disables formatting of mentions. | -| `padding` | `EdgeInsetsGeometry?` | Sets padding for the message list. | -| `margin` | `EdgeInsetsGeometry?` | Sets margin for the message list. | -| `width` | `double?` | Sets the width of the message list. | -| `height` | `double?` | Sets the height of the message list. | -| `reactionsRequestBuilder` | `ReactionsRequestBuilder?` | Fetches reactions for a specific message. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `onReactionClick` | `Function(String? emoji, BaseMessage message)?` | Custom action for clicking on a reaction pill. | -| `onReactionLongPress` | `Function(String? emoji, BaseMessage message)?` | Custom action for long pressing on a reaction pill. | -| `onReactionListItemClick` | `Function(String? reaction, BaseMessage? message)?` | Custom action for clicking on a reaction list item. | -| `hideStickyDate` | `bool?` | Hide the date separator. | -| `hideReplyInThreadOption` | `bool?` | Hide the "Reply in Thread" option. | -| `hideTranslateMessageOption` | `bool?` | Hide the "Translate Message" option. | -| `hideEditMessageOption` | `bool?` | Hide the "Edit Message" option. | -| `hideDeleteMessageOption` | `bool?` | Hide the "Delete Message" option. | -| `hideReactionOption` | `bool?` | Hide the "Reaction" option. | -| `hideMessagePrivatelyOption` | `bool?` | Hide the "Message Privately" option. | -| `hideCopyMessageOption` | `bool?` | Hide the "Copy Message" option. | -| `hideMessageInfoOption` | `bool?` | Hide the "Message Info" option. | -| `hideGroupActionMessages` | `bool?` | Hide group action messages. | -| `enableConversationStarters` | `bool?` | Enables conversation starters in new conversations. | -| `enableSmartReplies` | `bool?` | Enables smart replies in the chat. | -| `hideShareMessageOption` | `bool?` | Hide the "Share Message" option. | -| `smartRepliesDelayDuration` | `int?` | Delay in milliseconds before triggering Smart Replies. | -| `smartRepliesKeywords` | `List?` | Keywords that trigger Smart Replies. | -| `addTemplate` | `List?` | Add custom message templates to the existing templates. | -| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | Callback that can be used to format the date and time. | -| `hideModerationView` | `bool?` | Hide the moderation view | -| `hideThreadView` | `bool?` | Hide the thread view | -| `suggestedMessages` | `List?` | List of predefined replies for the AI assistant | -| `hideSuggestedMessages` | `bool?` | Hide the suggested messages | -| `emptyChatGreetingView` | `WidgetBuilder?` | View for empty chat view in AI assistant | -| `setAiAssistantTools` | `Map?` | Registers tool names with their corresponding callback functions | -| `streamingSpeed` | `int?` | Sets the speed of streaming for AI assistant | -| `hideDateSeparator` | `bool?` | Hide the date separator | -| `mentionAllLabelId` | `String?` | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | -| `mentionAllLabel` | `String?` | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | -| `hideFlagOption` | `bool?` | Hide the visibility of the "Report" option in the message actions menu. | -| `hideFlagRemarkField` | `bool?` | Hide the remark text area in the flag message dialog. | -| `unreadMessageThreshold` | `int?` | Sets the threshold for unread messages, determining when a message is marked as unread. | -| `startFromUnreadMessages` | `bool?` | Starts the message list from the first unread message. | -| `showMarkAsUnreadOption` | `bool?` | show the visibility of the "Mark unread" option in the message actions menu. | -| `newMessageIndicatorView` | `Widget?` | Custom view for the unread message indicator. | -| `enableConversationSummary` | `bool?` | Enables conversation summary generation. | -| `generateConversationSummary` | `bool?` | Triggers conversation summary generation. | -| `hideReplyOption` | `bool?` | Hides the reply message option. | -| `flagReasonLocalizer` | `String Function(String reasonId)?` | Function to localize flag reason IDs to the desired language. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### Template - -[CometChatMessageTemplate](/ui-kit/flutter/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/flutter/message-template). - -You can set message Templates to MessageList by using the following code snippet - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - templates: [], // Replace this placeholder with your custom widget. - ), -``` - - + + + - +## Advanced -**Example** +### Message Templates -Here is the complete example for reference: +[CometChatMessageTemplate](/ui-kit/flutter/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message bubbles. -```dart getTemplate() +```dart List getTemplate() { // Creating a text template CometChatMessageTemplate textTemplate = ChatConfigurator.getDataSource().getTextMessageTemplate(); @@ -500,517 +507,185 @@ List getTemplate() { color: alignment == BubbleAlignment.left ? Colors.deepPurple : Colors.yellow, fontSize: 14, fontWeight: FontWeight.bold, - fontFamily: "PlaywritePL" ), ), ); }; - // Creating an audio template - CometChatMessageTemplate audioTemplate = ChatConfigurator.getDataSource().getAudioMessageTemplate(); - // Creating a custom message template CometChatMessageTemplate customMessageTemplate = CometChatMessageTemplate( type: 'custom_template', category: 'custom_category', - bubbleView: (message, context, alignment) => const Text('this is a custom message template'), + bubbleView: (message, context, alignment) => const Text('Custom message'), ); - // custom list of templates - List messageTypes = [ - textTemplate, - audioTemplate, - customMessageTemplate - ]; - - return messageTypes; + return [textTemplate, customMessageTemplate]; } -``` - - - - - - -```dart +// Usage CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, templates: getTemplate(), ) ``` - - ![Image](/images/50ecaf18-message_list_template_cometchat_screens-ccc43daa9e5eb7548207eeed5d647749.png) - - ![Image](/images/5036c31b-message_list_template_cometchat_screens-99b7ffddbb7ab979bca23fade52a1503.png) - - - - - -*** - -#### DateSeparatorPattern - -You can modify the date pattern of the message list date separator to your requirement using `setDateSeparatorPattern()`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - dateSeparatorPattern: (DateTime dateTime) { - return ""; //Replace this empty string with your custom date time pattern. - }, -) -``` - - -**Example** +### Date Separator Pattern -Here is the complete example for reference: +Customize the date separator pattern: ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, dateSeparatorPattern: (DateTime dateTime) { return DateFormat("dd/MM/yyyy").format(dateTime); }, ) ``` - - ![Image](/images/49078272-message_list_date_time_separator_cometchat_screens-d90f711f80300c16d7f229543e3b7b23.png) - - ![Image](/images/b552b788-message_list_date_time_separator_cometchat_screens-dad8d61b105cdb2a5b3a9e5401c1a51c.png) - - - - - -*** - -#### SetDatePattern - -You can modify the date pattern to your requirement using .setDatePattern. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - datePattern: (message) { - return DateFormat('YOUR_PATTERN').format(message.sentAt!); - }, -) -``` - - -**Example** +### Date Pattern -Here is the complete example for reference: +Customize the date pattern for message receipts: ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, datePattern: (message) { return DateFormat('EEE, M/d/y').format(message.sentAt!); }, ) ``` - - ![Image](/images/7502494d-message_list_date_time_pattern_cometchat_screens-e29fe0e35e14bba04954bb7702abbdeb.png) - - ![Image](/images/36b9b0ae-message_list_date_time_pattern_cometchat_screens-601f4e68966053f11c3682665b8d3cb2.png) - - - - - -*** - -#### loadingStateView - -Customizes the loading indicator when messages are being fetched. - -Use Cases: - -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching messages..." text. - - - -```dart -CometChatMessageList( - loadingStateView: (context) { - // return leading view - }, -) -``` - - - - - -*** - -#### emptyStateView - -Defines a custom view to be displayed when no messages are available. - -Use Cases: - -* Show a friendly message like "No messages yet. Start the conversation!". - - - -```dart -CometChatMessageList( - emptyStateView: (context) { - // return empty view - }, -) -``` - - - - - -*** - -#### errorStateView - -Custom error state view displayed when fetching messages fails. - -Use Cases: - -* Show a retry button when an error occurs. -* Display a friendly message like "Couldn't load messages. Check your connection.". - - - -```dart -CometChatMessageList( - errorStateView: (context) { - // return error view - }, -) -``` - - - - -*** - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [MentionsFormatter Guide](/ui-kit/flutter/mentions-formatter-guide) - -Here is the complete example for reference: - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` - - - - - - - - - -*** - -#### HeaderView - -Allows developers to set a custom widget as the header of the message list. It provides context and access to `user`, `group`, and `parentMessageId`, enabling tailored designs for different use cases, such as displaying user details or group information. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - headerView: (context, {group, parentMessageId, user}) => - MessageListHeader( - backgroundColor: const Color(0XFFEDEAFA), - color: const Color(0XFF6852D6), - ), -) -``` - - - - -```dart -class MessageListHeader extends StatelessWidget { - const MessageListHeader( - {Key? key, required this.backgroundColor, required this.color}) - : super(key: key); - - final Color backgroundColor; - final Color color; - - @override - Widget build(BuildContext context) { - return Container( - width: double.maxFinite, - color: backgroundColor, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _buildHeaderItem( - icon: Icons.notes_outlined, - label: 'Notes', - color: color, - ), - _buildHeaderItem( - icon: Icons.bookmark, - label: 'Pinned Messages', - color: color, - ), - _buildHeaderItem( - icon: Icons.link, - label: 'Saved Links', - color: color, - ), - ], - ), - ), - ); - } - - Widget _buildHeaderItem( - {required IconData icon, required String label, required Color color}) { - return Container( - margin: const EdgeInsets.symmetric(horizontal: 5), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(30), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.1), - blurRadius: 8, - offset: const Offset(0, 4), - ), - ], - ), - child: Row( - children: [ - Icon( - icon, - color: color, - size: 20, - ), - const SizedBox(width: 4), - Text( - label, - style: TextStyle( - color: color, - fontSize: 12, - fontWeight: FontWeight.w400, - letterSpacing: 0), - ), - ], - ), - ); - } -} -``` - - - - - - - - - -*** - -#### FooterView - -Enables developers to add a custom widget to the footer of the message list. Like `headerView`, it supports `user`, `group`, and `parentMessageId` for context, offering flexibility to add components like timestamps, typing indicators, or action buttons. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - footerView: (context, {group, parentMessageId, user}) => - MessageListFooter( - backgroundColor: const Color(0XFFEDEAFA), - color: const Color(0XFF6852D6), - ), -) -``` - - - - -```dart -class MessageListFooter extends StatelessWidget { - const MessageListFooter( - {Key? key, required this.backgroundColor, required this.color}) - : super(key: key); - - final Color backgroundColor; - final Color color; - - @override - Widget build(BuildContext context) { - return Container( - width: double.maxFinite, - color: backgroundColor, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _buildFooterItem( - icon: Icons.sunny, - label: 'Ice Breakers', - color: color, - ), - _buildFooterItem( - icon: Icons.phone, - label: '+1-212-456-7890', - color: color, - ), - _buildFooterItem( - icon: Icons.photo_camera, - label: 'Instagram', - color: color, - ), - ], - ), - ), - ); - } - - Widget _buildFooterItem( - {required IconData icon, required String label, required Color color}) { - return Container( - margin: const EdgeInsets.symmetric(horizontal: 5), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(30), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.1), - blurRadius: 8, - offset: const Offset(0, 4), - ), - ], - ), - child: Row( - children: [ - Icon( - icon, - color: color, - size: 20, - ), - const SizedBox(width: 4), - Text( - label, - style: TextStyle( - color: color, - fontSize: 12, - fontWeight: FontWeight.w400, - letterSpacing: 0), - ), - ], - ), - ); - } -} -``` - - - - - - - - - -*** - -#### newMessageIndicatorView - -Customizes the unread message indicator view. - -Use Cases: - -* Set a custom view for the unread message indicator. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - newMessageIndicatorView: CustomWidget(), // your custom widget -) -``` - - - -*** +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for user message list | +| `group` | `Group?` | `null` | Group object for group message list | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Custom request builder for filtering | +| `style` | `CometChatMessageListStyle?` | - | Sets style for message list | +| `scrollController` | `ScrollController?` | - | Controller for the message list | +| `emptyStateText` | `String?` | - | Text when list is empty | +| `errorStateText` | `String?` | - | Text when error occurs | +| `loadingStateView` | `WidgetBuilder?` | - | View for loading state | +| `emptyStateView` | `WidgetBuilder?` | - | View for empty state | +| `errorStateView` | `WidgetBuilder?` | - | View for error state | +| `disableSoundForMessages` | `bool?` | `null` | Disables sound for messages | +| `customSoundForMessages` | `String?` | `null` | Custom sound URL | +| `readIcon` | `Widget?` | - | Custom read icon | +| `deliveredIcon` | `Widget?` | - | Custom delivered icon | +| `sentIcon` | `Widget?` | - | Custom sent icon | +| `waitIcon` | `Widget?` | - | Custom wait icon | +| `alignment` | `ChatAlignment` | `standard` | Chat alignment setting | +| `avatarVisibility` | `bool?` | `true` | Toggle avatar visibility | +| `datePattern` | `String Function(BaseMessage)?` | - | Custom date pattern | +| `hideTimestamp` | `bool?` | `null` | Toggle timestamp visibility | +| `templates` | `List?` | - | Message templates | +| `onThreadRepliesClick` | `ThreadRepliesClick?` | - | Thread replies callback | +| `headerView` | `Widget? Function(...)?` | - | Custom header view | +| `footerView` | `Widget? Function(...)?` | - | Custom footer view | +| `dateSeparatorPattern` | `String Function(DateTime)?` | - | Date separator pattern | +| `onError` | `OnError?` | - | Error callback | +| `receiptsVisibility` | `bool?` | `true` | Toggle read receipts | +| `dateSeparatorStyle` | `CometChatDateStyle?` | - | Date separator style | +| `disableReactions` | `bool?` | `false` | Toggle reactions | +| `addReactionIcon` | `Widget?` | - | Custom add reaction icon | +| `favoriteReactions` | `List?` | - | Frequently used reactions | +| `textFormatters` | `List?` | - | Text formatters | +| `disableMentions` | `bool?` | `null` | Disable mentions | +| `padding` | `EdgeInsetsGeometry?` | - | Padding for message list | +| `margin` | `EdgeInsetsGeometry?` | - | Margin for message list | +| `width` | `double?` | - | Width of message list | +| `height` | `double?` | - | Height of message list | +| `onLoad` | `OnLoad?` | - | Load callback | +| `onEmpty` | `OnEmpty?` | - | Empty callback | +| `onReactionClick` | `Function(String?, BaseMessage)?` | - | Reaction click callback | +| `onReactionLongPress` | `Function(String?, BaseMessage)?` | - | Reaction long press callback | +| `hideStickyDate` | `bool?` | `false` | Hide sticky date | +| `hideReplyInThreadOption` | `bool?` | `false` | Hide reply in thread option | +| `hideTranslateMessageOption` | `bool?` | `false` | Hide translate option | +| `hideEditMessageOption` | `bool?` | `false` | Hide edit option | +| `hideDeleteMessageOption` | `bool?` | `false` | Hide delete option | +| `hideReactionOption` | `bool?` | `false` | Hide reaction option | +| `hideMessagePrivatelyOption` | `bool?` | `false` | Hide message privately option | +| `hideCopyMessageOption` | `bool?` | `false` | Hide copy option | +| `hideMessageInfoOption` | `bool?` | `false` | Hide message info option | +| `hideGroupActionMessages` | `bool?` | `false` | Hide group action messages | +| `enableConversationStarters` | `bool?` | `false` | Enable conversation starters | +| `enableSmartReplies` | `bool?` | `false` | Enable smart replies | +| `hideShareMessageOption` | `bool?` | `false` | Hide share option | +| `smartRepliesDelayDuration` | `int?` | `10000` | Smart replies delay (ms) | +| `smartRepliesKeywords` | `List?` | - | Smart replies keywords | +| `addTemplate` | `List?` | - | Add custom templates | +| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | - | Date time formatter | +| `hideModerationView` | `bool?` | `null` | Hide moderation view | +| `hideThreadView` | `bool?` | `null` | Hide thread view | +| `suggestedMessages` | `List?` | - | AI assistant suggestions | +| `hideSuggestedMessages` | `bool?` | `false` | Hide suggested messages | +| `emptyChatGreetingView` | `WidgetBuilder?` | - | Empty chat greeting view | +| `setAiAssistantTools` | `Map?` | - | AI assistant tools | +| `streamingSpeed` | `int?` | - | AI streaming speed | +| `hideDateSeparator` | `bool?` | `false` | Hide date separator | +| `mentionAllLabel` | `String?` | - | Group mention label | +| `mentionAllLabelId` | `String?` | - | Group mention label ID | +| `hideFlagOption` | `bool?` | `false` | Hide report option | +| `hideFlagRemarkField` | `bool?` | `false` | Hide flag remark field | +| `startFromUnreadMessages` | `bool?` | `false` | Start from unread messages | +| `showMarkAsUnreadOption` | `bool?` | `false` | Show mark as unread option | +| `newMessageIndicatorView` | `WidgetBuilder?` | - | New message indicator view | +| `enableConversationSummary` | `bool?` | `false` | Enable conversation summary | +| `generateConversationSummary` | `bool?` | `false` | Generate conversation summary | +| `hideReplyOption` | `bool?` | `false` | Hide reply option | +| `flagReasonLocalizer` | `String Function(String)?` | - | Flag reason localizer | + + + + Display user or group details in the header + + + Compose and send messages + + + Customize message bubble templates + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/search.mdx b/ui-kit/flutter/search.mdx index e4511c558..34a29c7d2 100644 --- a/ui-kit/flutter/search.mdx +++ b/ui-kit/flutter/search.mdx @@ -1,34 +1,142 @@ --- title: "Search" +description: "A powerful search interface for finding conversations and messages in real time" --- -## Overview + +```json +{ + "component": "CometChatSearch", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A powerful search interface that allows users to search across conversations and messages in real time with filters and customization options", + "primaryOutput": { + "prop": "onMessageClicked", + "type": "void Function(BaseMessage message)" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message search" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message search" + }, + "searchFilters": { + "type": "List?", + "default": "null", + "note": "List of filters to be shown in the search screen" + }, + "searchIn": { + "type": "List?", + "default": "null", + "note": "List of scopes to be shown in the search result" + } + }, + "callbacks": { + "onBack": "VoidCallback?", + "onConversationClicked": "void Function(Conversation conversation)?", + "onMessageClicked": "void Function(BaseMessage message)?", + "onError": "OnError?", + "onConversationsLoad": "OnLoad?", + "onMessagesLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "usersStatusVisibility": { + "type": "bool?", + "default": "null" + }, + "receiptsVisibility": { + "type": "bool?", + "default": "null" + }, + "groupTypeVisibility": { + "type": "bool?", + "default": "null" + } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "initialStateView": "WidgetBuilder?", + "conversationItemView": "Widget? Function(BuildContext, Conversation)?", + "conversationTitleView": "Widget? Function(BuildContext, Conversation)?", + "conversationLeadingView": "Widget? Function(BuildContext, Conversation)?", + "conversationSubtitleView": "Widget? Function(BuildContext, Conversation)?", + "conversationTailView": "Widget? Function(BuildContext, Conversation)?", + "searchTextMessageView": "Widget? Function(BuildContext, TextMessage)?", + "searchImageMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchVideoMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchFileMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchAudioMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchMessageLinkView": "Widget? Function(BuildContext, BaseMessage)?" + }, + "formatting": { + "dateSeparatorFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + }, + "timeSeparatorFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatSearch can be used standalone or embedded within other screens", + "components": ["CometChatConversations", "CometChatMessageList"], + "flow": "User searches → Results displayed → User clicks result → Navigate to conversation/message" + }, + "types": { + "SearchFilter": { + "label": "String", + "icon": "Widget?" + }, + "SearchScope": { + "conversations": "bool", + "messages": "bool" + } + } +} +``` + + +## Where It Fits -The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. `CometChatSearch` helps users find messages, conversations, media, and more through an intuitive and filterable search experience. It can be embedded in multiple contexts — as part of the conversation list, message header, or as a full-screen search experience. +CometChatSearch is a full-screen search experience that allows users to find messages, conversations, media, and more through an intuitive and filterable search interface. It can be embedded in multiple contexts — as part of the conversation list, message header, or as a standalone full-screen search experience. -## Usage - -### Integration - -You can launch `CometChatSearch` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. +## Minimal Render -##### 1. Using Navigator to Launch `CometChatSearch` +The simplest way to render CometChatSearch: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatSearch())); -``` +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +// Using Navigator to launch CometChatSearch +Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatSearch()) +); +``` - -##### 2. Embedding `CometChatSearch` as a Widget in the build Method +You can also embed it as a widget: @@ -36,330 +144,344 @@ Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatSearch( import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; -class SearchComponent extends StatefulWidget { - const SearchComponent({super.key}); - - @override - State createState() => _SearchComponentState(); -} - -class _SearchComponentState extends State { - +class SearchScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatSearch(), - ) + body: SafeArea( + child: CometChatSearch(), + ), ); } } ``` - - -*** +## Filtering -### Actions +Use the request builder props to filter which items appear in the search results. -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +### ConversationsRequestBuilder -#### 1. onConversationClicked - -`onConversationClicked` is triggered when you click on a Conversation from the search result. The `onConversationClicked` action doesn’t have a predefined behavior. You can override this action using the following code snippet. +Filter conversations in the search results: ```dart - CometChatSearch( - onConversationClicked: (conversation) { - // Handle conversation click - }, - ); +CometChatSearch( + conversationsRequestBuilder: ConversationsRequestBuilder() + ..limit = 30, +) ``` - -*** +### MessagesRequestBuilder -#### 2. onMessageClicked - -`onMessageClicked` is triggered when you click on a Message from the search result. The `onMessageClicked` action doesn’t have a predefined behavior. You can override this action using the following code snippet. +Filter messages in the search results: ```dart - CometChatSearch( - onMessageClicked: (message) { - // Handle message click - }, - ); +CometChatSearch( + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 50, +) ``` - -*** - -#### 3. onBack +### Scoped Search -`OnBack` is triggered when you click on the back button of the Message Header component. You can override this action using the following code snippet. +Search within a specific user or group conversation: ```dart - CometChatSearch( - onBack: () { - // Handle back action - }, - ); -``` - - - - -*** - -#### 4. onError - -This action doesn’t change the behavior of the component but rather listens for any errors that occur in the Conversations component. +// Search within a specific user's conversation +CometChatSearch( + user: user, +) - - -```dart - CometChatSearch( - onError: (e) { - // Handle error - }, - ); +// Search within a specific group's conversation +CometChatSearch( + group: group, +) ``` - -*** +## Actions and Events -### Filters +### Callback Props -#### 1. ConversationsRequestBuilder +Component-level callbacks that fire on specific user interactions: -You can set the `ConversationsRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to `ConversationRequestBuilder`. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onConversationClicked` | `void Function(Conversation conversation)?` | User clicks a conversation from search results | +| `onMessageClicked` | `void Function(BaseMessage message)?` | User clicks a message from search results | +| `onBack` | `VoidCallback?` | User clicks the back button | +| `onError` | `OnError?` | An error occurs in the component | +| `onConversationsLoad` | `OnLoad?` | Conversations are loaded | +| `onMessagesLoad` | `OnLoad?` | Messages are loaded | +| `onEmpty` | `OnEmpty?` | Search results are empty | ```dart - CometChatSearch( - conversationsRequestBuilder: ConversationsRequestBuilder(), - ); +CometChatSearch( + onConversationClicked: (conversation) { + // Navigate to the conversation + print('Conversation clicked: ${conversation.conversationId}'); + }, + onMessageClicked: (message) { + // Navigate to the message + print('Message clicked: ${message.id}'); + }, + onBack: () { + Navigator.pop(context); + }, + onError: (e) { + print('Error: $e'); + }, +) ``` - -*** - -#### 2. MessagesRequestBuilder - -You can set the `MessagesRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to `MessagesRequestBuilder`. - - - -```dart - CometChatSearch( - messagesRequestBuilder: MessagesRequestBuilder(), - ); -``` - - - +### Global UI Events -*** +The CometChatSearch component does not produce any global UI events. -## Events +## Custom View Slots -`Events` are emitted by a Component. By using event you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. +Customize the appearance of CometChatSearch by replacing default views with your own widgets. -The `CometChatSearch` component does not produce any events. +### State Views -*** +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `initialStateView` | `WidgetBuilder?` | Initial state before search | -## Customization +### Conversation View Slots -To fit your app’s design requirements, you can customize the appearance of the `CometChatSearch` component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `conversationItemView` | `Widget? Function(BuildContext, Conversation)?` | Entire conversation list item | +| `conversationLeadingView` | `Widget? Function(BuildContext, Conversation)?` | Avatar / left section | +| `conversationTitleView` | `Widget? Function(BuildContext, Conversation)?` | Name / title text | +| `conversationSubtitleView` | `Widget? Function(BuildContext, Conversation)?` | Secondary text / preview | +| `conversationTailView` | `Widget? Function(BuildContext, Conversation)?` | Right section / timestamp | -## Style +### Message View Slots -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `searchTextMessageView` | `Widget? Function(BuildContext, TextMessage)?` | Text message item | +| `searchImageMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Image message item | +| `searchVideoMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Video message item | +| `searchFileMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | File message item | +| `searchAudioMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Audio message item | +| `searchMessageLinkView` | `Widget? Function(BuildContext, BaseMessage)?` | Link message item | - - - +### Example: Custom Text Message View ```dart CometChatSearch( - searchStyle: CometChatSearchStyle( - backgroundColor: const Color(0xFFEDEAFA), - searchFilterChipTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchSectionHeaderTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - - searchConversationItemBackgroundColor: const Color(0xFFEDEAFA), - searchConversationSubTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchConversationTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchConversationDateTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', - fontWeight: FontWeight.bold, - ), - - searchSeeMoreStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - - searchMessageItemBackgroundColor: const Color(0xFFEDEAFA), - searchMessageTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchMessageSubTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchMessageTimeStampStyle: CometChatDateStyle( - textStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - ), - - searchTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), + searchTextMessageView: (context, message) { + String senderName = message.sender?.name ?? "Unknown"; + return Container( + padding: const EdgeInsets.all(16), + width: double.infinity, + color: const Color(0xFFE8E4F3), + child: Row( + children: [ + Text( + "$senderName: ", + style: const TextStyle( + color: Color(0xFF6B4FBB), + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Expanded( + child: Text( + message.text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: Color(0xFF4A4A4A), + fontSize: 16, + ), + ), + ), + ], ), ); + }, +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -## CometChatMessageHeader Properties - -Following is a list of customizations along with their corresponding code snippets: - -| Property | Data Type | Description | -| --------------------- | -------------------------| ----------------------------------------------------------------- | -| `user` | `User?` | Set `User` object, one is mandatory either `user` or `group`. | -| `group` | `Group?` | Set `Group` object, one is mandatory either `user` or `group`. | -| `usersStatusVisibility` | `bool?` | Controls visibility of status indicator shown if a user is online. | -| `groupTypeVisibility` | `bool?` | Hide the group type icon which is visible on the group icon. | -| `initialStateView` | `WidgetBuilder?` | Sets view fow initial state | -| `loadingStateView` | `WidgetBuilder?` | Sets view fow loading state | -| `emptyStateView` | `WidgetBuilder?` | Sets view fow empty state | -| `errorStateView` | `WidgetBuilder?` | Sets view fow error state | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### conversationItemView - -With this function, you can assign a custom list item view to an conversation in the search result. For more information, refer to the [listItemView](/ui-kit/flutter/conversations#listitemview) prop of the `CometChatConversations` component. - - -#### conversationLeadingView - -With this function, you can assign a custom leading view to an conversation in the search result. For more information, refer to the [leadingView](/ui-kit/flutter/conversations#leadingview) prop of the `CometChatConversations` component. - - -#### conversationTitleView - -With this function, you can assign a custom title view of an conversation in the search result. For more information, refer to the [titleview](/ui-kit/flutter/conversations#titleview) prop of the `CometChatConversations` component. - -#### conversationSubtitleView - -With this function, you can assign a custom subtitle view to an conversation in the search result. For more information, refer to the [subtitleview](/ui-kit/flutter/conversations#subtitleview) prop of the `CometChatConversations` component. - + + + -#### conversationTailView +### Icon Customization -With this function, you can assign a custom tail view to an conversation in the search result. For more information, refer to the [trailingview](/ui-kit/flutter/conversations#trailingview) prop of the `CometChatConversations` component. +| Prop | Type | Description | +|------|------|-------------| +| `searchBackIcon` | `Widget?` | Custom back icon | +| `searchClearIcon` | `Widget?` | Custom clear icon | -#### MessageItemView +## Styling -With message item view functions, you can assign custom views to different types of messages in the search result. +Customize the appearance of CometChatSearch using `CometChatSearchStyle`. -Here’s how you can override the default message item view with a custom one for text messages: + + + ```dart CometChatSearch( - searchTextMessageView: (context, message) { - String senderName = message.sender?.name ?? "Unknown"; - String messageText = ""; - messageText = message.text; - return Container( - padding: const EdgeInsets.all(16), - width: double.infinity, - color: const Color(0xFFE8E4F3), - child: Row( - children: [ - Text( - "$senderName: ", - style: const TextStyle( - color: Color(0xFF6B4FBB), - fontSize: 16, - fontWeight: FontWeight.bold, - ), - ), - Expanded( - child: Text( - messageText, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - color: Color(0xFF4A4A4A), - fontSize: 16, - ), - ), - ), - ], - ), - ); - }, - ); + searchStyle: CometChatSearchStyle( + backgroundColor: const Color(0xFFEDEAFA), + searchBackgroundColor: Colors.white, + searchTextColor: Colors.black, + searchPlaceHolderTextColor: Colors.grey, + + // Filter chip styling + searchFilterChipBackgroundColor: Colors.grey[200], + searchFilterChipSelectedBackgroundColor: Colors.purple, + searchFilterChipTextColor: Colors.black, + searchFilterChipSelectedTextColor: Colors.white, + + // Conversation item styling + searchConversationItemBackgroundColor: const Color(0xFFEDEAFA), + searchConversationTitleTextStyle: const TextStyle(fontWeight: FontWeight.bold), + searchConversationSubTitleTextStyle: const TextStyle(color: Colors.grey), + + // Message item styling + searchMessageItemBackgroundColor: const Color(0xFFEDEAFA), + searchMessageTitleTextStyle: const TextStyle(fontWeight: FontWeight.bold), + + // See more button + searchSeeMoreColor: Colors.purple, + ), +) ``` - - - - - - -Bellow is the list of message item view functions available for customization: - -| Function | Message Type | -| ----------------------------| -------------------------| -| `searchTextMessageView` | Text Message | -| `searchImageMessageView` | Image Message | -| `searchAudioMessageView` | Audio Message | -| `searchFileMessageView` | Document Message | -| `searchMessageLinkView` | Link Message | -| `searchVideoMessageView` | Video Message | - -#### DateTime Formatters - -#### dateSeparatorFormatterCallback - -You can modify the date pattern of the chat history date separator to your requirement using `dateSeparatorFormatterCallback`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [MentionsFormatter Guide](/ui-kit/flutter/mentions-formatter-guide) - -*** +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the search component | +| `searchBackgroundColor` | `Color?` | Background color of the search text field | +| `searchBorder` | `BorderSide?` | Border of the search text field | +| `searchBorderRadius` | `BorderRadius?` | Border radius of the search text field | +| `searchTextColor` | `Color?` | Color of the search text | +| `searchTextStyle` | `TextStyle?` | Style of the search text | +| `searchPlaceHolderTextColor` | `Color?` | Color of the placeholder text | +| `searchPlaceHolderTextStyle` | `TextStyle?` | Style of the placeholder text | +| `searchBackIconColor` | `Color?` | Color of the back icon | +| `searchClearIconColor` | `Color?` | Color of the clear icon | +| `searchFilterChipBackgroundColor` | `Color?` | Background color of filter chips | +| `searchFilterChipSelectedBackgroundColor` | `Color?` | Background color of selected filter chips | +| `searchFilterChipTextColor` | `Color?` | Text color of filter chips | +| `searchFilterChipSelectedTextColor` | `Color?` | Text color of selected filter chips | +| `searchFilterChipBorder` | `Border?` | Border of filter chips | +| `searchFilterChipSelectedBorder` | `Border?` | Border of selected filter chips | +| `searchFilterChipBorderRadius` | `BorderRadius?` | Border radius of filter chips | +| `searchSectionHeaderTextColor` | `Color?` | Color of section header text | +| `searchSectionHeaderTextStyle` | `TextStyle?` | Style of section header text | +| `searchConversationItemBackgroundColor` | `Color?` | Background color of conversation items | +| `searchConversationTitleTextColor` | `Color?` | Text color of conversation titles | +| `searchConversationTitleTextStyle` | `TextStyle?` | Style of conversation titles | +| `searchConversationSubTitleTextStyle` | `TextStyle?` | Style of conversation subtitles | +| `searchConversationTitleSubTextColor` | `Color?` | Text color of conversation subtitles | +| `searchConversationDateTextColor` | `Color?` | Text color of conversation dates | +| `searchConversationDateTextStyle` | `TextStyle?` | Style of conversation dates | +| `searchMessageItemBackgroundColor` | `Color?` | Background color of message items | +| `searchMessageTitleTextColor` | `Color?` | Text color of message titles | +| `searchMessageTitleTextStyle` | `TextStyle?` | Style of message titles | +| `searchMessageSubTitleTextColor` | `Color?` | Text color of message subtitles | +| `searchMessageSubTitleTextStyle` | `TextStyle?` | Style of message subtitles | +| `searchMessageTimeStampStyle` | `CometChatDateStyle?` | Style of message timestamps | +| `searchMessageDateSeparatorStyle` | `CometChatDateStyle?` | Style of date separators | +| `searchEmptyStateTextColor` | `Color?` | Text color for empty state | +| `searchEmptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `searchErrorStateTextColor` | `Color?` | Text color for error state | +| `searchErrorStateTextStyle` | `TextStyle?` | Style for error state text | +| `searchSeeMoreColor` | `Color?` | Color of "See More" button | +| `searchSeeMoreStyle` | `TextStyle?` | Style of "See More" button | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for avatars | +| `badgeStyle` | `CometChatBadgeStyle?` | Style for badges | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for scoped search | +| `group` | `Group?` | `null` | Group object for scoped search | +| `searchFilters` | `List?` | `null` | List of filters to show | +| `searchIn` | `List?` | `null` | List of search scopes | +| `usersStatusVisibility` | `bool?` | `null` | Show/hide user status indicator | +| `receiptsVisibility` | `bool?` | `null` | Show/hide message receipts | +| `groupTypeVisibility` | `bool?` | `null` | Show/hide group type icon | +| `onBack` | `VoidCallback?` | `null` | Back button callback | +| `onConversationClicked` | `Function(Conversation)?` | `null` | Conversation click callback | +| `onMessageClicked` | `Function(BaseMessage)?` | `null` | Message click callback | +| `onError` | `OnError?` | `null` | Error callback | +| `onConversationsLoad` | `OnLoad?` | `null` | Conversations load callback | +| `onMessagesLoad` | `OnLoad?` | `null` | Messages load callback | +| `onEmpty` | `OnEmpty?` | `null` | Empty state callback | +| `loadingStateView` | `WidgetBuilder?` | `null` | Custom loading view | +| `errorStateView` | `WidgetBuilder?` | `null` | Custom error view | +| `emptyStateView` | `WidgetBuilder?` | `null` | Custom empty view | +| `initialStateView` | `WidgetBuilder?` | `null` | Custom initial view | +| `conversationItemView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation item | +| `conversationTitleView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation title | +| `conversationLeadingView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation leading view | +| `conversationSubtitleView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation subtitle | +| `conversationTailView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation tail view | +| `searchTextMessageView` | `Widget? Function(BuildContext, TextMessage)?` | `null` | Custom text message view | +| `searchImageMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom image message view | +| `searchVideoMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom video message view | +| `searchFileMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom file message view | +| `searchAudioMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom audio message view | +| `searchMessageLinkView` | `Widget? Function(BuildContext, BaseMessage)?` | `null` | Custom link message view | +| `searchBackIcon` | `Widget?` | `null` | Custom back icon | +| `searchClearIcon` | `Widget?` | `null` | Custom clear icon | +| `dateSeparatorFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Date separator formatter | +| `timeSeparatorFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Time separator formatter | +| `conversationsProtocol` | `ConversationsBuilderProtocol?` | `null` | Conversations builder protocol | +| `conversationsRequestBuilder` | `ConversationsRequestBuilder?` | `null` | Conversations request builder | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Messages request builder | +| `searchStyle` | `CometChatSearchStyle?` | `null` | Style configuration | + + + + Display and manage chat conversations + + + Display messages in a conversation + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/threaded-messages-header.mdx b/ui-kit/flutter/threaded-messages-header.mdx index 5d92d9182..e9383fcf6 100644 --- a/ui-kit/flutter/threaded-messages-header.mdx +++ b/ui-kit/flutter/threaded-messages-header.mdx @@ -1,41 +1,120 @@ --- title: "Threaded Messages Header" +description: "A widget that displays the parent message of a thread with reply count" --- -## Overview + +```json +{ + "component": "CometChatThreadedHeader", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that displays the parent message of a thread along with a reply count, used as the header section in threaded message views", + "primaryOutput": { + "prop": "messageActionView", + "type": "Widget Function(BaseMessage message, BuildContext context)?" + }, + "props": { + "data": { + "parentMessage": { + "type": "BaseMessage", + "required": true, + "note": "Parent message for the thread" + }, + "loggedInUser": { + "type": "User", + "required": true, + "note": "Logged in user object" + }, + "template": { + "type": "CometChatMessageTemplate?", + "default": "null", + "note": "Message template used in the thread" + }, + "height": { + "type": "double?", + "default": "null", + "note": "Height of the widget" + }, + "width": { + "type": "double?", + "default": "null", + "note": "Width of the widget" + } + }, + "visibility": { + "receiptsVisibility": { + "type": "bool?", + "default": true + } + }, + "viewSlots": { + "messageActionView": "Widget Function(BaseMessage message, BuildContext context)?" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatThreadedHeader is typically used within CometChatThreadedMessages as the header component", + "components": ["CometChatThreadedMessages", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "Parent message displayed at top → Reply count shown → Message list below with replies" + }, + "types": {} +} +``` + -ThreadedMessages is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays all replies made to a particular message in a conversation. By default, the parent message will be displayed at the top, the message composer will be at the bottom and between them a message list will contain all replies. +## Where It Fits + +CometChatThreadedHeader is a component that displays the parent message of a thread along with a reply count. It's typically used as part of the ThreadedMessages composite component, appearing at the top of the threaded conversation view. + +ThreadedMessages is composed of the following widgets: + +| Widget | Description | +|--------|-------------| +| [MessageList](/ui-kit/flutter/message-list) | CometChatMessageList displays a list of reply messages | +| [MessageComposer](/ui-kit/flutter/message-composer) | CometChatMessageComposer helps in writing and sending replies | -ThreadedMessages is composed of the following widgets: - -| Widget | Description | -| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| [MessageList](/ui-kit/flutter/message-list) | CometChatMessageList is a widget that displays a list of Messages | -| [MessageComposer](/ui-kit/flutter/message-composer) | CometChatMessageComposer is a widget that helps in writing and editing of messages and also sending attachments | +## Minimal Render -## Usage +The simplest way to render CometChatThreadedHeader: -### Integration + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -You can launch `CometChatThreadedHeader` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. +CometChatThreadedHeader( + parentMessage: parentMessage, // Required: BaseMessage object + loggedInUser: loggedInUser, // Required: User object +) +``` + + -##### 1. Using Navigator to Launch `CometChatThreadedHeader` +You can also launch it using Navigator: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatThreadedHeader(loggedInUser: loggedInUser, parentMessage: parentMessage))); // Logged in user object and parent message object is required to launch this widget. +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatThreadedHeader( + loggedInUser: loggedInUser, + parentMessage: parentMessage, + ), + ), +); ``` - - -##### 2. Embedding `CometChatThreadedHeader` as a Widget in the build Method +Or embed it as a widget: @@ -51,146 +130,41 @@ class ThreadMessages extends StatefulWidget { } class _ThreadMessagesState extends State { - @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( - child: CometChatThreadedHeader(loggedInUser: loggedInUser, parentMessage: parentMessage) // Logged in user object and parent message object is need. + child: CometChatThreadedHeader( + loggedInUser: loggedInUser, + parentMessage: parentMessage, + ), ), ); } } ``` - - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -*** - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -### Thread Header +## Actions and Events -To modify the styling, you can apply the `ThreadedHeaderStyle` to the `CometChatThreadedHeader` Widget using the `style` property. +### Callback Props - - -```dart - CometChatThreadedHeader( - parentMessage: message, - loggedInUser: CometChatUIKit.loggedInUser!, - style: CometChatThreadedHeaderStyle( - bubbleContainerBackGroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808), - borderRadius: BorderRadius.circular(12), - ) - ), - messageActionView: (message, context) { - final numberOfReplies = message.replyCount; - String replyText = numberOfReplies == 1 - ? Translations.of(context).reply - : Translations.of(context).replies; - return Container( - width: double.maxFinite, - color: Color(0xFFFEEDE1), - padding: EdgeInsets.symmetric( - vertical: 4, - ), - child: Row( - children: [ - Flexible( - child: Divider( - color: Color(0xFFF76808), - ), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text( - "$numberOfReplies $replyText", - style: TextStyle( - color: Color(0xFFF76808), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ), - ), - Flexible( - child: Divider( - color: Color(0xFFF76808), - ), - ), - ], - ), - ); - }, - ); -``` - - - - - - - - +The CometChatThreadedHeader component does not have traditional callback props. Instead, it provides a `messageActionView` slot for customizing the action area. -The following properties are exposed by `ThreadedMessagesStyle`: +### Global UI Events -| Property | Data Type | Description | -| -------------------------------- | -------------------------------------- | ----------------------------------------------- | -| `bubbleContainerBackGroundColor` | `Color?` | Sets background color for the bubble container. | -| `bubbleContainerBorder` | `BoxBorder?` | Sets border for the bubble container. | -| `bubbleContainerBorderRadius` | `BorderRadiusGeometry?` | Sets border radius for the bubble container. | -| `countTextStyle` | `TextStyle?` | Sets text style for the reply count. | -| `countTextColor` | `Color?` | Sets color for the reply count text. | -| `countContainerBackGroundColor` | `Color?` | Sets background color for the count container. | -| `countContainerBorder` | `BoxBorder?` | Sets border for the count container. | -| `constraints` | `BoxConstraints?` | Sets constraints for the message container. | -| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Sets style for the incoming message bubble. | -| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Sets style for the outgoing message bubble. | +The CometChatThreadedHeader component does not produce any global UI events. -*** +## Custom View Slots -### Functionality +Customize the appearance of CometChatThreadedHeader by replacing default views with your own widgets. -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `messageActionView` | `Widget Function(BaseMessage message, BuildContext context)?` | Reply count section below the message bubble | -Below is a list of customizations along with corresponding code snippets - -| Property | Data Type | Description | -| ------------------- | ------------------------------------------------------ | ---------------------------------------- | -| `parentMessage` | `BaseMessage` | Parent message for the thread. | -| `messageActionView` | `Function(BaseMessage message, BuildContext context)?` | Custom action view for the message. | -| `style` | `CometChatThreadedHeaderStyle?` | Style parameter for the threaded header. | -| `loggedInUser` | `User` | Represents the logged-in user. | -| `template` | `CometChatMessageTemplate?` | Message template used in the thread. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your widgets, layouts, and UI elements and then incorporate those into the widget. - -#### MessageActionView - -By utilizing the `messageActionView` method, you can assign custom actions to the parent message bubble widget inside the `CometChatThreadedHeader` Widget. - -**Example** - -Here is the complete example for reference: +### Example: Custom Message Action View @@ -208,33 +182,165 @@ CometChatThreadedHeader( border: Border.all(width: 5, color: Color(0xFF6851D6)), ), child: const Center( - child: Text("Your Custom Action View", - style: TextStyle(color: Colors.white),), + child: Text( + "Your Custom Action View", + style: TextStyle(color: Colors.white), + ), ), ); }, ) ``` - - ![Image](/images/854e21f6-threaded_messages_action_view_cometchat_screens-7f88ee62a1538cddfa6da45c8eb28982.png) - - ![Image](/images/07942114-threaded_messages_action_view_cometchat_screens-0d30d7d0d3394b0a40ee33ea511157b3.png) + + +### Example: Custom Reply Count with Dividers + + + +```dart +CometChatThreadedHeader( + parentMessage: message, + loggedInUser: CometChatUIKit.loggedInUser!, + style: CometChatThreadedHeaderStyle( + bubbleContainerBackGroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), + ), + messageActionView: (message, context) { + final numberOfReplies = message.replyCount; + String replyText = numberOfReplies == 1 + ? Translations.of(context).reply + : Translations.of(context).replies; + return Container( + width: double.maxFinite, + color: Color(0xFFFEEDE1), + padding: EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Flexible(child: Divider(color: Color(0xFFF76808))), + Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: Text( + "$numberOfReplies $replyText", + style: TextStyle( + color: Color(0xFFF76808), + fontSize: 14, + fontWeight: FontWeight.w400, + ), + ), + ), + Flexible(child: Divider(color: Color(0xFFF76808))), + ], + ), + ); + }, +) +``` + + + + + + +### Templates + +The `template` prop is used to configure and set a message template for the parent message bubble. It allows for dynamic customization of message appearance, content, or other predefined settings based on the template provided. + + +```dart +CometChatThreadedHeader( + parentMessage: parentMessage, + loggedInUser: loggedInUser, + template: CometChatMessageTemplate( + type: MessageTypeConstants.text, + category: MessageCategoryConstants.message, + // Custom template configuration + ), +) +``` + -*** +## Styling -#### Templates +Customize the appearance of CometChatThreadedHeader using `CometChatThreadedHeaderStyle`. + + + +```dart +CometChatThreadedHeader( + parentMessage: parentMessage, + loggedInUser: loggedInUser, + style: CometChatThreadedHeaderStyle( + bubbleContainerBackGroundColor: Color(0xFFFEEDE1), + countTextColor: Colors.purple, + countContainerBackGroundColor: Colors.grey[100], + incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle( + backgroundColor: Colors.grey[200], + ), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), + ), +) +``` + + -The template method is used to configure and set a list of templates for message bubbles. It allows for dynamic customization of message appearance, content, or other predefined settings based on the templates provided. This method can be called to update or apply a new set of templates to the message handling system. +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `bubbleContainerBackGroundColor` | `Color?` | Background color for the bubble container | +| `bubbleContainerBorder` | `BoxBorder?` | Border for the bubble container | +| `bubbleContainerBorderRadius` | `BorderRadiusGeometry?` | Border radius for the bubble container | +| `countTextStyle` | `TextStyle?` | Text style for the reply count | +| `countTextColor` | `Color?` | Color for the reply count text | +| `countContainerBackGroundColor` | `Color?` | Background color for the count container | +| `countContainerBorder` | `BoxBorder?` | Border for the count container | +| `constraints` | `BoxConstraints?` | Constraints for the message container | +| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | +| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `parentMessage` | `BaseMessage` | Required | Parent message for the thread | +| `loggedInUser` | `User` | Required | Logged in user object | +| `messageActionView` | `Function(BaseMessage, BuildContext)?` | `null` | Custom action view for the message | +| `style` | `CometChatThreadedHeaderStyle?` | `null` | Style parameter for the threaded header | +| `template` | `CometChatMessageTemplate?` | `null` | Message template used in the thread | +| `height` | `double?` | `null` | Height of the widget | +| `width` | `double?` | `null` | Width of the widget | +| `receiptsVisibility` | `bool?` | `true` | Controls visibility of receipts | + + + + Display messages in a conversation + + + Compose and send messages + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/users.mdx b/ui-kit/flutter/users.mdx index c8324ee63..85c83a5f0 100644 --- a/ui-kit/flutter/users.mdx +++ b/ui-kit/flutter/users.mdx @@ -1,272 +1,446 @@ --- title: "Users" +description: "Searchable, scrollable list of all available users with avatar, name, and online/offline status." --- -## Overview - -The `CometChatUsers` is a [Widget](/ui-kit/flutter/components-overview#components), showcasing an accessible list of all available users. It provides an integral search functionality, allowing you to locate any specific user swiftly and easily. For each user listed, the widget displays the user's name by default, in conjunction with their avatar when available. Furthermore, it includes a status indicator, visually informing you whether a user is currently online or offline. - - - - + +```json +{ + "component": "CometChatUsers", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Searchable, scrollable list of all available users with avatar, name, and online/offline status.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(BuildContext context, User user)" + }, + "props": { + "data": { + "usersRequestBuilder": { + "type": "UsersRequestBuilder?", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "usersProtocol": { + "type": "UsersBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching users" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Users", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "searchPlaceholder": { + "type": "String?", + "default": "null", + "note": "Placeholder text for search input" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "height": { + "type": "double?", + "default": "null" + }, + "width": { + "type": "double?", + "default": "null" + } + }, + "callbacks": { + "onItemTap": "Function(BuildContext context, User user)?", + "onItemLongPress": "Function(BuildContext context, User user)?", + "onSelection": "Function(List? list, BuildContext context)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "usersStatusVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": true }, + "stickyHeaderVisibility": { "type": "bool?", "default": false } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(User user)?", + "leadingView": "Widget? Function(BuildContext context, User user)?", + "titleView": "Widget? Function(BuildContext context, User user)?", + "subtitleView": "Widget? Function(BuildContext context, User user)?", + "trailingView": "Widget? Function(BuildContext context, User user)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(User, CometChatUsersController, BuildContext)?", + "addOptions": "List? Function(User, CometChatUsersController, BuildContext)?", + "appBarOptions": "List Function(BuildContext context)?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" } + }, + "style": { + "usersStyle": { "type": "CometChatUsersStyle", "default": "CometChatUsersStyle()" } + } + }, + "events": [ + { + "name": "CometChatUserEvents.ccUserBlocked", + "payload": "User", + "description": "User blocked" + }, + { + "name": "CometChatUserEvents.ccUserUnblocked", + "payload": "User", + "description": "User unblocked" + } + ], + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "ccUserBlocked", + "ccUserUnblocked", + "onConnected" + ], + "compositionExample": { + "description": "User list wired to message view", + "components": [ + "CometChatUsers", + "CometChatMessages", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits User -> pass to CometChatMessages or individual message components" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" + } + } +} +``` + -The `CometChatUsers` widget is composed of the following Base Widgets: -| Widgets | Description | -| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | -| [ListBase](/ui-kit/flutter/list-base) | a reusable container widget having title, search box, customisable background and a List View | -| [ListItem](/ui-kit/flutter/list-item) | a widget that renders data obtained from a User object on a Tile having a title, subtitle, leading and trailing view | +## Where It Fits -## Usage +`CometChatUsers` is a contact list widget. It renders all available users and emits the selected `User` via `onItemTap`. Wire it to `CometChatMessages` or individual message components (`CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer`) to build a standard two-panel chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatUsers` is a custom **widget**, it can be launched directly by user actions such as button clicks or other interactions. It's also possible to integrate it into a **tab widget**. `CometChatUsers` offers several parameters and methods for UI customization. +class ChatApp extends StatefulWidget { + const ChatApp({super.key}); -You can launch `CometChatUsers` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _ChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatUsers` +class _ChatAppState extends State { + User? selectedUser; - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatUsers())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatUsers( + onItemTap: (context, user) { + setState(() { + selectedUser = user; + }); + }, + ), + ), + Expanded( + child: selectedUser != null + ? CometChatMessages(user: selectedUser) + : const Center(child: Text('Select a user')), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatUsers` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Users extends StatefulWidget { - const Users({super.key}); - - @override - State createState() => _UsersState(); -} - -class _UsersState extends State { +class UsersDemo extends StatelessWidget { + const UsersDemo({super.key}); @override Widget build(BuildContext context) { return const Scaffold( - body: SafeArea( - child: CometChatUsers() - ) + body: SafeArea( + child: CometChatUsers(), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatUsers()) +); +``` -##### onSelection +--- -When the `onSelection` event is triggered, it furnishes the list of selected users. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected users. +## Filtering Users -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Pass a `UsersRequestBuilder` to `usersRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatUsers( - selectionMode: SelectionMode.multiple, - activateSelection: ActivateSelection.onClick, - onSelection: (list, context) { - //TODO: This action will trigger the end of selection. - }, + usersRequestBuilder: UsersRequestBuilder() + ..friendsOnly = true + ..limit = 15, ) ``` - - -*** +### Filter Recipes -##### onItemTap +| Recipe | Code | +| --- | --- | +| Friends only | `UsersRequestBuilder()..friendsOnly = true` | +| Online users only | `UsersRequestBuilder()..userStatus = CometChatUserStatus.online` | +| Limit to 15 per page | `UsersRequestBuilder()..limit = 15` | +| Search by keyword | `UsersRequestBuilder()..searchKeyword = "alice"` | +| Hide blocked users | `UsersRequestBuilder()..hideBlockedUsers = true` | +| Filter by roles | `UsersRequestBuilder()..roles = ["admin", "moderator"]` | +| Filter by tags | `UsersRequestBuilder()..tags = ["vip"]` | +| Specific UIDs | `UsersRequestBuilder()..uids = ["uid1", "uid2"]` | -The `onItemTap` method is used to override the onClick behavior in `CometChatUsers`. This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + + +### UsersRequestBuilder Properties + +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of users to fetch per request. Maximum 100. | `..limit = 30` | +| `searchKeyword` | Search users by name. | `..searchKeyword = "John"` | +| `friendsOnly` | Fetch only friends. Default `false`. | `..friendsOnly = true` | +| `userStatus` | Filter by status: `CometChatUserStatus.online` or `CometChatUserStatus.offline`. | `..userStatus = CometChatUserStatus.online` | +| `hideBlockedUsers` | Hide blocked users from the list. Default `false`. | `..hideBlockedUsers = true` | +| `roles` | Filter users by specific roles. | `..roles = ["admin"]` | +| `tags` | Filter users by specific tags. | `..tags = ["vip"]` | +| `withTags` | Include tags in the User object. Default `false`. | `..withTags = true` | +| `uids` | Fetch specific users by UIDs. | `..uids = ["uid1", "uid2"]` | +| `build()` | Builds and returns a `UsersRequest` object. | `.build()` | + +Refer to [UsersRequestBuilder](/sdk/flutter/retrieve-users) for the full builder API. + +--- + +## Actions and Events + +### Callback Props + +#### onItemTap + +Fires when a user row is tapped. Primary navigation hook — set the active user and render the message view. ```dart CometChatUsers( onItemTap: (context, user) { - // TODO("Not yet implemented") + print("Selected: ${user.name}"); }, ) ``` - - -*** +#### onItemLongPress -##### onBack - -This method allows users to override the onBack Pressed behavior in `CometChatUsers` by utilizing the `onBack` , providing customization options for handling the back action. - -By default, this action has a predefined behavior: it simply dismisses the current widget. However, the flexibility of CometChat UI Kit allows you to override this standard behavior according to your application's specific requirements. You can define a custom action that will be performed instead when the back button is pressed. +Fires when a user row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatUsers( - onBack: () { - // TODO("Not yet implemented") + onItemLongPress: (context, user) { + // Show custom context menu }, ) ``` - - -*** -##### onError +#### onSelection -This method `onError`, allows users to override error handling within `CometChatUsers`, providing greater control over error responses and actions. +Fires when users are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatUsers( - onError: (e) { - // TODO("Not yet implemented") + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedList, context) { + print("Selected ${selectedList?.length ?? 0} users"); }, ) ``` - - -*** +#### onError -##### onItemLongPress - -This method `onItemLongPress`, empowers users to customize long-click actions within `CometChatUsers`, offering enhanced functionality and interaction possibilities. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatUsers( - onItemLongPress: (context, user) { - // TODO("Not yet implemented") + onError: (error) { + print("CometChatUsers error: $error"); }, ) ``` - - -*** +#### onBack -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires when the back button is pressed. ```dart CometChatUsers( - onLoad: (list) { - // print("User List: $list"); - }, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** +#### onLoad -##### onEmpty - -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the user list is successfully loaded. ```dart CometChatUsers( - onEmpty: () { - // print("User List is empty"); - }, + onLoad: (list) { + print("Loaded ${list.length} users"); + }, ) ``` - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a Widget. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. - -##### 1. UsersRequestBuilder +#### onEmpty -The [UsersRequestBuilder](/sdk/flutter/retrieve-users) enables you to filter and customize the user list based on available parameters in UsersRequestBuilder. This feature allows you to create more specific and targeted queries when fetching users. The following are the parameters available in [UsersRequestBuilder](/sdk/flutter/retrieve-users) +Fires when the user list is empty. ```dart CometChatUsers( - usersRequestBuilder: UsersRequestBuilder() - ..limit = 10 + onEmpty: () { + print("No users found"); + }, ) ``` - - -*** -### Events +### Global UI Events -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `CometChatUsers` Widget. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +`CometChatUserEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -To handle events supported by Users you have to add corresponding listeners by using `CometChatUserEvents` +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccUserBlocked` | A user is blocked | `User` | +| `ccUserUnblocked` | A user is unblocked | `User` | -| Events | Description | -| --------------- | --------------------------------------------------------------------- | -| ccUserBlocked | This will get triggered when the logged in user blocks another user | -| ccUserUnblocked | This will get triggered when the logged in user unblocks another user | +When to use: sync external UI with user state changes. For example, update a blocked users count badge when a user is blocked. ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatUserEventListener { @@ -277,482 +451,1065 @@ class _YourScreenState extends State with CometChatUserEventListener } @override - void dispose(){ - super.dispose(); + void dispose() { CometChatUserEvents.removeUsersListener("listenerId"); + super.dispose(); } @override void ccUserBlocked(User user) { - // TODO + print("Blocked: ${user.name}"); } @override void ccUserUnblocked(User user) { - // TODO + print("Unblocked: ${user.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To fit your app's design requirements, you can customize the appearance of the `CometChatUsers` widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onUserOnline` | Updates the user's status indicator to online | +| `onUserOffline` | Updates the user's status indicator to offline | +| `ccUserBlocked` | Updates blocked user in list | +| `ccUserUnblocked` | Updates unblocked user in list | +| `onConnected` | Refreshes user list when connection is re-established | -You can set the `CometChatUsersStyle` to the `CometChatUsers` widget to customize the styling. +Automatic: user presence changes (online/offline), blocked/unblocked state, connection recovery. - - -```dart -CometChatUsers( - usersStyle: CometChatUsersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a user parameter receive the `User` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(User)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, User)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, User)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, User)` | Subtitle text | +| `trailingView` | `Widget? Function(BuildContext, User)` | Right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(User, CometChatUsersController, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(User, CometChatUsersController, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List Function(BuildContext)` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart +Widget getCustomUserListItem(User user, BuildContext context) { + // Get status indicator + StatusIndicatorUtils statusIndicatorUtils = StatusIndicatorUtils.getStatusIndicatorFromParams( + context: context, + user: user, + onlineStatusIndicatorColor: Color(0xFF56E8A7), + ); + + return CometChatListItem( + id: user.uid, + avatarName: user.name, + avatarURL: user.avatar, + avatarHeight: 40, + avatarWidth: 40, + title: user.name, + key: UniqueKey(), + statusIndicatorColor: statusIndicatorUtils.statusIndicatorColor, + statusIndicatorIcon: statusIndicatorUtils.icon, + statusIndicatorStyle: CometChatStatusIndicatorStyle( + border: Border.all(width: 2, color: Color(0xFFFFFFFF)), + backgroundColor: Color(0xFF56E8A7), + ), + hideSeparator: true, + style: ListItemStyle( + background: user.status == CometChatUserStatus.online + ? const Color(0xFFE6F4ED) + : Colors.transparent, + titleStyle: TextStyle( + overflow: TextOverflow.ellipsis, + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF141414), + ), + padding: EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 8), + ), + ); +} + +// Usage: CometChatUsers( - title: "Your Title", - backButton: Icon(Icons.add_alert, color: Color(0xFF6851D6)), - searchPlaceholder: "Search Users", + listItemView: (user) => getCustomUserListItem(user, context), ) ``` - - -## List of properties exposed by `CometChatUsers` - -| Property | Data Type | Description | -| ------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------- | -| `usersProtocol` | `UsersBuilderProtocol?` | Custom users request builder protocol. | -| `usersRequestBuilder` | `UsersRequestBuilder?` | Custom request builder for fetching users. | -| `subtitleView` | `Widget? Function(BuildContext, User)` | Widget to set subtitle for each user item. | -| `listItemView` | `Widget Function(User)` | Custom view for each user item. | -| `usersStyle` | `CometChatUsersStyle` | Styling options for the users list. | -| `scrollController` | `ScrollController?` | Controller for scrolling the list. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input box. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Mode defining how users can be selected. | -| `onSelection` | `Function(List?, BuildContext)?` | Callback for handling user selection. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `appBarOptions` | `List Function(BuildContext context)?` | Options available in the app bar. | -| `usersStatusVisibility` | `bool?` | Hide status indicator on user avatars. | -| `activateSelection` | `ActivateSelection?` | Controls whether selection is allowed. | -| `onError` | `OnError?` | Callback for handling errors. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(BuildContext context, User)?` | Callback triggered when tapping a user. | -| `onItemLongPress` | `Function(BuildContext context, User)?` | Callback triggered on long press of a user. | -| `submitIcon` | `Widget?` | Widget for displaying the submit icon. | -| `hideAppbar` | `bool?` | Flag to show/hide the app bar. | -| `controllerTag` | `String?` | Identifier tag for controller management. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `stickyHeaderVisibility` | `bool?` | Hide alphabets used to separate users. | -| `searchKeyword` | `String?` | Keyword used to fetch initial user list. | -| `onLoad` | `OnLoad?` | Callback triggered when the list loads. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `addOptions` | `List? Function(User, CometChatUsersController, BuildContext)?` | Additional long-press actions for users. | -| `setOptions` | `List? Function(User, CometChatUsersController, BuildContext)?` | Actions available on long-press of a user. | -| `titleView` | `Widget? Function(BuildContext, User)?` | Custom title view for each user. | -| `leadingView` | `Widget? Function(User)?` | Widget for leading section of each user. | -| `trailingView` | `Widget? Function(User)?` | Widget for trailing section of each user. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -*** - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: - -* Muting notifications for a specific user. - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. ```dart CometChatUsers( - setOptions: (user, controller, context) { - // return options + leadingView: (context, user) { + return Container( + decoration: BoxDecoration( + border: Border.all( + color: user.status == CometChatUserStatus.online + ? Color(0xFF09C26F) + : Colors.transparent, + width: 2, + ), + borderRadius: BorderRadius.circular(8), + ), + child: CometChatAvatar( + image: user.avatar, + name: user.name, + style: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(6), + ), + ), + ); }, ) ``` - - -*** - -#### addOptions - -This method extends the existing set of actions available when users long press a user item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +### titleView -* Adding a "Report Spam" action. -* Introducing a "Save to Notes" option. -* Integrating third-party actions such as "Share to Cloud Storage". - -This method provides flexibility in modifying user interaction capabilities. +Replace the name / title text. Role badge inline example. ```dart CometChatUsers( - addOptions: (user, controller, context) { - // return options + titleView: (context, user) { + return Row( + children: [ + Text( + user.name ?? "", + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + if (user.role != null) + Container( + margin: EdgeInsets.only(left: 4), + padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Color(0xFF09C26F), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + user.role!, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ], + ); }, ) ``` - - -*** +### subtitleView -#### loadingStateView +Replace the subtitle text for each user. -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. - -* Showing a skeleton loader for users while data loads. -* Displaying a custom progress indicator with branding. -* Providing an animated loading experience for a more engaging UI. + + + ```dart CometChatUsers( - loadingStateView: (context) { - // return loading view + subtitleView: (context, user) { + final dateTime = user.lastActiveAt ?? DateTime.now(); + final subtitle = "Last Active at ${DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime)}"; + + return Text( + subtitle, + style: TextStyle( + color: Color(0xFF727272), + fontSize: 14, + fontWeight: FontWeight.w400, + ), + ); }, ) ``` - - -*** - -#### emptyStateView -Configures a custom view to be displayed when there are no users. This improves the user experience by providing meaningful content instead of an empty screen. +### trailingView -* Displaying a message like "No users yet. Start a new chat!". -* Showing an illustration or animation to make the UI visually appealing. -* Providing a button to start a new user. +Replace the right section. Custom tag badge example. ```dart CometChatUsers( - emptyStateView: (context) { - // return empty view + trailingView: (context, user) { + final tag = user.tags?.isNotEmpty == true ? user.tags!.first : null; + if (tag == null) return null; + + return Container( + padding: EdgeInsets.symmetric(horizontal: 6, vertical: 4), + decoration: BoxDecoration( + color: Color(0xFF6852D6), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + tag, + style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w600), + ), + ); }, ) ``` - - -*** - -#### errorStateView +### setOptions -Defines a custom error state view that appears when an issue occurs while loading users or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. - -* Showing "Something went wrong. Please try again." with a retry button. -* Displaying a connection issue message if the user is offline. -* Providing troubleshooting steps for the error. +Replace the context menu / long-press actions on each user item. ```dart CometChatUsers( - errorStateView: (context) { - // return error view + setOptions: (user, controller, context) { + return [ + CometChatOption( + id: "block", + title: "Block User", + icon: AssetConstants.close, + onClick: () { + CometChat.blockUsers([user.uid], onSuccess: (users) { + print("User blocked"); + }, onError: (error) { + print("Error: $error"); + }); + }, + ), + CometChatOption( + id: "view_profile", + title: "View Profile", + iconWidget: Icon(Icons.person_outline), + onClick: () { + // Navigate to user profile + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView +### addOptions -This method allows developers to set a custom leading view element that appears at the beginning of each user item. Typically, this space is used for profile pictures, avatars, or user badges. - -* Profile Pictures & Avatars – Display user profile images with online/offline indicators. -* Custom Icons or Badges – Show role-based badges (Admin, VIP, Verified) before the user name. -* Status Indicators – Add an active status ring or colored border based on availability. +Add to the existing context menu actions without removing defaults. ```dart CometChatUsers( - leadingView: (context, user) { - // return leading view - }, + addOptions: (user, controller, context) { + return [ + CometChatOption( + id: "add_friend", + title: "Add Friend", + iconWidget: Icon(Icons.person_add_outlined), + onClick: () { + // Add friend logic + }, + ), + CometChatOption( + id: "send_message", + title: "Send Message", + iconWidget: Icon(Icons.message_outlined), + onClick: () { + // Navigate to messages + }, + ), + ]; + }, ) ``` - - -*** -#### titleView +### appBarOptions -This method customizes the title view of each user item, which typically displays the user’s name. It allows for styling modifications, additional metadata, or inline action buttons. +Add custom widgets to the app bar. -* Styled Usernames – Customize fonts, colors, or text sizes for the name display. -* Additional Metadata – Show extra details like username handles or job roles. -* Inline Actions – Add a follow button or verification checkmark next to the name. + + + ```dart CometChatUsers( - titleView: (context, user) { - // return title view - }, + appBarOptions: (context) => [ + IconButton( + onPressed: () { + // Handle action + }, + icon: Icon(Icons.add_comment_outlined, color: Color(0xFF141414)), + ), + ], ) ``` - - -*** - -#### trailingView - -This method allows developers to customize the trailing (right-end) section of each user item, typically used for actions like buttons, icons, or extra information. - -* Quick Actions – Add a follow/unfollow button. -* Notification Indicators – Show unread message counts or alert icons. -* Custom Info Display – Display last active time or mutual connections. +For a more complete popup menu with styling: ```dart CometChatUsers( - trailingView: (context, user) { - // return trailing view - }, + appBarOptions: (context) => [ + PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: Color(0xFFF5F5F5), width: 1), + ), + color: Colors.white, + elevation: 4, + icon: Icon(Icons.more_vert, color: Color(0xFF141414)), + onSelected: (value) { + switch (value) { + case 'refresh': + // Refresh users list + break; + case 'settings': + // Navigate to settings + break; + } + }, + itemBuilder: (BuildContext context) => [ + PopupMenuItem( + value: 'refresh', + child: Row( + children: [ + Icon(Icons.refresh, color: Color(0xFFA1A1A1)), + SizedBox(width: 8), + Text("Refresh"), + ], + ), + ), + PopupMenuItem( + value: 'settings', + child: Row( + children: [ + Icon(Icons.settings, color: Color(0xFFA1A1A1)), + SizedBox(width: 8), + Text("Settings"), + ], + ), + ), + ], + ), + ], ) ``` - - -*** +--- + -#### ListItemView +## Styling -With this function, you can assign a custom ListItem to the `CometChatUsers` Widget. +Set `CometChatUsersStyle` to customize the appearance. ```dart CometChatUsers( - listItemView: (user) { - return Placeholder(); - }, + usersStyle: CometChatUsersStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + ), ) ``` - - - + -**Example** +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the component | +| `border` | `Border?` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the widget | +| `titleTextColor` | `Color?` | Color of the header title | +| `titleTextStyle` | `TextStyle?` | Style for the header title | +| `backIconColor` | `Color?` | Back button icon color | +| `searchBackgroundColor` | `Color?` | Background color of search box | +| `searchBorder` | `BorderSide?` | Border for search box | +| `searchBorderRadius` | `BorderRadius?` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color?` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle?` | Placeholder text style in search | +| `searchIconColor` | `Color?` | Search icon color | +| `searchInputTextColor` | `Color?` | Search input text color | +| `searchInputTextStyle` | `TextStyle?` | Search input text style | +| `separatorColor` | `Color?` | Color of list item separators | +| `separatorHeight` | `double?` | Height of list item separators | +| `stickyTitleColor` | `Color?` | Color of sticky alphabetical headers | +| `stickyTitleTextStyle` | `TextStyle?` | Style for sticky alphabetical headers | +| `itemTitleTextColor` | `Color?` | Color of user name in list items | +| `itemTitleTextStyle` | `TextStyle?` | Style for user name in list items | +| `itemBorder` | `BoxBorder?` | Border for list items | +| `listItemSelectedBackgroundColor` | `Color?` | Background color for selected items | +| `emptyStateTextColor` | `Color?` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle?` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color?` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle?` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color?` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle?` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color?` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle?` | Text style for error state subtitle | +| `retryButtonBackgroundColor` | `Color?` | Background color for retry button | +| `retryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius for retry button | +| `retryButtonBorder` | `BorderSide?` | Border for retry button | +| `retryButtonTextColor` | `Color?` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle?` | Text style for retry button | +| `submitIconColor` | `Color?` | Color of submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color?` | Background color of unchecked checkbox | +| `checkBoxCheckedBackgroundColor` | `Color?` | Background color of checked checkbox | +| `checkboxSelectedIconColor` | `Color?` | Color of checkmark icon | +| `checkBoxBorderRadius` | `BorderRadiusGeometry?` | Border radius for checkbox | +| `checkBoxBorder` | `BorderSide?` | Border for checkbox | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for user avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicators | + +--- + -Here is the complete example for reference: +## Common Patterns + +### Custom empty state with CTA -```dart custom_list_item.dart - Widget getCustomUserListItem(User user) { - return CometChatListItem( - id: user.uid, - avatarName: user.name, - avatarURL: user.avatar, - avatarHeight: 40, - avatarWidth: 40, - title: user.name, - key: UniqueKey(), - statusIndicatorStyle: CometChatStatusIndicatorStyle( - border: Border.all( - width: 2, - color: Color(0xFFFFFFFF), - ), - backgroundColor: Color(0xFF56E8A7), - ), - hideSeparator: true, - style: ListItemStyle( - background: user.status == CometChatUserStatus.online - ? const Color(0xFFE6F4ED) - : Colors.transparent, - titleStyle: TextStyle( - overflow: TextOverflow.ellipsis, - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414), - ), - padding: EdgeInsets.only( - left: 16, - right: 16, - top: 8, - bottom: 8, - ), +```dart +CometChatUsers( + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No users found", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)), + SizedBox(height: 8), + ElevatedButton( + onPressed: () { + // Invite users + }, + child: Text("Invite Users"), + ), + ], ), ); - } + }, +) ``` - - +### Friends-only list + -```dart main.dart +```dart CometChatUsers( - listItemView: (user) { - return getCustomUserListItem(user); - }, + usersRequestBuilder: UsersRequestBuilder() + ..friendsOnly = true + ..limit = 15, ) ``` - - -*** - -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +### Multi-select with selection callback ```dart CometChatUsers( - subtitleView: (context, user) { - String subtitle = ""; - - final dateTime = user.lastActiveAt ?? DateTime.now(); - subtitle = "Last Active at ${DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime)}"; - - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - }, + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedUsers, context) { + if (selectedUsers != null && selectedUsers.isNotEmpty) { + print("Selected ${selectedUsers.length} users"); + // Create group with selected users, etc. + } + }, ) ``` - - - - - - -*** +### Hide all chrome — minimal list -#### AppBarOptions + + +```dart +CometChatUsers( + hideSearch: true, + hideAppbar: true, + usersStatusVisibility: false, + stickyHeaderVisibility: true, // hides alphabetical headers +) +``` + + -You can set the Custom AppBarOptions to the Conversations widget. +### Online users only ```dart CometChatUsers( - appBarOptions: (context) => [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.add_comment_outlined, - color: Color(0xFF141414), - ), - ), - ], + usersRequestBuilder: UsersRequestBuilder() + ..userStatus = CometChatUserStatus.online, ) ``` - - - - - +--- + + +## Accessibility + +The component renders a scrollable list of interactive items. Each user row supports: + +- Tap gesture for selection/navigation +- Long-press gesture for context menu actions +- Checkbox selection in multi-select mode with proper touch targets +- Status indicators with visual feedback for online/offline state + +For screen readers: +- User names are readable as list item titles +- Status indicators use color coding — consider adding `Semantics` widgets via `leadingView` if screen reader descriptions are needed for these visual indicators +- Selection state is communicated through checkbox widgets + +The component respects system accessibility settings including text scaling and high contrast modes. + +--- + +## Props + +All props are optional unless noted. + +### activateSelection + +Controls when selection mode activates. + +| | | +| --- | --- | +| Type | `ActivateSelection?` | +| Default | `null` | + +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` + +--- + +### addOptions + +Adds additional context menu actions to the default options. + +| | | +| --- | --- | +| Type | `List? Function(User, CometChatUsersController, BuildContext)?` | +| Default | `null` | + +--- + +### appBarOptions + +Custom widgets to display in the app bar. + +| | | +| --- | --- | +| Type | `List Function(BuildContext context)?` | +| Default | `null` | + +--- + +### backButton + +Custom back button widget. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in back arrow | + +--- + +### controllerTag + +Identifier tag for controller management. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + + +### emptyStateView + +Custom view displayed when there are no users. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in empty state | + +--- + +### errorStateView + +Custom view displayed when an error occurs. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in error state | + +--- + +### height + +Height of the widget. + +| | | +| --- | --- | +| Type | `double?` | +| Default | `null` | + +--- + +### hideAppbar + +Hides the app bar including title and search. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search input box. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | Built-in avatar | + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(User user)?` | +| Default | Built-in list item | + +--- + +### loadingStateView + +Custom view displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in shimmer | + +--- + + +### onBack + +Callback triggered when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback?` | +| Default | `null` | + +--- + +### onEmpty + +Callback triggered when the user list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty?` | +| Default | `null` | + +--- + +### onError + +Callback triggered when an error occurs. + +| | | +| --- | --- | +| Type | `OnError?` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback triggered on long press of a user item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### onItemTap + +Callback triggered when tapping a user item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### onLoad + +Callback triggered when the list is successfully loaded. + +| | | +| --- | --- | +| Type | `OnLoad?` | +| Default | `null` | + +--- + +### onSelection + +Callback triggered when users are selected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `Function(List? list, BuildContext context)?` | +| Default | `null` | + +--- + +### scrollController + +Controller for scrolling the list. + +| | | +| --- | --- | +| Type | `ScrollController?` | +| Default | `null` | + +--- + + +### searchBoxIcon + +Custom search box icon widget. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in search icon | + +--- + +### searchKeyword + +Pre-fills the search and filters the user list. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + +### searchPlaceholder + +Placeholder text for the search input box. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode?` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +--- + +### setOptions + +Replaces the default context menu actions. + +| | | +| --- | --- | +| Type | `List? Function(User, CometChatUsersController, BuildContext)?` | +| Default | `null` | + +--- + +### showBackButton + +Shows or hides the back button. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### stickyHeaderVisibility + +Hides alphabetical section headers when set to `true`. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `false` | + +Note: When `false`, alphabetical headers (A, B, C...) are shown to separate users. + +--- + + +### submitIcon + +Custom submit icon widget for selection mode. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in check icon | + +--- + +### subtitleView + +Custom renderer for the subtitle text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### title + +Title text displayed in the app bar. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `"Users"` | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### usersProtocol + +Custom protocol for fetching users. + +| | | +| --- | --- | +| Type | `UsersBuilderProtocol?` | +| Default | `null` | + +--- + +### usersRequestBuilder + +Controls which users load and in what order. + +| | | +| --- | --- | +| Type | `UsersRequestBuilder?` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### usersStatusVisibility + +Shows or hides the online/offline status indicator on user avatars. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `true` | + +--- + +### usersStyle + +Styling options for the users list. + +| | | +| --- | --- | +| Type | `CometChatUsersStyle` | +| Default | `CometChatUsersStyle()` | + +--- + +### width + +Width of the widget. + +| | | +| --- | --- | +| Type | `double?` | +| Default | `null` | + +--- + + +## Events + +`CometChatUsers` does not emit custom UI events. It subscribes to: + +| Event | Payload | Internal behavior | +| --- | --- | --- | +| `CometChatUserEvents.ccUserBlocked` | `User` | Updates blocked user in list | +| `CometChatUserEvents.ccUserUnblocked` | `User` | Updates unblocked user in list | + +--- + +## Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemTap: (ctx, user) => setActive(user)` | +| Filter which users appear | Component props | `usersRequestBuilder` | `usersRequestBuilder: UsersRequestBuilder()..friendsOnly = true` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideSearch: true` | +| Replace a section of the list item | Component props | `View` render props | `listItemView: (user) => CustomWidget()` | +| Change colors, fonts, spacing | Component props | `usersStyle` | `usersStyle: CometChatUsersStyle(titleTextColor: Colors.red)` | + +--- -*** + + + Display recent one-on-one and group conversations + + + Display and manage group chats + + + Display messages in a conversation + + + Learn how to customize the look and feel + + \ No newline at end of file From b45554b829800f82611de4e04bbf25fcf4b99423 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 12:09:48 +0530 Subject: [PATCH 13/32] fixes flutter docs --- ui-kit/flutter/group-members.mdx | 2 + ui-kit/flutter/message-composer.mdx | 18 ++++++- ui-kit/flutter/message-header.mdx | 73 ++++++++++++++++++++++++++++- ui-kit/flutter/message-list.mdx | 24 ++++++++++ ui-kit/flutter/search.mdx | 8 ++++ 5 files changed, 122 insertions(+), 3 deletions(-) diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index b5beb1fb3..6e8c4b369 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -922,7 +922,9 @@ CometChatGroupMembers( | `searchIconColor` | `Color?` | Search icon color | | `loadingIconColor` | `Color?` | Loading indicator color | | `emptyStateTextStyle` | `TextStyle?` | Style for empty state title | +| `emptyStateTextColor` | `Color?` | Color for empty state title text | | `emptyStateSubtitleTextStyle` | `TextStyle?` | Style for empty state subtitle | +| `emptyStateSubtitleTextColor` | `Color?` | Color for empty state subtitle text | | `errorStateTextStyle` | `TextStyle?` | Style for error state title | | `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | | `onlineStatusColor` | `Color?` | Online status indicator color | diff --git a/ui-kit/flutter/message-composer.mdx b/ui-kit/flutter/message-composer.mdx index 206701160..d9b0ff136 100644 --- a/ui-kit/flutter/message-composer.mdx +++ b/ui-kit/flutter/message-composer.mdx @@ -168,7 +168,7 @@ Component-level callbacks that fire on specific user interactions: | `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | User taps the send button | | `onChange` | `Function(String)?` | Text in the input field changes | | `onError` | `OnError?` | An error occurs | -| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Access controller functions | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Controller state callback for accessing controller functions | @@ -402,8 +402,10 @@ Customize the appearance of `CometChatMessageComposer` using `CometChatMessageCo | `sendButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the send button | | `secondaryButtonIconColor` | `Color?` | Color of the secondary button icon | | `secondaryButtonIconBackgroundColor` | `Color?` | Background color of the secondary button | +| `secondaryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the secondary button | | `auxiliaryButtonIconColor` | `Color?` | Color of the auxiliary button icon | | `auxiliaryButtonIconBackgroundColor` | `Color?` | Background color of the auxiliary button | +| `auxiliaryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the auxiliary button | | `textStyle` | `TextStyle?` | Style of the text | | `textColor` | `Color?` | Color of the text | | `placeHolderTextStyle` | `TextStyle?` | Style of the placeholder text | @@ -412,6 +414,10 @@ Customize the appearance of `CometChatMessageComposer` using `CometChatMessageCo | `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | | `mediaRecorderStyle` | `CometChatMediaRecorderStyle?` | Style for media recorder | | `aiOptionStyle` | `AIOptionsStyle?` | Style for AI options | +| `aiOptionSheetStyle` | `CometChatAiOptionSheetStyle?` | Style for AI option sheet | +| `attachmentOptionSheetStyle` | `CometChatAttachmentOptionSheetStyle?` | Style for attachment option sheet | +| `suggestionListStyle` | `CometChatSuggestionListStyle?` | Style for suggestion list | +| `messagePreviewStyle` | `CometChatMessagePreviewStyle?` | Style for message preview | ### Example: Custom Styling @@ -523,13 +529,17 @@ CometChatMessageComposer( | `disableTypingEvents` | `bool` | `false` | Disables typing events | | `disableSoundForMessages` | `bool` | `false` | Disables sound for sent messages | | `customSoundForMessage` | `String?` | - | URL for custom sound | +| `customSoundForMessagePackage` | `String?` | - | Package name for custom sound asset | | `parentMessageId` | `int` | `0` | ID of the parent message | | `padding` | `EdgeInsetsGeometry?` | - | Sets padding for the message composer | | `messageInputPadding` | `EdgeInsetsGeometry?` | - | Sets padding for the message input field | | `sendButtonView` | `Widget?` | - | Custom send button widget | | `attachmentIcon` | `Widget?` | - | Custom attachment icon | +| `attachmentIconURL` | `String?` | - | Path of the icon to show in the attachments button | | `voiceRecordingIcon` | `Widget?` | - | Custom voice recording icon | | `aiIcon` | `Widget?` | - | Custom AI button icon | +| `aiIconURL` | `String?` | - | Path of the icon to show in the AI button | +| `aiIconPackageName` | `String?` | - | Package name for AI icon asset | | `auxiliaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for auxiliary button | | `secondaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for secondary button | | `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | - | Controls position of auxiliary button view | @@ -549,12 +559,18 @@ CometChatMessageComposer( | `hideSendButton` | `bool?` | `null` | Hide/display the send button | | `hideStickersButton` | `bool?` | `null` | Hide/display the sticker button | | `sendButtonIcon` | `Widget?` | - | Custom send button icon | +| `recorderStartButtonIcon` | `Widget?` | - | Custom icon for media recorder start button | +| `recorderPauseButtonIcon` | `Widget?` | - | Custom icon for media recorder pause button | +| `recorderDeleteButtonIcon` | `Widget?` | - | Custom icon for media recorder delete button | +| `recorderStopButtonIcon` | `Widget?` | - | Custom icon for media recorder stop button | +| `recorderSendButtonIcon` | `Widget?` | - | Custom icon for media recorder send button | | `disableMentionAll` | `bool` | `false` | Disables @all mentions in groups | | `mentionAllLabel` | `String?` | - | Custom label for group mentions | | `mentionAllLabelId` | `String?` | - | Custom label ID for group mentions | | `headerView` | `ComposerWidgetBuilder?` | - | Custom header view | | `footerView` | `ComposerWidgetBuilder?` | - | Custom footer view | | `textFormatters` | `List?` | - | List of text formatters | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | - | Callback to access controller functions | diff --git a/ui-kit/flutter/message-header.mdx b/ui-kit/flutter/message-header.mdx index 6cddfc8ab..ab5ee45dc 100644 --- a/ui-kit/flutter/message-header.mdx +++ b/ui-kit/flutter/message-header.mdx @@ -136,6 +136,33 @@ CometChatMessageHeader( +### CometChatMessageHeaderStyle Properties + +| Property | Data Type | Description | +| ------------------------------------- | -------------------------------- | -------------------------------------------------------- | +| `backgroundColor` | `Color?` | Background color for the message header. | +| `border` | `BoxBorder?` | Border for the message header. | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the message header. | +| `titleTextStyle` | `TextStyle?` | Text style for the title. | +| `titleTextColor` | `Color?` | Color for the title text. | +| `subtitleTextStyle` | `TextStyle?` | Text style for the subtitle. | +| `subtitleTextColor` | `Color?` | Color for the subtitle text. | +| `typingIndicatorTextStyle` | `TextStyle?` | Text style for the typing indicator. | +| `onlineStatusColor` | `Color?` | Color for the online status indicator. | +| `backIconColor` | `Color?` | Color for the back icon. | +| `backIcon` | `Widget?` | Custom back icon widget. | +| `privateGroupBadgeIcon` | `Widget?` | Icon for private group badge. | +| `passwordProtectedGroupBadgeIcon` | `Widget?` | Icon for password protected group badge. | +| `privateGroupBadgeIconColor` | `Color?` | Color for private group badge icon. | +| `passwordProtectedGroupBadgeIconColor`| `Color?` | Color for password protected group badge icon. | +| `groupIconBackgroundColor` | `Color?` | Background color for group icon. | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for the avatar. | +| `callButtonsStyle` | `CometChatCallButtonsStyle?` | Style for call buttons. | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicator. | +| `newChatIconColor` | `Color?` | Color for the new chat icon. | +| `chatHistoryIconColor` | `Color?` | Color for the chat history icon. | +| `menuIconColor` | `Color?` | Color for the menu icon. | + *** ### Functionality @@ -181,8 +208,12 @@ Following is a list of customizations along with their corresponding code snippe | `avatarWidth` | `double?` | Set width for avatar. | | `height` | `double?` | Set height for message header. | | `padding` | `EdgeInsetsGeometry?` | Set padding for message header. | -| `showVideoCallButton` | `bool?` | Used to hide/display video call button. | -| `showVoiceCallButton` | `bool?` | Used to hide/display voice call button. | +| `hideVideoCallButton` | `bool?` | Used to hide video call button. | +| `hideVoiceCallButton` | `bool?` | Used to hide voice call button. | +| `showBackButton` | `bool?` | Toggle visibility for back button. Defaults to `true`. | +| `usersStatusVisibility` | `bool?` | Controls visibility of status indicator. Defaults to `true`. | +| `options` | `List? Function(User? user, Group? group, BuildContext context)?` | Set menu options for the header. | +| `menuIcon` | `Widget?` | Set custom menu icon widget. | | `leadingStateView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set leading view for the message header. | | `titleView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set the title view for the message header. | | `auxiliaryButtonView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set auxiliary view for the message header. | @@ -397,6 +428,44 @@ CometChatMessageHeader( *** +#### Options Menu + +You can add custom menu options to the message header using the `options` property. These options appear in a popup menu when the menu icon is tapped. + + + +```dart +CometChatMessageHeader( + user: user, + options: (User? user, Group? group, BuildContext context) { + return [ + CometChatOption( + id: "view_profile", + title: "View Profile", + icon: Icons.person, + onClick: () { + // Handle view profile action + }, + ), + CometChatOption( + id: "block_user", + title: "Block User", + icon: Icons.block, + onClick: () { + // Handle block user action + }, + ), + ]; + }, +) +``` + + + + + +*** + #### BackIcon You can customize the Back Icon according to your specific requirements by using the `.backButton` method. diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index 41a73db4c..54b943d1a 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -409,15 +409,35 @@ Customize the appearance of `CometChatMessageList` using `CometChatMessageListSt | `avatarStyle` | `CometChatAvatarStyle?` | Style for avatar in message bubble | | `emptyStateTextStyle` | `TextStyle?` | Style for empty state text | | `emptyStateTextColor` | `Color?` | Color for empty state text | +| `emptyStateSubtitleStyle` | `TextStyle?` | Style for empty state subtitle | +| `emptyStateSubtitleColor` | `Color?` | Color for empty state subtitle | | `errorStateTextStyle` | `TextStyle?` | Style for error state text | | `errorStateTextColor` | `Color?` | Color for error state text | +| `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | +| `errorStateSubtitleColor` | `Color?` | Color for error state subtitle | | `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | | `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | | `messageInformationStyle` | `CometChatMessageInformationStyle?` | Style for message information | | `messageOptionSheetStyle` | `CometChatMessageOptionSheetStyle?` | Style for message option sheet | | `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `actionBubbleStyle` | `CometChatActionBubbleStyle?` | Style for group action bubbles | +| `reactionListStyle` | `CometChatReactionListStyle?` | Style for reaction list | | `reactionsStyle` | `CometChatReactionsStyle?` | Style for reactions | | `aiSmartRepliesStyle` | `CometChatAISmartRepliesStyle?` | Style for smart replies | +| `aiConversationStarterStyle` | `CometChatAIConversationStarterStyle?` | Style for conversation starter | +| `aiConversationSummaryStyle` | `CometChatAIConversationSummaryStyle?` | Style for conversation summary | +| `aiAssistantSuggestedMessageTextStyle` | `TextStyle?` | Text style for AI suggested messages | +| `aiAssistantSuggestedMessageTextColor` | `Color?` | Text color for AI suggested messages | +| `aiAssistantSuggestedMessageBorder` | `Border?` | Border for AI suggested messages | +| `aiAssistantSuggestedMessageBorderRadius` | `BorderRadius?` | Border radius for AI suggested messages | +| `aiAssistantSuggestedMessageBackgroundColor` | `Color?` | Background color for AI suggested messages | +| `aiAssistantSuggestedMessageIconColor` | `Color?` | Icon color for AI suggested messages | +| `emptyChatGreetingTitleTextColor` | `Color?` | Text color for empty chat greeting title | +| `emptyChatGreetingTitleTextStyle` | `TextStyle?` | Text style for empty chat greeting title | +| `emptyChatGreetingSubtitleTextColor` | `Color?` | Text color for empty chat greeting subtitle | +| `emptyChatGreetingSubtitleTextStyle` | `TextStyle?` | Text style for empty chat greeting subtitle | +| `flagMessageStyle` | `CometchatFlagMessageStyle?` | Style for flag message dialog | +| `newMessageIndicatorStyle` | `CometChatNewMessageIndicatorStyle?` | Style for new message indicator | ### Example: Custom Styling @@ -674,6 +694,10 @@ CometChatMessageList( | `generateConversationSummary` | `bool?` | `false` | Generate conversation summary | | `hideReplyOption` | `bool?` | `false` | Hide reply option | | `flagReasonLocalizer` | `String Function(String)?` | - | Flag reason localizer | +| `reactionsRequestBuilder` | `ReactionsRequestBuilder?` | - | Request builder for reactions | +| `stateCallBack` | `Function(CometChatMessageListController)?` | - | Callback to access controller | +| `customSoundForMessagePackage` | `String?` | - | Package name for custom sound | +| `messageId` | `int?` | - | Specific message ID to scroll to | diff --git a/ui-kit/flutter/search.mdx b/ui-kit/flutter/search.mdx index 34a29c7d2..61ab7042f 100644 --- a/ui-kit/flutter/search.mdx +++ b/ui-kit/flutter/search.mdx @@ -400,7 +400,11 @@ CometChatSearch( | `searchFilterChipBackgroundColor` | `Color?` | Background color of filter chips | | `searchFilterChipSelectedBackgroundColor` | `Color?` | Background color of selected filter chips | | `searchFilterChipTextColor` | `Color?` | Text color of filter chips | +| `searchFilterChipTextStyle` | `TextStyle?` | Text style of filter chips | | `searchFilterChipSelectedTextColor` | `Color?` | Text color of selected filter chips | +| `searchFilterChipSelectedTextStyle` | `TextStyle?` | Text style of selected filter chips | +| `searchFilterIconColor` | `Color?` | Color of filter icons | +| `searchFilterSelectedIconColor` | `Color?` | Color of selected filter icons | | `searchFilterChipBorder` | `Border?` | Border of filter chips | | `searchFilterChipSelectedBorder` | `Border?` | Border of selected filter chips | | `searchFilterChipBorderRadius` | `BorderRadius?` | Border radius of filter chips | @@ -422,8 +426,12 @@ CometChatSearch( | `searchMessageDateSeparatorStyle` | `CometChatDateStyle?` | Style of date separators | | `searchEmptyStateTextColor` | `Color?` | Text color for empty state | | `searchEmptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `searchEmptyStateSubtitleColor` | `Color?` | Color for empty state subtitle | +| `searchEmptyStateSubtitleStyle` | `TextStyle?` | Style for empty state subtitle | | `searchErrorStateTextColor` | `Color?` | Text color for error state | | `searchErrorStateTextStyle` | `TextStyle?` | Style for error state text | +| `searchErrorStateSubtitleColor` | `Color?` | Color for error state subtitle | +| `searchErrorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | | `searchSeeMoreColor` | `Color?` | Color of "See More" button | | `searchSeeMoreStyle` | `TextStyle?` | Style of "See More" button | | `avatarStyle` | `CometChatAvatarStyle?` | Style for avatars | From 57b151eec1be8797e3fb2f8ca8494d84b7ccca03 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 13:31:14 +0530 Subject: [PATCH 14/32] updates integration guides --- ui-kit/flutter/flutter-conversation.mdx | 414 ++--------- ui-kit/flutter/flutter-one-to-one-chat.mdx | 710 +++---------------- ui-kit/flutter/flutter-tab-based-chat.mdx | 758 +++------------------ ui-kit/flutter/getting-started.mdx | 579 ++++------------ ui-kit/flutter/overview.mdx | 236 ++----- 5 files changed, 394 insertions(+), 2303 deletions(-) diff --git a/ui-kit/flutter/flutter-conversation.mdx b/ui-kit/flutter/flutter-conversation.mdx index 965ae8489..af6bd97a7 100644 --- a/ui-kit/flutter/flutter-conversation.mdx +++ b/ui-kit/flutter/flutter-conversation.mdx @@ -1,196 +1,51 @@ --- title: "Conversation List + Message View" sidebarTitle: "Conversation + Message" -description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets" +description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -```dart -// Show conversations with navigation to messages -CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - final target = conversation.conversationWith; - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - ), - ); - }, -) - -// Messages screen with header, list, and composer -Scaffold( - appBar: CometChatMessageHeader(user: user, group: group), - body: Column( - children: [ - Expanded(child: CometChatMessageList(user: user, group: group)), - CometChatMessageComposer(user: user, group: group), - ], - ), -) -``` + -**Key Components:** -- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) -- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) -- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) -- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Two-panel — conversation list + message view with Navigator push | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | WhatsApp, Telegram, Slack | -The **Conversation List + Message View** layout provides a seamless **two-panel chat interface**, commonly seen in modern messaging apps like **WhatsApp Web**, **Slack**, and **Microsoft Teams**. + -This layout allows users to switch between conversations while keeping the active chat open, delivering a **smooth, real-time messaging experience**. +This guide builds a two-panel chat layout — conversation list that navigates to a message screen. Users tap a conversation to open it. + +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -*** - -## **How It Works** - -This implementation uses Flutter's navigation system to create a mobile-friendly chat experience: - -1. **Conversation List Screen** – Displays all recent conversations using `CometChatConversations` -2. **Navigation** – Tapping a conversation pushes the message screen onto the navigation stack -3. **Message Screen** – Shows the full chat interface with header, message list, and composer -4. **Back Navigation** – Users can return to the conversation list using the back button +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -*** - -## **Implementation** - -### **Step 1: Render the Conversation Component** - -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +--- - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - final target = conversation.conversationWith; +## What You're Building - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - ), - ); - }, - ), - ), - ); -} -``` - - +Two screens working together: -**Key Properties:** +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message screen** — header + messages + composer for the selected conversation -| Property | Type | Description | -| --- | --- | --- | -| `showBackButton` | bool | Shows/hides the back button in the app bar | -| `onItemTap` | Function | Callback when a conversation is tapped | -| `conversationWith` | User or Group | The target entity (user or group) for the conversation | +--- -*** +## Step 1 — Create the Conversations Screen -### **Full Example: main.dart** +The `CometChatConversations` widget displays all conversations. Tapping one navigates to the message screen. - - -```dart main.dart +```dart title="lib/conversations_page.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const ConversationsPage(); - }, - ); - } -} class ConversationsPage extends StatelessWidget { const ConversationsPage({super.key}); @@ -200,10 +55,8 @@ class ConversationsPage extends StatelessWidget { return Scaffold( body: SafeArea( child: CometChatConversations( - showBackButton: true, onItemTap: (conversation) { final target = conversation.conversationWith; - Navigator.push( context, MaterialPageRoute( @@ -220,60 +73,38 @@ class ConversationsPage extends StatelessWidget { } } ``` - - - -*** -### **Step 2: Render the Messages Component** +Key points: +- `onItemTap` fires when a conversation is tapped, passing the `Conversation` object. +- `conversationWith` returns either a `User` or `Group` — pass the correct one to the message screen. -To create a complete messaging view, include the following components in `messages_screen.dart`: +--- -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages +## Step 2 — Create the Messages Screen - - - +The message screen combines header, message list, and composer. - - -```dart messages_screen.dart +```dart title="lib/messages_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class MessagesScreen extends StatefulWidget { +class MessagesScreen extends StatelessWidget { final User? user; final Group? group; - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); - - @override - State createState() => _MessagesScreenState(); -} + const MessagesScreen({super.key, this.user, this.group}); -class _MessagesScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), + appBar: CometChatMessageHeader(user: user, group: group), body: SafeArea( child: Column( children: [ Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, + child: CometChatMessageList(user: user, group: group), ), + CometChatMessageComposer(user: user, group: group), ], ), ), @@ -281,175 +112,38 @@ class _MessagesScreenState extends State { } } ``` - - - -**Component Breakdown:** -| Component | Purpose | Key Features | -| --- | --- | --- | -| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | -| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | -| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | +| Component | Purpose | +| --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and call buttons | +| `CometChatMessageList` | Displays messages with real-time updates | +| `CometChatMessageComposer` | Input field for text, media, and attachments | -*** - -### **Step 3: Run the App** +--- -Use the following command to run the app on a connected device or emulator: +## Step 3 — Run the App ```bash flutter run ``` -This will launch the app and display the **Conversation List**. Tapping a conversation will navigate to the **Message View**. - -*** - -## **Customization Options** - -### **Conversation List Customization** - - - -```dart -CometChatConversations( - title: "My Chats", - showBackButton: false, - hideSearch: false, - onItemTap: (conversation) { - // Custom navigation logic - }, - onItemLongPress: (conversation) { - // Show options menu - }, - conversationsStyle: ConversationsStyle( - background: Colors.white, - titleStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), - ), -) -``` - - - -### **Message Screen Customization** - - - -```dart -CometChatMessageList( - user: user, - group: group, - hideMessageComposer: false, - hideMessageHeader: false, - messageListStyle: MessageListStyle( - background: Colors.grey[100], - ), -) -``` - - - -For complete customization options, see: -* [Conversations Customization](/ui-kit/flutter/conversations) -* [Message List Customization](/ui-kit/flutter/message-list) -* [Message Composer Customization](/ui-kit/flutter/message-composer) -* [Theming Guide](/ui-kit/flutter/theme-introduction) - -*** - -## **Common Use Cases** - - - - - - ```dart - CometChatConversations( - conversationsRequestBuilder: ConversationsRequestBuilder() - ..conversationType = CometChatConversationType.user // or .group - ..limit = 30, - ) - ``` - - - - - - - - ```dart - CometChatConversations( - onItemLongPress: (conversation) { - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text('Options'), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - title: Text('Delete Conversation'), - onTap: () { - // Delete conversation logic - }, - ), - ], - ), - ), - ); - }, - ) - ``` - - - - - - - - ```dart - Navigator.push( - context, - PageRouteBuilder( - pageBuilder: (context, animation, secondaryAnimation) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - transitionsBuilder: (context, animation, secondaryAnimation, child) { - return SlideTransition( - position: Tween( - begin: const Offset(1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - }, - ), - ); - ``` - - - - +You should see the conversation list. Tapping a conversation navigates to the message screen. -*** +--- -## **Next Steps** +## Next Steps - - Learn about all conversation list customization options + + Customize the conversation list - - Explore message list, header, and composer features + + Customize the message view - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - - Handle real-time events and user interactions + + Handle real-time events - -*** diff --git a/ui-kit/flutter/flutter-one-to-one-chat.mdx b/ui-kit/flutter/flutter-one-to-one-chat.mdx index 136095916..5b6d8c0ab 100644 --- a/ui-kit/flutter/flutter-one-to-one-chat.mdx +++ b/ui-kit/flutter/flutter-one-to-one-chat.mdx @@ -1,213 +1,57 @@ --- -title: "Building A One To One/Group Chat Experience" -sidebarTitle: "One To One/Group Chat" -description: "Create a focused direct messaging interface for one-to-one or group conversations using Flutter UI Kit" +title: "One-to-One / Group Chat" +sidebarTitle: "One-to-One / Group Chat" +description: "Build a focused one-to-one or group chat experience in Flutter with CometChat UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Fetch a user and show messages directly -Future fetchCometChatUser(String uid) async { - final completer = Completer(); - CometChat.getUser( - uid, - onSuccess: (user) => completer.complete(user), - onError: (error) => completer.completeError(error), - ); - return completer.future; -} - -// Show messages screen directly -FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } - return CircularProgressIndicator(); - }, -) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Single chat window — no conversation list | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | Support chat, embedded widgets, focused messaging | -// Messages screen -Scaffold( - appBar: CometChatMessageHeader(user: user, group: group), - body: Column( - children: [ - Expanded(child: CometChatMessageList(user: user, group: group)), - CometChatMessageComposer(user: user, group: group), - ], - ), -) -``` + -**Key Components:** -- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) -- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) -- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) - +This guide builds a single chat window — no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, deep links, or focused messaging. -The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -*** - -## **How It Works** - -This implementation bypasses the conversation list and opens directly into a chat: - -1. **Fetch User/Group** – Retrieve the target user or group using their UID/GUID -2. **Direct Navigation** – Launch directly into the message screen -3. **Focused Experience** – No conversation list, just the active chat -4. **Ideal for Context** – Perfect for support tickets, notifications, or deep links - -*** - -## **Use Cases** - -* **Customer Support** – Direct users to agent chat from help center -* **Dating Apps** – Open chat after a match -* **Notifications** – Deep link from push notification to specific chat -* **Onboarding** – Guide new users through a welcome chat -* **Contextual Messaging** – Start chat from user profile or product page +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -*** - -## **Implementation** - -### **Step 1: Render the Message View** +--- -The `CometChatMessageList` widget displays all messages for a specific user or group. Follow the steps below to render this component: +## What You're Building - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), - ), - ); -} -``` - - +Three components stacked vertically: -**Key Concepts:** +1. **Chat header** — displays recipient name, avatar, and call buttons +2. **Message list** — real-time chat history +3. **Message composer** — text input with media and emojis -| Concept | Description | -| --- | --- | -| `fetchCometChatUser()` | Async function to retrieve user by UID | -| `FutureBuilder` | Widget that builds based on async operation state | -| `MessagesScreen` | Custom widget containing message components | +--- -*** +## Step 1 — Create the Chat Screen -### **Full Example: main.dart** +The app fetches a user on mount and renders the message components. - - -```dart main.dart +```dart title="lib/chat_screen.dart" +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling -import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -import 'dart:async'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const MessagesPage(); - }, - ); - } -} - -class MessagesPage extends StatelessWidget { - const MessagesPage({super.key}); +class ChatScreen extends StatelessWidget { + const ChatScreen({super.key}); - Future fetchCometChatUser(String uid) async { + Future fetchUser(String uid) async { final completer = Completer(); CometChat.getUser( uid, @@ -219,123 +63,49 @@ class MessagesPage extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), - ), - ); - } -} -``` - - - -*** - -### **Step 2: Render the Messages Component** - -To create a complete messaging view, include the following components in `messages_screen.dart`: - -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages - - - - - - - -```dart messages_screen.dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -class MessagesScreen extends StatefulWidget { - final User? user; - final Group? group; - - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); - - @override - State createState() => _MessagesScreenState(); -} - -class _MessagesScreenState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), - body: SafeArea( - child: Column( - children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, + return FutureBuilder( + future: fetchUser("cometchat-uid-2"), // Replace with target UID + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + return Scaffold( + body: Center(child: Text('Error: ${snapshot.error}')), + ); + } + final user = snapshot.data!; + return Scaffold( + appBar: CometChatMessageHeader(user: user), + body: SafeArea( + child: Column( + children: [ + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], ), - ], - ), - ), + ), + ); + }, ); } } ``` - - - -**Component Breakdown:** - -| Component | Purpose | Key Features | -| --- | --- | --- | -| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | -| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | -| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | - -*** -### **Step 3: Run the App** +Key points: +- `CometChat.getUser(uid)` fetches the user object — you need a real user object, not a manually constructed one. +- Pass either `user` or `group` to the message components, never both. -Use the following command to run the app on a connected device or emulator: - -```bash -flutter run -``` - -This will launch the app, and you should see the one-to-one chat interface with the message header, list, and composer ready for use. - -*** - -## **Variations** +--- -### **For Group Chat** +## Switching to Group Chat -To open a group chat instead of a one-to-one chat, fetch a group instead of a user: +To load a group chat instead, use `CometChat.getGroup()`: - - ```dart -Future fetchCometChatGroup(String guid) async { +Future fetchGroup(String guid) async { final completer = Completer(); CometChat.getGroup( guid, @@ -345,356 +115,52 @@ Future fetchCometChatGroup(String guid) async { return completer.future; } -// In your widget +// Then in build(): FutureBuilder( - future: fetchCometChatGroup("your-group-guid"), + future: fetchGroup("your-group-guid"), builder: (context, snapshot) { if (snapshot.hasData) { - return MessagesScreen(group: snapshot.data!); - } - return CircularProgressIndicator(); - }, -) -``` - - - -### **From Route Parameters** - -Pass user/group ID through navigation: - - - -```dart -// Navigate with parameters -Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen(userId: "cometchat-uid-2"), - ), -); - -// ChatScreen widget -class ChatScreen extends StatelessWidget { - final String userId; - - const ChatScreen({Key? key, required this.userId}) : super(key: key); - - Future fetchUser() async { - final completer = Completer(); - CometChat.getUser( - userId, - onSuccess: (user) => completer.complete(user), - onError: (error) => completer.completeError(error), - ); - return completer.future; - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: fetchUser(), - builder: (context, snapshot) { - if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } - return Scaffold( - body: Center(child: CircularProgressIndicator()), - ); - }, - ); - } -} -``` - - - -### **From Deep Link** - -Handle deep links to open specific chats: - - - -```dart -// In your main app -MaterialApp( - onGenerateRoute: (settings) { - if (settings.name == '/chat') { - final args = settings.arguments as Map; - return MaterialPageRoute( - builder: (_) => ChatScreen( - userId: args['userId'], - groupId: args['groupId'], + final group = snapshot.data!; + return Scaffold( + appBar: CometChatMessageHeader(group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(group: group)), + CometChatMessageComposer(group: group), + ], ), ); } - return null; + return const CircularProgressIndicator(); }, ) - -// Navigate from deep link -Navigator.pushNamed( - context, - '/chat', - arguments: {'userId': 'cometchat-uid-2'}, -); -``` - - - -*** - -## **Customization Options** - -### **Hide Header or Composer** - - - -```dart -MessagesScreen( - user: user, - hideMessageHeader: true, // Hide the header - hideMessageComposer: false, // Show the composer -) ``` - - - -### **Custom Message Actions** - - -```dart -CometChatMessageList( - user: user, - onMessageTap: (message) { - // Handle message tap - }, - onMessageLongPress: (message) { - // Show options menu - }, -) -``` - - +--- -### **Styling** +## Step 2 — Run the App - - -```dart -CometChatMessageList( - user: user, - messageListStyle: MessageListStyle( - background: Colors.grey[100], - loadingIconTint: Colors.blue, - ), -) +```bash +flutter run ``` - - - -For complete customization options, see: -* [Message List Customization](/ui-kit/flutter/message-list) -* [Message Header Customization](/ui-kit/flutter/message-header) -* [Message Composer Customization](/ui-kit/flutter/message-composer) -* [Theming Guide](/ui-kit/flutter/theme-introduction) -*** +You should see the chat window load with the conversation for the UID you set. -## **Common Use Cases** - - - - - - ```dart - // From support ticket screen - ElevatedButton( - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen( - userId: ticket.assignedAgentId, - ), - ), - ); - }, - child: Text('Chat with Support'), - ) - ``` - - - - - - - - ```dart - // From user profile screen - IconButton( - icon: Icon(Icons.message), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen(userId: profile.userId), - ), - ); - }, - ) - ``` - - - - - - - - ```dart - // Handle notification tap - void handleNotificationTap(Map data) { - final userId = data['senderId']; - Navigator.pushNamed( - context, - '/chat', - arguments: {'userId': userId}, - ); - } - ``` - - - - - - - - ```dart - CometChatMessageComposer( - user: user, - text: "Hello! I need help with...", // Pre-filled text - ) - ``` - - - - - -*** - -## **Best Practices** - - - - Always handle errors when fetching users or groups: - - - - ```dart - FutureBuilder( - future: fetchCometChatUser(userId), - builder: (context, snapshot) { - if (snapshot.hasError) { - return Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.error, size: 48, color: Colors.red), - SizedBox(height: 16), - Text('Failed to load chat'), - ElevatedButton( - onPressed: () => setState(() {}), // Retry - child: Text('Retry'), - ), - ], - ), - ), - ); - } - // ... rest of builder - }, - ) - ``` - - - - - - Provide clear loading indicators: - - - - ```dart - if (snapshot.connectionState == ConnectionState.waiting) { - return Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - CircularProgressIndicator(), - SizedBox(height: 16), - Text('Loading chat...'), - ], - ), - ), - ); - } - ``` - - - - - - Cache fetched users to avoid repeated API calls: - - - - ```dart - class UserCache { - static final Map _cache = {}; - - static Future getUser(String uid) async { - if (_cache.containsKey(uid)) { - return _cache[uid]!; - } - - final completer = Completer(); - CometChat.getUser( - uid, - onSuccess: (user) { - _cache[uid] = user; - completer.complete(user); - }, - onError: (error) => completer.completeError(error), - ); - return completer.future; - } - } - ``` - - - - - -*** +--- -## **Next Steps** +## Next Steps - - Explore message list, header, and composer features + + Customize the message view - - Add a conversation list for multi-chat support + + Add a conversation list - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - - Handle real-time events and user interactions + + Handle real-time events - -*** diff --git a/ui-kit/flutter/flutter-tab-based-chat.mdx b/ui-kit/flutter/flutter-tab-based-chat.mdx index 5959a206b..ba02849dc 100644 --- a/ui-kit/flutter/flutter-tab-based-chat.mdx +++ b/ui-kit/flutter/flutter-tab-based-chat.mdx @@ -1,248 +1,53 @@ --- -title: "Building A Messaging UI With Tabs, Sidebar, And Message View" -sidebarTitle: "Tab Based Chat Experience" -description: "Create a multi-tab chat interface with conversations, calls, users, and groups using Flutter bottom navigation" +title: "Tab-Based Chat" +sidebarTitle: "Tab-Based Chat" +description: "Build a tab-based messaging UI with chats, calls, users, and groups in Flutter with CometChat UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -```dart -// Tab-based UI with bottom navigation -Scaffold( - body: PageView( - controller: _pageController, - children: [ - CometChatConversations(), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - ], - ), - bottomNavigationBar: BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: (index) { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - }, - items: [ - BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chat"), - BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), - BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), - BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), - ], - ), -) -``` + -**Key Components:** -- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) -- **Call Logs** → [CometChatCallLogs](/ui-kit/flutter/call-logs) -- **Users** → [CometChatUsers](/ui-kit/flutter/users) -- **Groups** → [CometChatGroups](/ui-kit/flutter/groups) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatConversations`, `CometChatCallLogs`, `CometChatUsers`, `CometChatGroups`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Bottom navigation tabs (Chats, Calls, Users, Groups) + message view | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | Full-featured messaging app with multiple sections | -This guide walks you through creating a **tab-based messaging UI** using **Flutter** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. + -*** +This guide builds a tabbed messaging UI — Chats, Calls, Users, and Groups tabs with bottom navigation. Good for full-featured apps that need more than just conversations. -## **User Interface Preview** +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -This layout consists of: - -1. **Bottom Navigation Bar** – Tabs for switching between Chats, Calls, Users, and Groups -2. **Page View** – Displays the selected tab's content -3. **Conversation List** – Shows recent conversations with active users and groups -4. **Message View** – Opens when a conversation is tapped - -*** - -## **How It Works** - -This implementation uses Flutter's `BottomNavigationBar` and `PageView` to create a tabbed interface: - -1. **Bottom Navigation** – Provides quick access to different sections -2. **Page View** – Swipeable pages for each tab -3. **State Management** – Syncs selected tab with page view -4. **Navigation** – Tapping a conversation opens the message screen - -*** +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -## **Use Cases** - -* **All-in-One Chat Apps** – Complete messaging solution with multiple features -* **Business Messengers** – Professional communication with organized sections -* **Social Platforms** – Community chat with user discovery -* **Support Apps** – Help desk with call logs and user management -* **Team Collaboration** – Internal communication with group management - -*** +--- -## **Implementation** +## What You're Building -### **Step 1: Render the Tab Component** +Three sections working together: -The tab-based UI uses `BottomNavigationBar` for navigation and `PageView` for content display: +1. **Bottom navigation** — switches between Chats, Calls, Users, and Groups +2. **Page view** — renders the list for the active tab +3. **Message view** — header + messages + composer for the selected item - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: PageView( - controller: _pageController, - onPageChanged: (index) { - setState(() { - _selectedIndex = index; - }); - }, - children: [ - CometChatConversations( - showBackButton: false, - onItemTap: (conversation) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen( - user: conversation.conversationWith is User - ? conversation.conversationWith as User - : null, - group: conversation.conversationWith is Group - ? conversation.conversationWith as Group - : null, - ), - ), - ); - }, - ), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - ], - ), - bottomNavigationBar: BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: _onItemTapped, - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.chat), - label: "Chat", - ), - BottomNavigationBarItem( - icon: Icon(Icons.call), - label: "Calls", - ), - BottomNavigationBarItem( - icon: Icon(Icons.person), - label: "Users", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group), - label: "Groups", - ), - ], - ), - ); -} -``` - - - -**Key Components:** - -| Component | Purpose | Key Features | -| --- | --- | --- | -| `PageView` | Container for swipeable pages | Smooth transitions, gesture support | -| `BottomNavigationBar` | Tab navigation | Icon + label, active state | -| `PageController` | Controls page view | Jump to page, animate transitions | +--- -*** +## Step 1 — Create the Tabs Screen -### **Full Example: main.dart** +The tabs screen uses `BottomNavigationBar` and `PageView` to create a tabbed interface. - - -```dart main.dart +```dart title="lib/tabs_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const TabsScreen(); - }, - ); - } -} class TabsScreen extends StatefulWidget { const TabsScreen({super.key}); @@ -256,9 +61,7 @@ class _TabsScreenState extends State { final PageController _pageController = PageController(); void _onItemTapped(int index) { - setState(() { - _selectedIndex = index; - }); + setState(() => _selectedIndex = index); _pageController.jumpToPage(index); } @@ -273,25 +76,17 @@ class _TabsScreenState extends State { return Scaffold( body: PageView( controller: _pageController, - onPageChanged: (index) { - setState(() { - _selectedIndex = index; - }); - }, + onPageChanged: (index) => setState(() => _selectedIndex = index), children: [ CometChatConversations( - showBackButton: false, onItemTap: (conversation) { + final target = conversation.conversationWith; Navigator.push( context, MaterialPageRoute( - builder: (context) => MessagesScreen( - user: conversation.conversationWith is User - ? conversation.conversationWith as User - : null, - group: conversation.conversationWith is Group - ? conversation.conversationWith as Group - : null, + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, ), ), ); @@ -299,24 +94,16 @@ class _TabsScreenState extends State { ), CometChatCallLogs(), CometChatUsers( - onItemTap: (user) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen(user: user), - ), - ); - }, + onItemTap: (user) => Navigator.push( + context, + MaterialPageRoute(builder: (_) => MessagesScreen(user: user)), + ), ), CometChatGroups( - onItemTap: (group) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen(group: group), - ), - ); - }, + onItemTap: (group) => Navigator.push( + context, + MaterialPageRoute(builder: (_) => MessagesScreen(group: group)), + ), ), ], ), @@ -327,82 +114,47 @@ class _TabsScreenState extends State { selectedItemColor: Colors.deepPurple, unselectedItemColor: Colors.grey, items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.chat), - label: "Chat", - ), - BottomNavigationBarItem( - icon: Icon(Icons.call), - label: "Calls", - ), - BottomNavigationBarItem( - icon: Icon(Icons.person), - label: "Users", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group), - label: "Groups", - ), + BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chats"), + BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), + BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), + BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), ], ), ); } } ``` - - - -*** -### **Step 2: Render the Messages Component** +Key points: +- `PageView` enables swipeable pages for each tab. +- `BottomNavigationBar` provides quick access to different sections. +- Each list component navigates to `MessagesScreen` on item tap. -To create a complete messaging view, include the following components in `messages_screen.dart`: +--- -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages +## Step 2 — Create the Messages Screen - - - +Same as the [Conversation + Message](/ui-kit/flutter/flutter-conversation) guide: - - -```dart messages_screen.dart +```dart title="lib/messages_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class MessagesScreen extends StatefulWidget { +class MessagesScreen extends StatelessWidget { final User? user; final Group? group; - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); + const MessagesScreen({super.key, this.user, this.group}); - @override - State createState() => _MessagesScreenState(); -} - -class _MessagesScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), + appBar: CometChatMessageHeader(user: user, group: group), body: SafeArea( child: Column( children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, - ), + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), ], ), ), @@ -410,401 +162,43 @@ class _MessagesScreenState extends State { } } ``` - - - -*** -### **Step 3: Run the App** +--- -Use the following command to run the app on a connected device or emulator: +## Step 3 — Run the App ```bash flutter run ``` -This will launch the app, and you should see the tab-based chat experience with the sidebar and message view. You can navigate between different tabs (Chats, Calls, Users, and Groups) and interact with the messaging features seamlessly. - -*** - -## **Tab Descriptions** - -### **1. Chat Tab** - -Displays recent conversations with users and groups: - -* **CometChatConversations** – Shows conversation list -* **Real-time updates** – New messages appear instantly -* **Unread counts** – Badge showing unread message count -* **Last message preview** – Shows snippet of last message -* **Tap to open** – Navigate to full message view +You should see the tab bar at the bottom. Switch between Chats, Calls, Users, and Groups — tapping any item opens the message view. -### **2. Calls Tab** - -Shows call history and logs: - -* **CometChatCallLogs** – Displays all call records -* **Call types** – Audio and video calls -* **Call status** – Missed, incoming, outgoing -* **Tap to call back** – Initiate new call from history -* **Call duration** – Shows length of completed calls - -### **3. Users Tab** - -Browse and search all users: - -* **CometChatUsers** – Lists all available users -* **Search functionality** – Find users by name -* **User status** – Online/offline indicators -* **Tap to chat** – Start conversation with any user -* **User avatars** – Profile pictures - -### **4. Groups Tab** - -Manage and join groups: - -* **CometChatGroups** – Shows all groups -* **Group types** – Public, private, password-protected -* **Member count** – Number of participants -* **Join groups** – Request to join or join directly -* **Tap to chat** – Open group conversation +--- -*** +## Tab Descriptions -## **Customization Options** +| Tab | Component | Purpose | +| --- | --- | --- | +| Chats | `CometChatConversations` | Recent conversations with unread counts | +| Calls | `CometChatCallLogs` | Call history (audio/video) | +| Users | `CometChatUsers` | Browse and search all users | +| Groups | `CometChatGroups` | Browse and join groups | -### **Custom Tab Icons** +--- - - -```dart -BottomNavigationBar( - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.forum), - activeIcon: Icon(Icons.forum, size: 28), - label: "Chats", - ), - BottomNavigationBarItem( - icon: Icon(Icons.phone), - activeIcon: Icon(Icons.phone, size: 28), - label: "Calls", - ), - // ... more tabs - ], -) -``` - - - -### **Custom Tab Colors** - - - -```dart -BottomNavigationBar( - selectedItemColor: Colors.blue, - unselectedItemColor: Colors.grey, - backgroundColor: Colors.white, - elevation: 8, - // ... items -) -``` - - - -### **Disable Swipe Between Tabs** - - - -```dart -PageView( - controller: _pageController, - physics: NeverScrollableScrollPhysics(), // Disable swipe - children: [ - // ... pages - ], -) -``` - - - -### **Add More Tabs** - - - -```dart -// Add a Settings tab -children: [ - CometChatConversations(), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - SettingsScreen(), // New tab -], - -items: [ - // ... existing items - BottomNavigationBarItem( - icon: Icon(Icons.settings), - label: "Settings", - ), -], -``` - - - -### **Custom Tab Styling** - - - -```dart -CometChatConversations( - title: "My Chats", - conversationsStyle: ConversationsStyle( - background: Colors.white, - titleStyle: TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - ), - ), -) -``` - - - -For complete customization options, see: -* [Conversations Customization](/ui-kit/flutter/conversations) -* [Call Logs Customization](/ui-kit/flutter/call-logs) -* [Users Customization](/ui-kit/flutter/users) -* [Groups Customization](/ui-kit/flutter/groups) -* [Theming Guide](/ui-kit/flutter/theme-introduction) - -*** - -## **Common Use Cases** - - - - - - ```dart - BottomNavigationBarItem( - icon: Stack( - children: [ - Icon(Icons.chat), - if (unreadCount > 0) - Positioned( - right: 0, - top: 0, - child: Container( - padding: EdgeInsets.all(2), - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(10), - ), - constraints: BoxConstraints( - minWidth: 16, - minHeight: 16, - ), - child: Text( - '$unreadCount', - style: TextStyle( - color: Colors.white, - fontSize: 10, - ), - textAlign: TextAlign.center, - ), - ), - ), - ], - ), - label: "Chat", - ) - ``` - - - - - - - - ```dart - // Save selected tab to shared preferences - void _onItemTapped(int index) async { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - - final prefs = await SharedPreferences.getInstance(); - await prefs.setInt('selected_tab', index); - } - - // Load selected tab on init - @override - void initState() { - super.initState(); - _loadSelectedTab(); - } - - Future _loadSelectedTab() async { - final prefs = await SharedPreferences.getInstance(); - final savedIndex = prefs.getInt('selected_tab') ?? 0; - setState(() => _selectedIndex = savedIndex); - _pageController.jumpToPage(savedIndex); - } - ``` - - - - - - - - ```dart - void _onItemTapped(int index) { - setState(() => _selectedIndex = index); - _pageController.animateToPage( - index, - duration: Duration(milliseconds: 300), - curve: Curves.easeInOut, - ); - } - ``` - - - - - - - - ```dart - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async { - if (_selectedIndex != 0) { - // Go back to first tab instead of exiting - _onItemTapped(0); - return false; - } - return true; // Allow exit - }, - child: Scaffold( - // ... rest of widget - ), - ); - } - ``` - - - - - -*** - -## **Best Practices** - - - - Always dispose of controllers to prevent memory leaks: - - - - ```dart - @override - void dispose() { - _pageController.dispose(); - super.dispose(); - } - ``` - - - - - - For 4+ tabs, use fixed type to prevent shifting: - - - - ```dart - BottomNavigationBar( - type: BottomNavigationBarType.fixed, // Prevents label shifting - // ... rest of properties - ) - ``` - - - - - - Load tab content only when needed: - - - - ```dart - PageView( - controller: _pageController, - children: [ - _selectedIndex == 0 ? CometChatConversations() : SizedBox(), - _selectedIndex == 1 ? CometChatCallLogs() : SizedBox(), - _selectedIndex == 2 ? CometChatUsers() : SizedBox(), - _selectedIndex == 3 ? CometChatGroups() : SizedBox(), - ], - ) - ``` - - - - - - Refresh tab content when switching: - - - - ```dart - void _onItemTapped(int index) { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - - // Refresh current tab - _refreshTab(index); - } - - void _refreshTab(int index) { - // Implement refresh logic for each tab - switch (index) { - case 0: - // Refresh conversations - break; - case 1: - // Refresh call logs - break; - // ... etc - } - } - ``` - - - - - -*** - -## **Next Steps** +## Next Steps - Customize the conversation list appearance and behavior + Customize the conversation list - Configure call history and calling features + Configure call history - Manage user lists and group memberships + Manage user and group lists - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - -*** diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index ac00ff131..df8966cce 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -1,275 +1,119 @@ --- -title: "Getting Started With CometChat Flutter UI Kit" +title: "Getting Started" sidebarTitle: "Getting Started" -description: "Install and configure CometChat Flutter UI Kit with step-by-step setup, initialization, and authentication guide" +description: "Add CometChat to a Flutter app in 5 steps: create project, install, init, login, render." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Setup Reference** + -```bash -# Install -flutter pub add cometchat_chat_uikit -flutter pub add cometchat_calls_uikit # Optional: for calling - -# Initialize (run once at app start) -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..authKey = "YOUR_AUTH_KEY" - ..subscriptionType = CometChatSubscriptionType.allUsers - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension() -).build(); -await CometChatUIKit.init(uiKitSettings: uiKitSettings); - -# Login (after init) -await CometChatUIKit.login("cometchat-uid-1"); -``` - -**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) -**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Init | `CometChatUIKit.init(uiKitSettings)` — must resolve before `login()` | +| Login | `CometChatUIKit.login("UID")` — must resolve before rendering widgets | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Install `cometchat_calls_uikit` to enable | +| Platforms | iOS 13.0+, Android API 24+ (with calling) | -**Integration Paths:** -- **Conversation List + Message** → [flutter-conversation](/ui-kit/flutter/flutter-conversation) -- **One-to-One Chat** → [flutter-one-to-one-chat](/ui-kit/flutter/flutter-one-to-one-chat) -- **Tab-Based Chat** → [flutter-tab-based-chat](/ui-kit/flutter/flutter-tab-based-chat) - + -The **CometChat UI Kit for Flutter** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI widgets**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. - -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat Flutter UI Kit. +This guide walks you through adding CometChat to a Flutter app. By the end you'll have a working chat UI. - + -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for Flutter**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - - - -To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: - -1. **App ID** -2. **Auth Key** -3. **Region** - -Ensure you have these details ready before proceeding with the installation and configuration. - - - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. - -### **Step 1: Register on CometChat** - -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. - -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** - -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to the **QuickStart** or **API & Auth Keys** section. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** - - - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **iOS, Android, and web**. - - - -### **Step 3: Set Up Your Development Environment** +--- -Ensure your system meets the following **prerequisites** before proceeding with integration. +## Prerequisites -**System Requirements:** +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): -* **Flutter** installed on your system (Flutter 3.0 or higher recommended) -* **Android Studio** or **VS Code** with configured Flutter/Dart plugins -* **Xcode & CocoaPods** for iOS development -* An **iOS device or simulator** with iOS 13.0 or above -* An **Android device or emulator** with Android version 5.0 (API level 21) or above +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | -*** +You also need Flutter 3.0+ installed with Android Studio or VS Code. -## **Getting Started** + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use `loginWithAuthToken()`. Never ship Auth Keys in client code. + -### **Step 1: Create Flutter Application Project** +--- -To get started, create a new Flutter application project: +## Step 1 — Create a Flutter Project ```bash flutter create my_chat_app cd my_chat_app ``` -*** - -### **Step 2: Add Dependency** - -**1. Update Pubspec** - -To use this UI Kit in your Flutter project, you'll need to add the following dependency to the dependencies section of your `pubspec.yaml` file: +--- -```yaml pubspec.yaml -dependencies: - flutter: - sdk: flutter - - cometchat_chat_uikit: ^5.2.10 - cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling -``` +## Step 2 — Install the UI Kit -**Final `pubspec.yaml` Example:** +Add to your `pubspec.yaml`: ```yaml pubspec.yaml -name: my_chat_app -description: "A Flutter chat application using CometChat UI Kit" - -publish_to: 'none' - -version: 1.0.0+1 - -environment: - sdk: '>=3.8.0 <4.0.0' - dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.10 - cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling - cupertino_icons: ^1.0.8 - -dev_dependencies: - flutter_test: - sdk: flutter - - flutter_lints: ^4.0.0 - -flutter: - uses-material-design: true + cometchat_calls_uikit: ^5.0.12 # Optional: for voice/video calling ``` -After updating `pubspec.yaml`, run: +Then run: ```bash flutter pub get ``` -*** - -**2. Android App Setup** - -To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**. - -Update the `minSdkVersion` in your Android project configuration, located at `android/app/build.gradle`: +**Android Setup** — Update `android/app/build.gradle`: ```gradle build.gradle android { defaultConfig { - minSdk = 24 - // Other configurations... + minSdk = 24 // Required for calling } } ``` -*** - -**3. Update iOS Podfile** - -In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: +**iOS Setup** — Update `ios/Podfile`: ```ruby Podfile platform :ios, '13.0' ``` -After updating, run: +Then run: ```bash -cd ios -pod install -cd .. -``` - -*** - -**4. Import CometChat UIKit** - -In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your `main.dart` file: - - - -```dart main.dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling +cd ios && pod install && cd .. ``` - - - -*** - -### **Step 3: Initialize UI Kit** - -Before using any features from the CometChat UI Kit, initialize it with your app credentials. - - - -You must call `CometChatUIKit.init()` before rendering any UI Kit widgets or calling any SDK methods. Initialization must complete before login. - - -**1. Import & Configure UIKit Settings** +--- -You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. +## Step 3 — Initialize CometChat -**Example Configuration File:** +Create a constants file and initialize the UI Kit before anything else. - - -```dart cometchat_config.dart +```dart title="lib/cometchat_config.dart" class CometChatConfig { static const String appId = "APP_ID"; // Replace with your App ID - static const String region = "REGION"; // Replace with your App Region - static const String authKey = "AUTH_KEY"; // Replace with your Auth Key + static const String region = "REGION"; // Replace with your Region + static const String authKey = "AUTH_KEY"; // Replace with your Auth Key (dev only) } ``` - - -**Initialization Code:** - - - -```dart main.dart +```dart title="lib/main.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional import 'cometchat_config.dart'; -void main() { - runApp(const MyApp()); -} +void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @@ -277,334 +121,169 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), + title: 'CometChat Demo', + home: const InitializerScreen(), ); } } -class Home extends StatelessWidget { - const Home({super.key}); +class InitializerScreen extends StatelessWidget { + const InitializerScreen({super.key}); - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true + Future _initCometChat() async { + final settings = (UIKitSettingsBuilder() ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if using Audio/Video Calling + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Optional + ).build(); - await CometChatUIKit.init( - uiKitSettings: settings.build(), - onSuccess: (successMessage) { - debugPrint('✅ CometChat Initialized'); - }, - onError: (error) { - debugPrint('❌ CometChat Initialization error: $error'); - }, - ); + await CometChatUIKit.init(uiKitSettings: settings); } @override Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { + return FutureBuilder( + future: _initCometChat(), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), + body: Center(child: CircularProgressIndicator()), ); } - if (snap.hasError) { + if (snapshot.hasError) { return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), + body: Center(child: Text('Init failed: ${snapshot.error}')), ); } - return const LoginScreen(); // Navigate to your login screen + return const LoginScreen(); }, ); } } ``` - - - - - -Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding sensitive information. - - - -**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. - +`init()` must resolve before you call `login()`. If you call `login()` before init completes, it will fail silently. -*** +--- + +## Step 4 — Login -### **Step 4: Login to UI Kit** +After init resolves, log the user in. For development, use one of the pre-created test UIDs: -Once the UI Kit is initialized, authenticate your user using the `login()` method. You'll receive a `User` object upon success. +`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5` - - -```dart main.dart +```dart CometChatUIKit.login( - "cometchat-uid-1", // Replace with a valid UID + "cometchat-uid-1", onSuccess: (user) { - debugPrint('✅ CometChat LoggedIn success: ${user.name}'); - // Navigate to your chat screen + debugPrint('Login successful: ${user.name}'); + // Navigate to chat screen }, onError: (error) { - debugPrint('❌ CometChat LoggedIn error: $error'); + debugPrint('Login failed: $error'); }, ); ``` - - - -**Test Users:** - -You can test using any of the following pre-generated users: - -* `cometchat-uid-1` -* `cometchat-uid-2` -* `cometchat-uid-3` -* `cometchat-uid-4` -* `cometchat-uid-5` - - - -For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). - - - -**Example: Initialization and Login Combined** - - - -```dart main.dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension(); - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const ConversationsPage(); // Your main chat screen - }, - ); - } -} -``` - - +Key points: +- `getLoggedInUser()` checks for an existing session so you don't re-login unnecessarily. +- Widgets must not render until login resolves — use a state flag to gate rendering. - -Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. - +For production, use `loginWithAuthToken()` instead of Auth Key. Generate tokens server-side via the REST API. -*** - -### **Step 5: Choose a Chat Experience** - -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: +--- -*** +## Step 5 — Choose a Chat Experience -### **1️⃣ Conversation List + Message View** +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. -**Best for:** Flutter apps that need a **smooth, stack-based navigation** between conversations and messages. +### Conversation List + Message View -**Highlights:** +Two-panel layout — conversation list with navigation to messages. Think WhatsApp or Telegram. -* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation -* **One-to-One & Group Chats** – Built-in support for private and group conversations -* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events -* **State Persistence** – Session-aware updates across screens and app restarts -* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes -* **Extremely Customizable** – Modify styles, themes, and components easily +- Stack-based navigation with `Navigator.push()` +- Switch between one-to-one and group conversations +- Real-time updates and message sync across sessions -**Use When:** - -* You want a **clean navigation experience** for multiple chat sessions -* Your Flutter app supports **both direct and group messaging** -* You prefer a **stack-based routing approach** using `Navigator` + + Step-by-step guide to build this layout + -[Integrate Conversation List + Message View](./flutter-conversation) - -*** - -### **2️⃣ One-to-One / Group Chat** +--- -**Best for:** When a user lands **directly into a chat screen**, bypassing the conversation list. +### One-to-One / Group Chat -**Highlights:** +Single chat window — no conversation list. Good for support chat, embedded widgets, or focused messaging. -* **Single Screen Chat** – Use `CometChatMessageList` widget with preselected user/group -* **No Conversation List** – Start with just the message screen -* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication -* **Simplified Routing** – Pass user/group as route argument -* **Real-Time Communication** – Auto-updates messages and statuses +- Dedicated chat window for one-on-one or group messaging +- No conversation list — users go directly into the chat +- Ideal for support chat or contextual messaging -**Use When:** - -* Your chat starts **from a specific user or group ID** -* You want a **clean, focused chat interface** -* Use case involves **support, onboarding, or one-time messages** - -[Integrate One-to-One / Group Chat](./flutter-one-to-one-chat) + + Step-by-step guide to build this layout + -*** - -### **3️⃣ Tab-Based Messaging UI (All-in-One)** +--- -**Best for:** Flutter apps needing a **multi-tab experience** to access Chat, Users, Calls, and Settings. +### Tab-Based Chat -**Highlights:** +Tabbed navigation — Chat, Call Logs, Users, Groups in separate tabs. Good for full-featured apps. -* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features -* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets -* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices -* **Scalable** – Add new tabs like Profile, Notifications, or Help later -* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate +- `BottomNavigationBar` with independent screens +- Unified experience for conversations, call history, and contacts +- Scales well for adding future features -**Use When:** - -* You need a **full-featured chat solution** in one UI -* Your users require **structured navigation** between modules -* Use cases like **support apps, business messengers, or social platforms** - -[Integrate Tab-Based Chat](./flutter-tab-based-chat) - -*** + + Step-by-step guide to build this layout + -## **Build Your Own Chat Experience** - -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app's design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** +--- -* Apps that require **a fully customized chat experience** -* Developers who want to **extend functionalities and modify UI components** -* Businesses integrating chat seamlessly into **existing platforms** +## Build Your Own Chat Experience -**Key Areas to Explore:** +Need full control over the UI? Use individual widgets, customize themes, and wire up your own layouts. -* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding -* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience +- [Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) — Working reference app to compare against +- [Components](/ui-kit/flutter/components-overview) — All prebuilt UI widgets with props and customization options +- [Core Features](/ui-kit/flutter/core-features) — Messaging, real-time updates, and other capabilities +- [Theming](/ui-kit/flutter/theme-introduction) — Colors, fonts, dark mode, and custom styling +- [Build Your Own UI](/sdk/flutter/overview) — Skip the UI Kit entirely and build on the raw SDK -*** +--- -## **Next Steps** +## Next Steps - - Two-panel layout with conversation list and message view + + Browse all prebuilt UI widgets - - Direct messaging interface for focused conversations + + Customize colors, fonts, and styles - - Multi-tab experience with chats, calls, users, and groups + + Chat features included out of the box - - Adjust colors, fonts, and styles to match your brand + + Init, login, and other SDK methods - -*** diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index 84839787b..e1391ba86 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -1,219 +1,77 @@ --- -title: "CometChat UI Kit For Flutter" +title: "Flutter UI Kit" sidebarTitle: "Overview" -description: "Prebuilt Flutter widgets for chat, calling, and messaging with modular, customizable components for iOS and Android" +description: "Prebuilt Flutter widgets for chat, voice, and video calling. Works on iOS and Android." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Install -flutter pub add cometchat_chat_uikit +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` v5.2.x | +| Calling | Optional — `cometchat_calls_uikit` | +| Platforms | iOS 13.0+, Android API 21+ | +| Flutter | 3.0+ recommended | +| Localization | Built-in support | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | -// Initialize (run once at app start) -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..subscriptionType = CometChatSubscriptionType.allUsers -).build(); -CometChatUIKit.init(uiKitSettings: uiKitSettings); + -// Login -CometChatUIKit.login("UID"); - -// Show conversations -CometChatConversations() - -// Show messages -CometChatMessageList(user: user) // or group: group -``` - -**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) -**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys - - -The **CometChat UI Kit** for Flutter is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI widgets** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. - -*** - -## **Why Choose CometChat UI Kit?** - -* **Rapid Integration** – Prebuilt UI widgets for faster deployment. -* **Customizable & Flexible** – Modify the UI to align with your brand's identity. -* **Cross-Platform Compatibility** – Works seamlessly across iOS and Android platforms. -* **Scalable & Reliable** – Built on CometChat's **robust chat infrastructure** for enterprise-grade performance. - -*** - -## **User Interface Preview** +The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding chat, voice, and video calling to any Flutter app. Each widget handles its own data fetching, real-time listeners, and state — you just drop them into your layout. -*** - -## **Integration** - -### **UI Components (Assemble It Yourself)** +--- -A collection of individual widgets—like conversation lists, message lists, message composer, etc.—each with built-in chat logic so you can customize every element. +## Get Started - + -**How It Works** - -* Import the widgets you need from our UI Kits. -* Arrange them in your desired layout, applying styling or customization as needed. -* You don't need to rewrite the SDK calls yourself—each widget already integrates with CometChat logic. - -**Why It's Great** - -* **Flexible Design** – You control the final UI arrangement. -* **No Extra Overhead** – Implement only the features you need. -* **Modular** – Use exactly what you want, when you want. - -[**Go to Flutter UI Docs**](/ui-kit/flutter/getting-started) - -*** - -## **Before Getting Started** - -Before you begin, it's essential to grasp the fundamental concepts and features offered by CometChat's APIs, SDK, and UI Kit. You can find detailed information in the [Key Concepts](/fundamentals/key-concepts) documentation. - -You can start building a modern messaging experience in your app by installing the new UI Kit. This developer kit is an add-on feature to CometChat Flutter SDK so installing it will also install the core Chat SDK. - -To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) guide. - -*** - -## **Key Features** - -### **Comprehensive Widget Library** - -The UI Kit includes a complete set of widgets for building chat experiences: - -* **CometChatConversations** – Display recent conversations with users and groups -* **CometChatMessageList** – Full-featured messaging interface with real-time updates -* **CometChatMessageComposer** – Input field for sending text, media, and attachments -* **CometChatMessageHeader** – Conversation header with user/group info and actions -* **CometChatUsers** – Browse and search users -* **CometChatGroups** – Manage and join groups -* **CometChatGroupMembers** – View and manage group participants -* **Calling Components** – Voice and video calling widgets - -### **Built-in Chat Logic** - -Each widget comes with integrated CometChat SDK functionality: - -* Real-time message delivery and updates -* Typing indicators and read receipts -* User presence and status -* Message reactions and threading -* File and media sharing -* Push notifications support - -### **Extensive Customization** - -Tailor the UI to match your brand: - -* **Theming** – Customize colors, fonts, and spacing -* **Styling** – Override default styles for any component -* **Templates** – Create custom message bubble layouts -* **Formatters** – Add mentions, shortcuts, and URL previews -* **Configurations** – Control feature availability and behavior - -*** - -## **Architecture** - -The CometChat UI Kit for Flutter is built on top of the [CometChat Flutter SDK](/sdk/flutter/overview) and follows a modular architecture: - -``` -Your Flutter App - ↓ -CometChat UI Kit (Widgets) - ↓ -CometChat Flutter SDK (Core Chat Logic) - ↓ -CometChat Platform -``` - -This layered approach means: - -* **Widgets handle UI** – Rendering, user interactions, animations -* **SDK handles logic** – Message delivery, real-time events, data management -* **Platform handles infrastructure** – Scalability, reliability, security - -*** - -## **Supported Platforms** - -The Flutter UI Kit works seamlessly across: - -* **iOS** – iPhone and iPad (iOS 13.0+) -* **Android** – Phones and tablets (API level 21+) + + Install, initialize, and build your first chat screen + -*** +--- -## **Next Steps** +## Explore - - Install the UI Kit and build your first chat screen + + Browse all prebuilt UI widgets - - Understand CometChat's core concepts and terminology + + Chat, calling, AI, and extensions - - Explore all available widgets and their capabilities + + Colors, fonts, dark mode, and custom styling - - Customize colors, fonts, and styles to match your brand + + Understand CometChat's core concepts -*** - -## **Helpful Resources** - -Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. - - - - -Fully functional sample applications to accelerate your development. - -View on GitHub - - - - - -Access the complete UI Kit source code on GitHub. - -View on GitHub - - - - - -UI design resources for customization and prototyping. +--- -View on Figma +## Resources - + + + Working reference app + + + Full UI Kit source on GitHub + + + Design resources and prototyping + + + Open a support ticket + + + Developer community forum + - -*** - -## **Need Help?** - -If you need assistance, check out: - -* 💬 [Developer Community](http://community.cometchat.com/) -* ❓ [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) From edebad31e0aaf37d003ab008ce43ab745d67d39a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 13:39:08 +0530 Subject: [PATCH 15/32] Update color-resources.mdx --- ui-kit/flutter/color-resources.mdx | 267 ++++++++++++++++++----------- 1 file changed, 169 insertions(+), 98 deletions(-) diff --git a/ui-kit/flutter/color-resources.mdx b/ui-kit/flutter/color-resources.mdx index 9d9a8550d..5ac72fe51 100644 --- a/ui-kit/flutter/color-resources.mdx +++ b/ui-kit/flutter/color-resources.mdx @@ -1,140 +1,211 @@ --- title: "Color Resources" +sidebarTitle: "Color Resources" +description: "Complete reference for CometChatColorPalette tokens in Flutter UI Kit." --- -## Introducing CometChatColorPalette: + -### Your Theme Customization Toolbox! +| Field | Value | +| --- | --- | +| Class | `CometChatColorPalette` | +| Usage | `ThemeData(extensions: [CometChatColorPalette(...)])` | +| Categories | Primary, Neutral, Alert, Text, Icon, Border, Background, Button, Shimmer | +| Light mode | Use light color values | +| Dark mode | Use dark color values | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/theme/colors) | -Ever wanted to personalize your app's entire look and feel with just a few lines of code? Introducing the `CometChatColorPalette` class! This powerful tool, designed for the V5 CometChat Flutter UI Kit, allows you to effortlessly change the colors used throughout your app. + -Think of it like a giant paintbrush for your app's theme. You can set the primary color, neutral tones, and even specific colors for alerts, backgrounds, text, borders, and icons. +`CometChatColorPalette` controls all colors in the UI Kit. Apply it via `ThemeData.extensions`. -Here's a breakdown of what you can customize: - -* **Primary Colors:** Define the main color scheme of your app. -* **Neutral Colors:** Create a balanced base for your app's visuals. -* **Alert Colors:** Set unique colors for informative, warning, success, and error messages. -* **Background Colors:** Choose the background shades for different areas of your app. -* **Text Colors:** Control the color of text elements for optimal readability and aesthetics. -* **Border Colors:** Set the color of borders for elements like buttons and cards. -* **Icon Colors:** Customize the colors of app icons for a cohesive look. -* **Button Colors:** Choose the background and text color of buttons for clear action prompts. -* **Shimmer Colors:** Define the colors used in loading animations for user feedback. +--- -By simply creating a `CometChatColorPalette` object and assigning it to the `extensions` property of your `ThemeData`, you can instantly transform your app's appearance. +## Complete Token Reference + +### Primary Colors + +| Token | Description | +| --- | --- | +| `primary` | Main accent color | +| `extendedPrimary50` | 96% lighter (light) / 80% darker (dark) | +| `extendedPrimary100` | 88% lighter (light) / 72% darker (dark) | +| `extendedPrimary200` | 77% lighter (light) / 64% darker (dark) | +| `extendedPrimary300` | 66% lighter (light) / 56% darker (dark) | +| `extendedPrimary400` | 55% lighter (light) / 48% darker (dark) | +| `extendedPrimary500` | 44% lighter (light) / 40% darker (dark) | +| `extendedPrimary600` | 33% lighter (light) / 32% darker (dark) | +| `extendedPrimary700` | 22% lighter (light) / 24% darker (dark) | +| `extendedPrimary800` | 11% lighter (light) / 16% darker (dark) | +| `extendedPrimary900` | 11% lighter (light) / 8% darker (dark) | + +### Neutral Colors + +| Token | Description | +| --- | --- | +| `neutral50` - `neutral900` | Surface and background shades (50, 100, 200, 300, 400, 500, 600, 700, 800, 900) | + +### Alert Colors + +| Token | Description | +| --- | --- | +| `info` | Information indicator | +| `warning` | Warning indicator | +| `error` | Error indicator | +| `success` | Success indicator | +| `error100` | Light/dark mode error shade | + +### Text Colors + +| Token | Description | +| --- | --- | +| `textPrimary` | Primary text | +| `textSecondary` | Secondary text | +| `textTertiary` | Tertiary text | +| `textDisabled` | Disabled text | +| `textWhite` | White text | +| `textHighlight` | Highlighted text | + +### Icon Colors + +| Token | Description | +| --- | --- | +| `iconPrimary` | Primary icon | +| `iconSecondary` | Secondary icon | +| `iconTertiary` | Tertiary icon | +| `iconWhite` | White icon | +| `iconHighlight` | Highlighted icon | + +### Border Colors + +| Token | Description | +| --- | --- | +| `borderLight` | Light border | +| `borderDefault` | Default border | +| `borderDark` | Dark border | +| `borderHighlight` | Highlighted border | + +### Background Colors + +| Token | Description | +| --- | --- | +| `background1` | Primary background | +| `background2` | Secondary background | +| `background3` | Tertiary background | +| `background4` | Quaternary background | + +### Button Colors + +| Token | Description | +| --- | --- | +| `buttonBackground` | Primary button background | +| `secondaryButtonBackground` | Secondary button background | +| `buttonIconColor` | Primary button icon | +| `buttonText` | Primary button text | +| `secondaryButtonIcon` | Secondary button icon | +| `secondaryButtonText` | Secondary button text | + +### Other + +| Token | Description | +| --- | --- | +| `shimmerBackground` | Shimmer effect background | +| `shimmerGradient` | Shimmer effect gradient | +| `messageSeen` | Read receipt indicator | +| `white` | White color | +| `black` | Black color | +| `transparent` | Transparent color | -### Light mode +--- -Achieve a vibrant and clean aesthetic with colors optimized for light backgrounds. The CometChatColorPalette offers shades and tints designed to ensure readability and contrast in bright environments. +## Light Mode - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF727272), - background1: Color(0xFFFFFFFF), - textPrimary: Color(0xFF141414), - borderLight: Color(0xFFF5F5F5), - borderDark: Color(0xFFDCDCDC), - iconSecondary: Color(0xFFA1A1A1), - success: Color(0xFF09C26F), - iconHighlight: Color(0xFF6852D6), - extendedPrimary500: Color(0xFFAA9EE8), - warning: Color(0xFFFAAB00), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFF141414), - neutral600: Color(0xFF727272), - neutral300: Color(0xFFE8E8E8), - primary: Color(0xFF6852D6) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + borderDark: Color(0xFFDCDCDC), + iconSecondary: Color(0xFFA1A1A1), + iconHighlight: Color(0xFF6852D6), + success: Color(0xFF09C26F), + warning: Color(0xFFFAAB00), + extendedPrimary500: Color(0xFFAA9EE8), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFFE8E8E8), + neutral600: Color(0xFF727272), + neutral900: Color(0xFF141414), + ), + ], ) ``` - - - - -### Dark mode +--- -Provide a modern and eye-friendly experience with a palette tailored for darker themes, enhancing visual comfort and reducing glare during nighttime use. +## Dark Mode - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF989898), - background1: Color(0xFF1A1A1A), - textPrimary: Color(0xFFFFFFFF), - borderLight: Color(0xFF272727), - iconSecondary: Color(0xFF858585), - success: Color(0xFF0B9F5D), - iconHighlight: Color(0xFF6852D6), - extendedPrimary500: Color(0xFF3E3180), - warning: Color(0xFFD08D04), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFFFFFFFF), - neutral600: Color(0xFF989898), - neutral300: Color(0xFF383838), - primary: Color(0xFF6852D6) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFFFFFFFF), + textSecondary: Color(0xFF989898), + background1: Color(0xFF1A1A1A), + borderLight: Color(0xFF272727), + iconSecondary: Color(0xFF858585), + iconHighlight: Color(0xFF6852D6), + success: Color(0xFF0B9F5D), + warning: Color(0xFFD08D04), + extendedPrimary500: Color(0xFF3E3180), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFF383838), + neutral600: Color(0xFF989898), + neutral900: Color(0xFFFFFFFF), + ), + ], ) ``` - - - - -### Custom Colors +--- -Personalize your application's appearance by defining unique color schemes using CometChatColorPalette, aligning the chat interface with specific branding or creative preferences. +## Custom Brand Colors - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF727272), - background1: Color(0xFFFFFFFF), - textPrimary: Color(0xFF141414), - borderLight: Color(0xFFF5F5F5), - borderDark: Color(0xFFDCDCDC), - iconSecondary: Color(0xFFA1A1A1), - success: Color(0xFF09C26F), - iconHighlight: Color(0xFFF76808), - extendedPrimary500: Color(0xFFFBAA75), - warning: Color(0xFFFAAB00), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFF141414), - neutral600: Color(0xFF727272), - neutral300: Color(0xFFE8E8E8), - primary: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + iconHighlight: Color(0xFFF76808), + extendedPrimary500: Color(0xFFFBAA75), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + borderDark: Color(0xFFDCDCDC), + success: Color(0xFF09C26F), + warning: Color(0xFFFAAB00), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFFE8E8E8), + neutral600: Color(0xFF727272), + neutral900: Color(0xFF141414), + ), + ], ) ``` - - - - - -Ready to unleash your inner designer? Explore the `CometChatColorPalette` and create a stunning and personalized user experience! From d015f89ec016d83e862adfe0bc1120e2d1446253 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:01:38 +0530 Subject: [PATCH 16/32] Updates docs for { "group": "Theming", "pages": [ "ui-kit/flutter/theme-introduction", "ui-kit/flutter/color-resources", "ui-kit/flutter/component-styling", "ui-kit/flutter/message-bubble-styling", "ui-kit/flutter/localize", "ui-kit/flutter/sound-manager" ] }, --- ui-kit/flutter/component-styling.mdx | 626 +++------------- ui-kit/flutter/localize.mdx | 430 +++-------- ui-kit/flutter/message-bubble-styling.mdx | 827 +++++----------------- ui-kit/flutter/sound-manager.mdx | 126 ++-- ui-kit/flutter/theme-introduction.mdx | 208 +++--- 5 files changed, 586 insertions(+), 1631 deletions(-) diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 312a7ce36..29eb4bf94 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -1,670 +1,248 @@ --- -title: "Elevate Your Chat Experience: Mastering Component Styling In CometChat" +title: "Component Styling" sidebarTitle: "Component Styling" +description: "Style individual CometChat Flutter UI Kit components using ThemeExtensions." --- -## Unlock the Power of Customization + -Tired of generic chat interfaces? With CometChat's powerful component styling capabilities, you can now create truly unique and visually stunning chat experiences. +| Field | Value | +| --- | --- | +| Method | Add component style classes to `ThemeData.extensions` | +| Components | Conversations, MessageList, MessageComposer, MessageHeader, Users, Groups, GroupMembers | +| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, MediaRecorder | +| Pattern | `CometChatStyle` classes | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | -## Transform Your Chat with Component Styling + -Component Styling empowers you to fine-tune every aspect of your chat UI, from the subtle nuances of message bubbles to the bold impact of global theme changes. Customize the following key components to match your brand's identity and user preferences: +Style individual components by adding their style classes to `ThemeData.extensions`. -## Components +--- -### Conversation +## Main Components -Control the overall layout and behavior of conversations. +### Conversations - - ```dart ThemeData( - fontFamily: 'Times New Roman', - extensions: [ - CometChatConversationsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75) - ), - badgeStyle: CometChatBadgeStyle( - backgroundColor: Color(0xFFF76808) - ) - ) - ] + extensions: [ + CometChatConversationsStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + badgeStyle: CometChatBadgeStyle( + backgroundColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Message List -Customize the appearance of message lists, including bubble styles, timestamps, and reactions. - - - ```dart ThemeData( - extensions: [ - CometChatMessageListStyle( - backgroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ) - ) - ] + extensions: [ + CometChatMessageListStyle( + backgroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Message Composer -Tailor the input field and send button to suit your design. - - - ```dart ThemeData( - extensions: [ - CometChatMessageComposerStyle( - sendButtonIconBackgroundColor: Color(0xFFF76808), - secondaryButtonIconColor: Color(0xFFF76808), - auxiliaryButtonIconColor: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatMessageComposerStyle( + sendButtonIconBackgroundColor: Color(0xFFF76808), + secondaryButtonIconColor: Color(0xFFF76808), + auxiliaryButtonIconColor: Color(0xFFF76808), + ), + ], ) ``` - - - - ### Message Header -Customize the header displayed at the top of each conversation. - - - ```dart ThemeData( - extensions: [ - CometChatMessageHeaderStyle( - avatarStyle: CometChatAvatarStyle( - backgroundColor: Color(0xFFFBAA75), - borderRadius: BorderRadius.circular(6.67), - ), - callButtonsStyle: CometChatCallButtonsStyle( - voiceCallIconColor: Color(0xFFF76808), - videoCallIconColor: Color(0xFFF76808), - ), - ) - ] + extensions: [ + CometChatMessageHeaderStyle( + avatarStyle: CometChatAvatarStyle( + backgroundColor: Color(0xFFFBAA75), + borderRadius: BorderRadius.circular(6.67), + ), + callButtonsStyle: CometChatCallButtonsStyle( + voiceCallIconColor: Color(0xFFF76808), + videoCallIconColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Users -Style user profiles and lists. - - - ```dart ThemeData( - extensions: [ - CometChatUsersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - backgroundColor: Color(0xFFFFF9F5) - ) - ] + extensions: [ + CometChatUsersStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + backgroundColor: Color(0xFFFFF9F5), + ), + ], ) ``` - - - - ### Groups -Customize the appearance of group chats and group information. - - - -```dart -ThemeData( - extensions: [ - CometChatGroupsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - backgroundColor: Color(0xFFFFF9F5) - ) - ] -) -``` - - - - - -### Group Members - -Elevate your group chat experience with customizable member list styles. - - - - - - - ```dart ThemeData( - extensions: [ - CometChatGroupMembersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleStyle: TextStyle(color: Color(0xFFF76808)), - separatorColor: Color(0xFFF76808), - ownerMemberScopeBackgroundColor: Color(0xFFF76808), - adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), - adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), - adminMemberScopeTextColor: Color(0xFFF76808), - moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), - moderatorMemberScopeTextColor: Color(0xFFF76808), - backIconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### AI Assistant Chat History - -The `CometChatAIAssistantChatHistory` component displays the history of interactions with an AI assistant. It provides a seamless way to view past conversations, ensuring users can easily reference previous AI responses. - - - - - - - -```dart -final ccColor = CometChatThemeHelper.getColorPalette(context); -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - style: CometChatAIAssistantChatHistoryStyle( - backgroundColor: const Color(0xFFFFFAF6), - headerBackgroundColor: const Color(0xFFFFFAF6), - headerTitleTextColor: ccColor.textPrimary, - headerTitleTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - newChatIconColor: ccColor.iconSecondary, - newChatTextColor: ccColor.textPrimary, - newChaTitleStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - dateSeparatorStyle: CometChatDateStyle( - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + extensions: [ + CometChatGroupsStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), ), - textColor: ccColor.textTertiary, - backgroundColor: const Color(0xFFFFFAF6), - ), - itemTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + backgroundColor: Color(0xFFFFF9F5), ), - itemTextColor: ccColor.textPrimary, - ), -), + ], +) ``` - - - +--- ## Base Components ### Avatar -Personalize user avatars with different shapes, sizes, and borders. - - - -```dart -ThemeData( - extensions: [ - CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ) - ] -) -``` - - - - - -### Status Indicator - -Control the appearance of online/offline indicators. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatStatusIndicatorStyle( - backgroundColor: Color(0xFFFFAB00), - borderRadius: BorderRadius.circular(2), - ) - ] +CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), ) ``` - - - - ### Badge -Customize badges for unread messages and notifications. - - - ```dart -ThemeData( - extensions: [ - CometChatBadgeStyle( - borderRadius: BorderRadius.circular(4), - backgroundColor: Color(0xFFF44649), - ), - ] +CometChatBadgeStyle( + borderRadius: BorderRadius.circular(4), + backgroundColor: Color(0xFFF44649), ) ``` - - - - -### Date - -Format and style timestamps. - -### Receipts - -Customize the appearance of message receipts (e.g., "Seen," "Delivered"). +### Status Indicator - + - - ```dart -ThemeData( - extensions: [ - CometChatMessageReceiptStyle( - readIconColor: Color(0xFFFFAB00), - ) - ] +CometChatStatusIndicatorStyle( + backgroundColor: Color(0xFFFFAB00), + borderRadius: BorderRadius.circular(2), ) ``` - - - - -### Media Recorder - -Style the audio and video recording interfaces. +### Receipts - + - - ```dart -ThemeData( - extensions: [ - CometChatMediaRecorderStyle( - recordIndicatorBackgroundColor: Color(0xFFF44649), - recordIndicatorBorderRadius: BorderRadius.circular(20), - pauseButtonBorderRadius: BorderRadius.circular(8), - deleteButtonBorderRadius: BorderRadius.circular(8), - stopButtonBorderRadius: BorderRadius.circular(8), - ) - ] +CometChatMessageReceiptStyle( + readIconColor: Color(0xFFFFAB00), ) ``` - - - - -### Sticker Keyboard - -Customize the appearance of sticker keyboards. - ### Reactions -Style the appearance of reactions to messages. - - - -```dart -ThemeData( - extensions: [ - CometChatReactionsStyle( - borderRadius: BorderRadius.circular(8), - ) - ] -) -``` - - - - - -### Reaction List - -Control the style of reactions displayed on messages. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatReactionListStyle( - activeTabTextColor: Color(0xFFF76808), - activeTabIndicatorColor: Color(0xFFF76808), - ) - ] +CometChatReactionsStyle( + borderRadius: BorderRadius.circular(8), ) ``` - +--- - +## AI Components ### Conversation Starter -Tailor the initial message or prompt. - - - -```dart -ThemeData( - extensions: [ - CometChatAIConversationStarterStyle( - backgroundColor: Color(0xFFFEEDE1), - border: Border.all(color: Color(0xFFFBBB90)), - ) - ] -) -``` - - - - - -### Conversation Summary - -Customize the summary view of a conversation. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatAIConversationSummaryStyle( - backgroundColor: Color(0xFFFEEDE1), - titleStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ] +CometChatAIConversationStarterStyle( + backgroundColor: Color(0xFFFEEDE1), + border: Border.all(color: Color(0xFFFBBB90)), ) ``` - - - - ### Smart Replies -Style the appearance of suggested replies. - - - ```dart -ThemeData( - extensions: [ - CometChatAISmartRepliesStyle( - backgroundColor: Color(0xFFFEEDE1), - titleStyle: TextStyle( - color: Color(0xFFF76808), - ), - itemBackgroundColor: Color(0xFFFFF9F5), - itemBorder: Border.all(color: Color(0xFFFBBB90)), - ) - ] +CometChatAISmartRepliesStyle( + backgroundColor: Color(0xFFFEEDE1), + titleStyle: TextStyle(color: Color(0xFFF76808)), + itemBackgroundColor: Color(0xFFFFF9F5), + itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` - - - - - -### Message Information - -Customize the information displayed when tapping on a message. - - - - - - - -```dart -ThemeData( - fontFamily: "Times New Roman", - extensions: [ - CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - CometChatMessageInformationStyle( - backgroundHighLightColor: Color(0xFFFEEDE1), - messageReceiptStyle: CometChatMessageReceiptStyle( - readIconColor: Color(0xFFF76808) - ) - ), - ] - ) -``` - - - - - -### Message Option Sheet - -Style the options menu for individual messages. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatMessageOptionSheetStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### Attachment Option Sheet - -Customize the attachment options menu. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatAttachmentOptionSheetStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### AI Option Sheet - -Style the all-in-one options menu. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatAiOptionSheetStyle( - backgroundColor: Color(0xFFFFF9F5), - iconColor: Color(0xFFF76808) - ) - ] -) -``` - - - - - -### Mentions - -Customize the appearance of user and group mentions. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ] -) -``` - - - - diff --git a/ui-kit/flutter/localize.mdx b/ui-kit/flutter/localize.mdx index 3b8399004..5ae38bc1a 100644 --- a/ui-kit/flutter/localize.mdx +++ b/ui-kit/flutter/localize.mdx @@ -1,402 +1,184 @@ --- -title: "Localize" +title: "Localization" +sidebarTitle: "Localize" +description: "Configure multi-language localization and custom translations in CometChat Flutter UI Kit." --- -## Overview + -CometChat UI Kit provides language localization to adapt to the language of a specific country or region. The CometChatLocalize class allows you to detect the language of your users based on their browser or device settings, and set the language accordingly. +| Field | Value | +| --- | --- | +| Package | `cometchat_uikit_shared` | +| Import | `import 'package:cometchat_uikit_shared/l10n/translations.dart';` | +| Set language | Add `Locale('fr')` to `supportedLocales` | +| Delegates | `Translations.delegate`, `GlobalMaterialLocalizations.delegate`, etc. | +| Supported | 18 languages: ar, de, en, en-GB, es, fr, hi, hu, ja, ko, lt, ms, nl, pt, ru, sv, tr, zh | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/l10n) | -CometChatLocalize is a class that includes methods related to locale. Developers can use these methods to change the language of the UI Kit library. + -Presently, the UI Kit supports 19 languages for localization, which are: +`Translations` manages multi-language localization for the UI Kit. -* Arabic (ar) -* German (de) -* English (en, en-GB) -* Spanish (es) -* French (fr) -* Hindi(hi) -* Hungarian (hu) -* Japanese (ja) -* Korean\* (ko) -* Lithuanian(lt) -* Malay (ms) -* Dutch (nl) -* Portuguese (pt) -* Russian (ru) -* Swedish (sv) -* Turkish (tr) -* Chinese (zh, zh-TW) +--- -## Usage +## Supported Languages + +| Language | Code | +| --- | --- | +| Arabic | `ar` | +| German | `de` | +| English | `en` | +| English (UK) | `en-GB` | +| Spanish | `es` | +| French | `fr` | +| Hindi | `hi` | +| Hungarian | `hu` | +| Japanese | `ja` | +| Korean | `ko` | +| Lithuanian | `lt` | +| Malay | `ms` | +| Dutch | `nl` | +| Portuguese | `pt` | +| Russian | `ru` | +| Swedish | `sv` | +| Turkish | `tr` | +| Chinese | `zh` | -### Integration +--- -Add the following dependency in `pubspec.yaml` +## Setup - - -```dart +Add the dependency in `pubspec.yaml`: + +```yaml flutter_localizations: - sdk: flutter + sdk: flutter ``` - - - - -*** +Configure `MaterialApp`: -Update MaterialApp Localizations Delegates - - - ```dart -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_uikit_shared/l10n/translations.dart' as cc; -import 'package:flutter/material.dart'; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; -import 'guard_screen.dart'; - - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - // This widget is the root of your application. - @override - Widget build(BuildContext context) { - return MaterialApp( - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - ], - localizationsDelegates: const [ - cc.Translations.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, - ), - ), - title: 'CometChat Flutter Sample App', - navigatorKey: CallNavigationContext.navigatorKey, - home: GuardScreen(), - debugShowCheckedModeBanner: false, - ); - } -} +MaterialApp( + supportedLocales: const [ + Locale('en'), + Locale('fr'), + Locale('es'), + Locale('de'), + // Add more as needed + ], + localizationsDelegates: Translations.localizationsDelegates, + home: MyApp(), +) ``` - - - - -*** +--- -You can also translate specific strings. For example: +## Get Translated Strings - - ```dart String translatedString = Translations.of(context).users; - -//Use it in a widget Text(translatedString); ``` - - - - -### Customizing UI Kit Translations for a Specific Language +--- -*** +## Custom Translations -To override a specific language's default translations in the CometChat UI Kit, you can create a custom localization class and delegate. The example below demonstrates how to override the English (en) language by customizing labels such as "chats" and "calls". This allows you to tailor the UI text to better fit your application's tone or branding requirements. +Override default translations by extending the language class: - - ```dart -// Import necessary Flutter and package dependencies -import 'dart:async'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart' as cc; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:get/get.dart'; -import 'package:master_app/guard_screen.dart'; -import 'package:master_app/utils/page_manager.dart'; -import 'prefs/shared_preferences.dart'; - -// Main function - entry point of the Flutter application -Future main() async { - WidgetsFlutterBinding.ensureInitialized(); // Ensures bindings are initialized before runApp - SharedPreferencesClass.init(); // Initialize shared preferences - Get.put(PageManager()); // Register PageManager with GetX dependency injection - - runApp(const MyApp()); // Launch the app -} - -// Root widget of the application -class MyApp extends StatefulWidget { - const MyApp({super.key}); - - @override - State createState() => _MyAppState(); -} - -class _MyAppState extends State { - // Builds the MaterialApp with localization, theme, and navigation setup - @override - Widget build(BuildContext context) { - return MaterialApp( - // List of all supported locales - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - ], - - // Localization delegates required to load localized resources - localizationsDelegates: const [ - CustomEN.delegate, // Custom override for English localization - cc.Translations.delegate, // CometChat UI Kit translations - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - - // Application theme configuration - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, // No shadow when scrolling under the AppBar - ), - ), - - title: 'CometChat Flutter Sample App', // App title - navigatorKey: CallNavigationContext - .navigatorKey, // Navigator key for CometChat call handling - home: GuardScreen(), // Initial screen shown to the user - debugShowCheckedModeBanner: false, // Hides the debug banner - ); - } -} -// Custom English translation class overriding default CometChat translations class CustomEN extends TranslationsEn { - static const delegate = _CustomCometChatLocalizationsDelegate(); + static const delegate = _CustomLocalizationsDelegate(); @override - String get chats => "Overridden Chat"; // Custom string for "chats" + String get chats => "My Chats"; @override - String get calls => "Overridden Call"; // Custom string for "calls" + String get calls => "My Calls"; } -// Localization delegate to provide the CustomEN class for English -class _CustomCometChatLocalizationsDelegate - extends LocalizationsDelegate { - const _CustomCometChatLocalizationsDelegate(); +class _CustomLocalizationsDelegate extends LocalizationsDelegate { + const _CustomLocalizationsDelegate(); - // Only support English for this custom delegate @override bool isSupported(Locale locale) => locale.languageCode == 'en'; - // Load the custom English translations synchronously @override - Future load(Locale locale) => - SynchronousFuture(CustomEN()); + Future load(Locale locale) => SynchronousFuture(CustomEN()); - // No need to reload delegate on changes @override - bool shouldReload(_CustomCometChatLocalizationsDelegate old) => false; + bool shouldReload(_CustomLocalizationsDelegate old) => false; } ``` - +Then add to `MaterialApp`: - +```dart +localizationsDelegates: const [ + CustomEN.delegate, // Custom override first + ...Translations.localizationsDelegates, +], +``` -### Adding New Language Support in CometChat UI Kit +--- -*** +## Add New Language -This implementation demonstrates how to extend the CometChat Flutter UI Kit with custom localization support for the Telugu (te) language. By creating a custom translation class and registering it through a LocalizationsDelegate, developers can override or define translation strings such as "Chats" and "Calls" in Telugu. This approach enables personalized and region-specific user experiences beyond the default set of supported languages in the UI Kit. +Create a custom translation class for unsupported languages: - - ```dart -// Import Dart and Flutter dependencies -import 'dart:async'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart' as cc; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:get/get.dart'; -import 'package:master_app/guard_screen.dart'; -import 'package:master_app/utils/page_manager.dart'; -import 'prefs/shared_preferences.dart'; - -// Entry point of the Flutter application -Future main() async { - WidgetsFlutterBinding.ensureInitialized(); // Ensures Flutter engine is initialized - SharedPreferencesClass.init(); // Initialize shared preferences for app storage - Get.put(PageManager()); // Register PageManager using GetX dependency injection - - runApp(const MyApp()); // Launch the main app widget -} -// Main application widget -class MyApp extends StatefulWidget { - const MyApp({super.key}); +class TeluguTranslations extends Translations { + TeluguTranslations([super.locale = "te"]); + static const delegate = _TeluguDelegate(); @override - State createState() => _MyAppState(); -} + String get chats => "సందేశాలు"; -class _MyAppState extends State { - // Root of the application @override - Widget build(BuildContext context) { - return MaterialApp( - // Set the default locale to Telugu - locale: Locale('te'), - - // List of all supported locales including the new Telugu support - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - Locale('te'), // Newly added Telugu locale - ], - - // Localization delegates used to load translations - localizationsDelegates: const [ - MmCCLocalization.delegate, // Custom Telugu localization delegate - cc.Translations.delegate, // CometChat UI Kit default translations - GlobalMaterialLocalizations.delegate, // Flutter built-in material localization - GlobalWidgetsLocalizations.delegate, // Flutter built-in widget localization - GlobalCupertinoLocalizations.delegate, // Flutter built-in Cupertino localization - ], - - // Define app theme (e.g., AppBar style) - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, // Remove shadow when scrolling under AppBar - ), - ), - - title: 'CometChat Flutter Sample App', // App title - navigatorKey: CallNavigationContext.navigatorKey, // Navigator key for CometChat call handling - home: GuardScreen(), // Entry screen of the app - debugShowCheckedModeBanner: false, // Disable debug banner in release mode - ); - } + String get calls => "ఫోన్ కాల్స్"; + + // Override all required getters from Translations... } -// Custom localization delegate for Telugu language -class _NnCometChatLocalizationsDelegate - extends LocalizationsDelegate { - const _NnCometChatLocalizationsDelegate(); +class _TeluguDelegate extends LocalizationsDelegate { + const _TeluguDelegate(); - // Checks if the provided locale is supported (only 'te' in this case) @override bool isSupported(Locale locale) => locale.languageCode == 'te'; - // Load the custom Telugu translation class @override - Future load(Locale locale) => - SynchronousFuture(MmCCLocalization()); + Future load(Locale locale) => SynchronousFuture(TeluguTranslations()); - // Determines whether to reload the delegate (not needed here) @override - bool shouldReload(_NnCometChatLocalizationsDelegate old) => false; + bool shouldReload(_TeluguDelegate old) => false; } +``` -// NOTE: -// Only "chats" and "calls" have been overridden in this example. -// To fully localize the UI for the Telugu language, you should override -// all relevant strings provided by the CometChat UI Kit's Translations class. -// This ensures a consistent and complete user experience across the app. - -// Custom Telugu translation class for CometChat UI Kit -class MmCCLocalization extends cc.Translations { - MmCCLocalization([super.locale = "te"]); - - // Register the delegate for use in MaterialApp - static const delegate = _NnCometChatLocalizationsDelegate(); - - // Override specific UI Kit strings in Telugu - @override - String get chats => "సందేశాలు"; // Telugu for "Chats" +Then add to `MaterialApp`: - @override - String get calls => "ఫోన్ కాల్స్"; // Telugu for "Calls" - - // Note: Add more overrides here to fully localize the UI -} +```dart +localizationsDelegates: const [ + TeluguTranslations.delegate, // Custom language first + ...Translations.localizationsDelegates, +], +supportedLocales: const [ + Locale('te'), // Telugu + Locale('en'), + // Other locales... +], ``` - - - +--- -### DateTimeFormatter -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. +## Date/Time Formatting -For more detailed information and the full reference for the DateTimeFormatterCallback methods, refer to the DateTimeFormatterCallback methods section in the [CometChatUIKit class](/ui-kit/flutter/methods#dateformatter) \ No newline at end of file +Customize date/time display globally via `DateTimeFormatterCallback`. See [CometChatUIKit Methods](/ui-kit/flutter/methods#dateformatter) for details. diff --git a/ui-kit/flutter/message-bubble-styling.mdx b/ui-kit/flutter/message-bubble-styling.mdx index c3e519d0e..4c928a04f 100644 --- a/ui-kit/flutter/message-bubble-styling.mdx +++ b/ui-kit/flutter/message-bubble-styling.mdx @@ -1,774 +1,297 @@ --- -title: "Customizing Message Bubbles" -sidebarTitle: "Message Bubble Styling" +title: "Message Bubble Styling" +sidebarTitle: "Message Bubbles" +description: "Customize incoming and outgoing message bubbles in CometChat Flutter UI Kit." --- -When building chat applications, customizing the look and feel of message bubbles is often a significant challenge. Developers frequently encounter difficulties when they need to modify specific design elements, such as background colors or styles for particular message types. This complexity is amplified by the wide range of message bubbles available in the **CometChat Flutter UI Kit**. + -To simplify this process, the CometChat UI Kit provides two specialized classes: **CometChatOutgoingMessageBubbleStyle** and **CometChatIncomingMessageBubbleStyle**. These classes are designed to give developers fine-grained control over the appearance of message bubbles for **sent** and **received** messages, respectively. Both classes extend the `ThemeExtension` class, allowing customizations to be seamlessly applied through global theming or by explicitly passing style objects. +| Field | Value | +| --- | --- | +| Outgoing | `CometChatOutgoingMessageBubbleStyle` | +| Incoming | `CometChatIncomingMessageBubbleStyle` | +| Usage | Add to `ThemeData.extensions` or pass to `CometChatMessageListStyle` | +| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, AI Assistant (incoming only) | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/models/extension_bubble_styles) | + + + +Customize message bubbles using `CometChatOutgoingMessageBubbleStyle` and `CometChatIncomingMessageBubbleStyle`. -## How These Classes Help - -### 1. Targeted Customization - -Developers can customize specific attributes of message bubbles, such as: - -* Background color - -* Border radius - -* Text style - -* Bubble-specific elements like reactions or avatars - -* Specialized bubbles for various message types, such as: - - * Audio bubbles - * File bubbles - * Collaborative bubbles - * Poll bubbles - * Deleted message bubbles - * Link preview bubbles - * Message translation bubbles - * Sticker bubbles - -This targeted approach eliminates the need to modify every bubble type when changes are required for just one. - -### 2. Unified Global Theming - -By leveraging the power of Flutter's global theming system: +--- -* You can define consistent styles across your application. -* Alternatively, you can apply custom styles dynamically by passing `CometChatOutgoingMessageBubbleStyle` and `CometChatIncomingMessageBubbleStyle` objects to the `outgoingMessageBubbleStyle` and `incomingMessageBubbleStyle` properties of the **CometChatMessageListStyle** class. +## Global Theming - - - +Apply bubble styles globally via `ThemeData.extensions`: - - ```dart MaterialApp( - title: 'Your app', - theme: ThemeData( - extensions: [ - CometChatIncomingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - ] + theme: ThemeData( + extensions: [ + CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), ), - home: ... - ); -``` - - - - - -### 3. Ease of Integration - -To apply these styles: - -1. Create a `CometChatMessageListStyle` object. -2. Assign your custom outgoing and incoming bubble styles. -3. Pass this object to the `style` property of the **CometChatMessageList** widget. - -This modular approach ensures that customization is both easy to manage and highly adaptable. - - - -```dart -CometChatMessageList( - user: user, - group: group, - style: CometChatMessageListStyle( - incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle(), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle(), - ), + CometChatIncomingMessageBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + ), + ], + ), ) ``` - - - - -## Key Features of Each Class - -### CometChatOutgoingMessageBubbleStyle - -Focused on customizing bubbles for **messages sent by the user**, with properties for: - -* **Text bubbles**: Style text content sent by users. -* **Image and video bubbles**: Customize visual media messages. -* **Audio bubbles**: Adjust styles for audio messages. -* **File bubbles**: Tailor the look of file-sharing bubbles. -* **Collaborative bubbles**: Style messages related to collaboration features. -* **Poll bubbles**: Adjust the appearance of poll-related messages. -* **Deleted message bubbles**: Customize how deleted messages are displayed. -* **Link preview bubbles**: Style links with previews for shared URLs. -* **Message translation bubbles**: Adjust translations for sent messages. -* **Sticker bubbles**: Customize stickers sent in chats. -* **Call bubbles**: Style voice and video call bubbles. -* Additional customizations like reactions, timestamps, avatars, and borders. - - + - - -```dart -CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) -) -``` - - - - - -### CometChatIncomingMessageBubbleStyle +--- -Designed to style bubbles for **messages received from others**, with properties for: - -* **Text bubbles**: Customize text content from other users. -* **Image and video bubbles**: Adjust styles for media from others. -* **Audio bubbles**: Customize received audio messages. -* **File bubbles**: Tailor the look of received files. -* **Collaborative bubbles**: Style incoming collaboration-related messages. -* **Poll bubbles**: Adjust the appearance of polls sent by others. -* **Deleted message bubbles**: Customize how deleted messages appear. -* **Link preview bubbles**: Style links with previews in received messages. -* **Message translation bubbles**: Adjust translations for received messages. -* **Sticker bubbles**: Customize stickers sent by others. -* **Call bubbles**: Style voice and video call bubbles. -* **Sender name**: Customize the display style for sender names. -* **AI Assistant bubbles**: Customize how ai assistant messages appear. -* Additional customizations like reactions, timestamps, avatars, and borders. +## Component-Level Styling - - - +Pass styles directly to `CometChatMessageList`: - - ```dart -CometChatIncomingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) +CometChatMessageList( + user: user, + style: CometChatMessageListStyle( + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + ), + ), ) ``` - - - - -## Benefits - -By using these classes, developers can: - -* Save time by focusing on specific customizations. -* Reduce complexity while maintaining a consistent design. -* Create visually appealing and user-friendly chat interfaces. - -Whether you're tweaking a single bubble type or applying a cohesive design across your application, these tools provide the flexibility and precision needed to bring your vision to life. - - - -## Customizable Message Bubbles +--- -The CometChat Flutter Chat UI Kit offers a versatile range of customizable message bubbles tailored to enhance any chat experience. From Text, Image, Video, and Audio Bubbles for seamless multimedia sharing, to File, Poll, and Collaborative Whiteboard/Document Bubbles for productivity, the UI Kit ensures every interaction is visually engaging. Link Previews, Stickers, and Call Bubbles add rich context, while Action and Deleted Message Bubbles enhance clarity. These bubbles are fully customizable, empowering developers to create unique, brand-specific chat interfaces. +## Bubble Types ### Text Bubble - + -Modify text color, font, and background to match your branding while maintaining readability. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` -![Image](/images/1c8970f5-text_bubble_customized-7e864e9942e622a04619f92451de0d4e.png) - - - - - ### Image Bubble - + -Customize borders and background to enhance media presentation. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - imageBubbleStyle: CometChatImageBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - imageBubbleStyle: CometChatImageBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + imageBubbleStyle: CometChatImageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - ### Video Bubble -Style play button color, background color and borders for a seamless viewing experience. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - videoBubbleStyle: CometChatVideoBubbleStyle( - backgroundColor:Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - videoBubbleStyle: CometChatVideoBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - playIconColor: Color(0xFFF76808), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + videoBubbleStyle: CometChatVideoBubbleStyle( + backgroundColor: Color(0xFFF76808), + playIconColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - ### Audio Bubble - - - - -Adjust progress bar colors, play and download button styles, and backgrounds to suit your theme. - - - -```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - audioBubbleStyle: CometChatAudioBubbleStyle( - backgroundColor:Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - audioBubbleStyle: CometChatAudioBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - downloadIconColor: Color(0xFFF76808), - audioBarColor: Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - ] - ) -``` - - - - - -### File Bubble - - - - - -Personalize file bubble's background and download icon colors. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - fileBubbleStyle: CometChatFileBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - fileBubbleStyle: CometChatFileBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - downloadIconTint: Color(0xFFF76808), - ) - ), - ] - ) +CometChatIncomingMessageBubbleStyle( + audioBubbleStyle: CometChatAudioBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + downloadIconColor: Color(0xFFF76808), + audioBarColor: Color(0xFFF76808), + playIconColor: Color(0xFFF76808), + ), +) ``` - - - +### File Bubble -### Sticker Bubble - - - - - -Personalize sticker display with unique padding, borders, and background styles to match the app's personality. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - stickerBubbleStyle: CometChatStickerBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - stickerBubbleStyle: CometChatStickerBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatIncomingMessageBubbleStyle( + fileBubbleStyle: CometChatFileBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + downloadIconTint: Color(0xFFF76808), + ), +) ``` - - - - - - - - -### Call Bubble +### Poll Bubble - + -Customize icons, text, and background elements for incoming and outgoing call notifications to fit seamlessly into your UI design. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - videoCallBubbleStyle: CometChatCallBubbleStyle( - backgroundColor: Color(0xFFF76808), - iconColor: Color(0xFFF76808), - buttonTextStyle: TextStyle( - color: Colors.white, - ), - dividerColor: Color(0xFFFBAA75) - ), - ), - CometChatIncomingMessageBubbleStyle( - videoCallBubbleStyle: CometChatCallBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + pollsBubbleStyle: CometChatPollsBubbleStyle( + backgroundColor: Color(0xFFF76808), + progressBackgroundColor: Color(0xFFFBAA75), + iconColor: Color(0xFFF76808), + ), +) ``` - - - +### Call Bubble -### Collaborative Whiteboard Bubble - - - - - -Style the background and interaction controls to support creative collaboration. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor:Color(0xFFF76808), - iconTint: Color(0xFFFFFFFF), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - color: Color(0xFFFFFFFF), - ), - buttonTextStyle: TextStyle( - color: Color(0xFFFFFFFF), - ), - dividerColor: Color(0xFFFBAA75), - ) - ), - CometChatIncomingMessageBubbleStyle( - collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconTint: Color(0xFFF76808), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - ), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ), - ] - ) -``` - - - - - - - - - -### Collaborative Document Bubble - - - - - -Customize fonts and interface elements for shared document interaction. - - - -```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor:Color(0xFFF76808), - iconTint: Color(0xFFFFFFFF), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - color: Color(0xFFFFFFFF), - ), - buttonTextStyle: TextStyle( - color: Color(0xFFFFFFFF), - ), - dividerColor: Color(0xFFFBAA75), - ) - ), - CometChatIncomingMessageBubbleStyle( - collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconTint: Color(0xFFF76808), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - ), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + videoCallBubbleStyle: CometChatCallBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconColor: Color(0xFFF76808), + buttonTextStyle: TextStyle(color: Colors.white), + dividerColor: Color(0xFFFBAA75), + ), +) ``` - - - - - - - - -### Poll Bubble +### Link Preview Bubble - + -Tailor vote bar colors, text, and layouts to align with your UI design. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - pollsBubbleStyle: CometChatPollsBubbleStyle( - backgroundColor: Color(0xFFF76808), - progressBackgroundColor: Color(0xFFFBAA75), - iconColor: Color(0xFFF76808), - voterAvatarStyle: CometChatAvatarStyle( - border: Border.all(color: Color(0xFFF76808)), - ) - ), - ), - CometChatIncomingMessageBubbleStyle( - pollsBubbleStyle: CometChatPollsBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - progressBackgroundColor: Color(0xFFDCDCDC), - progressColor: Color(0xFFF76808), - iconColor: Colors.white, - selectedOptionColor: Color(0xFFF76808), - voterAvatarStyle: CometChatAvatarStyle( - border: Border.all(color: Color(0xFFFEEDE1)), - ) - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( + backgroundColor: Color(0xFFFBAA75), + ), + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - -### Link Preview Bubble +### Deleted Message Bubble - + -Adjust title fonts, descriptions, and thumbnail frames for cohesive link displays. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( - backgroundColor:Color(0xFFFBAA75), - ), - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( - backgroundColor: Color(0xFFFBAA75), - ), - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + deletedBubbleStyle: CometChatDeletedBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - +### Collaborative Bubbles - - - -### Action Message Bubble - - - + -Style background colors and icons for activity-driven notifications. - - - ```dart -ThemeData( - extensions: [ - CometChatActionBubbleStyle( - textStyle: TextStyle( - color: Color(0xFFF76808), - ), - border: Border.all( - color: Color(0xFFF76808), - ), - backgroundColor: Color(0xFFFEEDE1) - ) - ] - ) +CometChatOutgoingMessageBubbleStyle( + collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconTint: Color(0xFFFFFFFF), + titleStyle: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFFFFFFFF)), + buttonTextStyle: TextStyle(color: Color(0xFFFFFFFF)), + dividerColor: Color(0xFFFBAA75), + ), +) ``` - - - - - - - - -### Deleted Message Bubble - - - - - -Add unique styles for placeholders that indicate message deletion. +### Sticker Bubble - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - deletedBubbleStyle: CometChatDeletedBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - deletedBubbleStyle: CometChatDeletedBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + stickerBubbleStyle: CometChatStickerBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), +) ``` - - - +### Voice Call Bubble - - - - -### Call Action Bubble - - - - - -Customize call action bubbles with unique background colors and icons. - - - ```dart -ThemeData(extensions: [ - CometChatColorPalette(textSecondary: Color(0xFFF76808)), - CometChatActionBubbleStyle( - textStyle: TextStyle( - color: Color(0xFFF76808), - ), - border: Border.all( - color: Color(0xFFF76808), - ), - backgroundColor: Color(0xFFFEEDE1)) - ]); +CometChatOutgoingMessageBubbleStyle( + voiceCallBubbleStyle: CometChatCallBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconColor: Color(0xFFFFFFFF), + buttonTextStyle: TextStyle(color: Colors.white), + ), +) ``` - - - - - - - - -### AI Assistant Bubble - -AI Assistant bubbles display messages and interactions from an AI assistant within the chat interface. - -**Default** - - - - +--- -**Customization** +## Style Properties Reference - - - +### CometChatOutgoingMessageBubbleStyle -**Customizing Bubble** +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the message bubble | +| `border` | `BoxBorder?` | Border of the message bubble | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message bubble | +| `messageBubbleBackgroundImage` | `DecorationImage?` | Background image for the bubble | +| `threadedMessageIndicatorTextStyle` | `TextStyle?` | Text style for threaded message indicator | +| `threadedMessageIndicatorIconColor` | `Color?` | Icon color for threaded message indicator | +| `messageBubbleAvatarStyle` | `CometChatAvatarStyle?` | Style for sender avatar | +| `messageReceiptStyle` | `CometChatMessageReceiptStyle?` | Style for message receipts | +| `messageBubbleReactionStyle` | `CometChatReactionsStyle?` | Style for message reactions | +| `messageBubbleDateStyle` | `CometChatDateStyle?` | Style for message date | +| `textBubbleStyle` | `CometChatTextBubbleStyle?` | Style for text messages | +| `imageBubbleStyle` | `CometChatImageBubbleStyle?` | Style for image messages | +| `videoBubbleStyle` | `CometChatVideoBubbleStyle?` | Style for video messages | +| `audioBubbleStyle` | `CometChatAudioBubbleStyle?` | Style for audio messages | +| `fileBubbleStyle` | `CometChatFileBubbleStyle?` | Style for file messages | +| `pollsBubbleStyle` | `CometChatPollsBubbleStyle?` | Style for poll messages | +| `stickerBubbleStyle` | `CometChatStickerBubbleStyle?` | Style for sticker messages | +| `voiceCallBubbleStyle` | `CometChatCallBubbleStyle?` | Style for voice call bubbles | +| `videoCallBubbleStyle` | `CometChatCallBubbleStyle?` | Style for video call bubbles | +| `linkPreviewBubbleStyle` | `CometChatLinkPreviewBubbleStyle?` | Style for link preview bubbles | +| `collaborativeDocumentBubbleStyle` | `CometChatCollaborativeBubbleStyle?` | Style for collaborative document bubbles | +| `collaborativeWhiteboardBubbleStyle` | `CometChatCollaborativeBubbleStyle?` | Style for collaborative whiteboard bubbles | +| `messageTranslationBubbleStyle` | `CometChatMessageTranslationBubbleStyle?` | Style for translated messages | +| `deletedBubbleStyle` | `CometChatDeletedBubbleStyle?` | Style for deleted messages | +| `moderationStyle` | `CometChatModerationStyle?` | Style for moderated messages | +| `messagePreviewStyle` | `CometChatMessagePreviewStyle?` | Style for message previews | +| `exceptionStyle` | `CometChatExceptionStyle?` | Style for exception views | - - -```dart -ThemeData( - extensions: [ - CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - textColor: const Color(0xFF141414), - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - ), - ], -); -``` +### CometChatIncomingMessageBubbleStyle - +Includes all properties from `CometChatOutgoingMessageBubbleStyle` except `messageReceiptStyle`, `moderationStyle`, and `exceptionStyle`, plus: - \ No newline at end of file +| Property | Type | Description | +| --- | --- | --- | +| `senderNameTextStyle` | `TextStyle?` | Text style for sender name | +| `aiAssistantBubbleStyle` | `CometChatAIAssistantBubbleStyle?` | Style for AI assistant bubbles | diff --git a/ui-kit/flutter/sound-manager.mdx b/ui-kit/flutter/sound-manager.mdx index fd3317552..c70ad5b88 100644 --- a/ui-kit/flutter/sound-manager.mdx +++ b/ui-kit/flutter/sound-manager.mdx @@ -1,72 +1,116 @@ --- title: "Sound Manager" +sidebarTitle: "Sound Manager" +description: "Manage and customize audio cues for incoming/outgoing calls and messages in CometChat Flutter UI Kit." --- -## Overview + -The SoundManager is a helper class responsible for managing and playing various types of audio in the CometChat UI Kit. This includes sound events for incoming and outgoing messages and calls. +| Field | Value | +| --- | --- | +| Package | `cometchat_uikit_shared` | +| Import | `import 'package:cometchat_uikit_shared/cometchat_uikit_shared.dart';` | +| Class | `SoundManager` (singleton) | +| Play sound | `SoundManager().play(sound: Sound.incomingMessage)` | +| Stop sound | `SoundManager().stop()` | +| Sound events | `incomingMessage`, `outgoingMessage`, `incomingMessageFromOther`, `incomingCall`, `outgoingCall` | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/resources) | -## Methods + -### Play Sound +`SoundManager` is a singleton helper class for managing and playing audio cues — incoming/outgoing calls and messages. -The SoundManager plays pre-defined or custom sounds based on user interactions with the chat interface. If no custom sound file is provided, the default sound is played. +--- -* `play()`: This method plays different types of sounds for incoming and outgoing calls and messages. +## Methods - - -```dart -// Play sound with default sound: -SoundManager().play(sound: Sound.incomingMessage); //To play default incoming message sound -SoundManager().play(sound: Sound.outgoingMessage);//To play default outgoing message sound -``` +### play - +Plays the default or custom audio for a sound event. - +```dart +void play({ + required Sound sound, + String? customSound, + String? packageName, + bool? isLooping, +}) +``` -CometChat sound will behave differently with different type of OS in case of background playing +| Parameter | Type | Description | +| --- | --- | --- | +| `sound` | `Sound` | Required. The sound event type to play | +| `customSound` | `String?` | Optional. Asset path for custom sound file | +| `packageName` | `String?` | Optional. Package name when using sounds from another plugin | +| `isLooping` | `bool?` | Optional. Whether to loop the sound (default: `false`) | -### Stop Sound +```dart +// Play default sounds +SoundManager().play(sound: Sound.incomingMessage); +SoundManager().play(sound: Sound.outgoingMessage); + +// Play custom sound +SoundManager().play( + sound: Sound.outgoingMessage, + customSound: "assets/custom_sound.wav", +); + +// Play looping sound (e.g., for incoming call) +SoundManager().play( + sound: Sound.incomingCall, + isLooping: true, +); +``` -The SoundManager can Stop different types of sounds for incoming and outgoing calls and messages using the following method: +### stop -* `stop()`: This method Stops any sound currently being played. +Stops any currently playing sound. - - ```dart SoundManager().stop(); ``` - +--- - +## Sound Enum -## Usage +| Value | Default Asset | When it plays | +| --- | --- | --- | +| `incomingMessage` | `assets/sound/incoming_message.wav` | New message received | +| `outgoingMessage` | `assets/sound/outgoing_message.wav` | Message sent | +| `incomingMessageFromOther` | `assets/sound/incoming_message.wav` | Message from another conversation | +| `incomingCall` | `assets/sound/incoming_call.wav` | Incoming call detected | +| `outgoingCall` | `assets/sound/outgoing_call.wav` | Outgoing call initiated | -Here is how to use SoundManager: +--- + +## Usage - - ```dart -//Play sound with custom sound -SoundManager().play(sound: Sound.outgoingMessage, customSound: "assetPath"); //To custom message sound -``` +import 'package:cometchat_uikit_shared/cometchat_uikit_shared.dart'; + +// Play incoming message sound +SoundManager().play(sound: Sound.incomingMessage); - +// Play outgoing call sound +SoundManager().play(sound: Sound.outgoingCall); - +// Play custom notification sound +SoundManager().play( + sound: Sound.incomingMessage, + customSound: "assets/sounds/notification.mp3", +); -By using the SoundManager, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. +// Play looping ringtone for incoming call +SoundManager().play( + sound: Sound.incomingCall, + isLooping: true, +); -The table below lists down various Sound enum cases and the corresponding assets played for them: +// Stop any playing sound +SoundManager().stop(); +``` -| Sound | Asset | -| ------------------------ | ---------------------------------- | -| incomingMessage | assets/sound/incoming\_message.wav | -| outgoingMessage | assets/sound/outgoing\_message.wav | -| incomingMessageFromOther | assets/sound/incoming\_message.wav | -| outgoingCall | assets/sound/outgoing\_call.wav | -| incomingCall | assets/sound/incoming\_call.wav | + +Sound behavior varies by OS when the app is in the background. + diff --git a/ui-kit/flutter/theme-introduction.mdx b/ui-kit/flutter/theme-introduction.mdx index a4f874967..984444790 100644 --- a/ui-kit/flutter/theme-introduction.mdx +++ b/ui-kit/flutter/theme-introduction.mdx @@ -1,129 +1,157 @@ --- -title: "Theming In CometChat Flutter UI Kit" -sidebarTitle: "Introduction" +title: "Theming" +sidebarTitle: "Overview" +description: "Customize the CometChat Flutter UI Kit appearance using ThemeExtensions for colors, fonts, spacing, and dark mode." --- -CometChat's theming framework is a robust system that empowers developers to define the **look and feel** of their applications with precision and consistency. It follows three essential design system principles: **Color**, **Typography**, and **Shape**. These principles guide the customization of various UI components. + - - - - -*** +| Field | Value | +| --- | --- | +| Goal | Customize UI Kit appearance (colors, fonts, spacing) via Flutter ThemeExtensions | +| Where | `ThemeData.extensions` in `MaterialApp` | +| Color | `CometChatColorPalette` — primary, neutral, alert, text, icon, background colors | +| Typography | `CometChatTypography` — font sizes, weights, text styles | +| Spacing | `CometChatSpacing` — padding, margin, border radius | +| Dark mode | Use separate `CometChatColorPalette` for dark theme | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/theme) | -## Theming Overview + -Theming in our UI Kit consists of three core components: +Theming controls the look and feel of the chat UI — colors, fonts, and spacing — through Flutter's `ThemeExtension` system. -* **Color**: Managed through `CometChatColorPalette`, it controls the application's color scheme, including primary, neutral, alert, and text colors. -* **Typography**: Defined via `CometChatTypography`, it standardizes text styles, such as font size and weight. -* **Shape**: Configured using `CometChatSpacing`, it defines the structure of margins, paddings, and border radii, shaping the visual layout. + + + -### Key Benefits +--- -* Achieve **consistent UI** design across your application. -* Support for **light and dark themes**. -* Easy **scalability and customization** for app-specific requirements. +## Core Components -*** +| Component | Class | Purpose | +| --- | --- | --- | +| Color | `CometChatColorPalette` | Primary, neutral, alert, text, icon, background colors | +| Typography | `CometChatTypography` | Font sizes, weights, text styles | +| Spacing | `CometChatSpacing` | Padding, margin, border radius | -### Light and Dark Themes +### Typography Tokens -Our Chat UI Kit supports both light and dark themes, to enhance usability and accessibility across diverse environments ensuring that your application is adaptable to user preferences and device settings. +| Token | Purpose | +| --- | --- | +| `heading1` - `heading4` | Heading text styles | +| `body` | Body text | +| `caption1`, `caption2` | Caption text | +| `button` | Button text | +| `link` | Link text | +| `title` | Title text | - - - +### Spacing Tokens -The light theme provides a clean and bright interface ideal for well-lit settings, while the dark theme reduces eye strain and conserves battery life in low-light environments. +| Token | Default Value | +| --- | --- | +| `spacing` - `spacing20` | 2px - 80px (increments of 4) | +| `padding` - `padding10` | Derived from spacing | +| `margin` - `margin20` | Derived from spacing | +| `radius` - `radius6`, `radiusMax` | Border radius values | - - - +--- -By offering adaptive theming, the UI Kit ensures a seamless and visually appealing experience that caters to user preferences and situational needs. This flexibility helps deliver a modern and inclusive chat experience. +## Basic Usage -### Custom Theme +Override theme properties in your `MaterialApp`: -The Chat UI Kit offers robust support for creating **customized themes**, allowing developers to define unique visual styles using `CometChatColorPalette`, `CometChatTypography`, and `CometChatSpacing`. By integrating these custom objects with `ThemeData` `extensions`, developers can establish global theming tailored to their application's specific design requirements. This approach promotes consistency, adaptability, and personalization, enabling seamless alignment with branding guidelines while enhancing user experience. The customization capabilities empower developers to build visually distinct and cohesive chat interfaces that resonate with their target audience. +```dart title="main.dart" +MaterialApp( + theme: ThemeData( + fontFamily: 'Roboto', + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + textPrimary: Color(0xFF141414), + background1: Color(0xFFFFFFFF), + ), + ], + ), + home: MyApp(), +) +``` -Flutter's [**ThemeExtension**](https://api.flutter.dev/flutter/material/ThemeExtension-class.html) allows you to extend the default theming system to include **custom properties**, enabling **global styling** for app-specific widgets. It provides a structured way to define custom colors, typography, or spacing beyond Flutter’s default themes. +--- -By creating custom **ThemeExtension** classes, you can apply consistent styles across widgets using `ThemeData`. Developers can access these styles through `Theme.of(context).extension()`, ensuring a clean and maintainable approach to styling. This is particularly useful for apps requiring **customizable and reusable themes**. +## Light and Dark Themes - + - - -```dart +```dart title="Light Theme" ThemeData( - fontFamily: 'Times New Roman', - extensions: [ - CometChatColorPalette( - primary: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + ), + ], ) ``` - - - - -*** - -## Core Components - -### **Color** - -The `CometChatColorPalette` class offers a comprehensive way to manage colors in your app. It includes colors for primary themes, alerts, text, icons, borders, and backgrounds. - -#### Features - -* **Primary Colors**: Base colors and extended shades. -* **Neutral Colors**: Shades for surfaces and backgrounds. -* **Alert Colors**: Colors for states like success, error, warning, and info. -* **Text Colors**: Differentiated for primary, secondary, and disabled states. - - + -### **Typography** - -Typography plays a critical role in ensuring that content is both legible and engaging. The UI Kit supports custom font styles and weights, allowing developers to create a hierarchy of text elements. +```dart title="Dark Theme" +ThemeData( + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFFFFFFFF), + textSecondary: Color(0xFF989898), + background1: Color(0xFF1A1A1A), + borderLight: Color(0xFF272727), + ), + ], +) +``` -#### Features +--- -* **Headings**: Text styles for various heading levels, allowing for clear text hierarchy. -* **Body**: Defines the styling for regular text, such as paragraphs or content. -* **Captions**: Smaller text style, typically used for labels or supplementary information. -* **Buttons**: Customizes the text style for button text. -* **Links**: Styles the text for clickable links. -* **Titles**: Defines the style for main titles or component headers. +## Custom Brand Colors - + -### **Spacing** - -Spacing plays a key role in modern UI design by improving clarity, readability, and usability. Proper spacing allows elements to stand out, guides the user’s focus, and enhances the visual hierarchy. It ensures that interfaces feel organized and easy to navigate, contributing significantly to a seamless and intuitive user experience.`CometChatSpacing` provides various spacing properties such as padding, margin, and radius, essential for maintaining consistent layouts across the UI. - -#### Features - -* **Padding**: Controls the internal spacing within elements, ensuring content doesn't touch the edges. -* **Margin**: Defines the space between elements, providing separation for better visual structure. -* **Radius**: Adjusts the corner rounding of UI elements for a smoother, more modern appearance. - - - - +```dart +ThemeData( + fontFamily: 'Times New Roman', + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + iconHighlight: Color(0xFFF76808), + extendedPrimary500: Color(0xFFFBAA75), + ), + ], +) +``` -### Best Practices +--- -* **Ensure** Contrast: Follow accessibility guidelines to maintain a minimum contrast ratio. -* **Consistency**: Use a consistent color palette across all components. -* **Adaptability**: Test your theme in various scenarios, such as low-light and high-contrast environments. +## Next Steps + + + + Full list of color tokens + + + Style individual components + + + Customize message bubbles + + + Multi-language support + + From 1e5ca024588cbcfeac78f61b22179b351fe68161 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:13:57 +0530 Subject: [PATCH 17/32] Update component-styling.mdx --- ui-kit/flutter/component-styling.mdx | 152 ++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 29eb4bf94..5ca6af35a 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -10,7 +10,9 @@ description: "Style individual CometChat Flutter UI Kit components using ThemeEx | --- | --- | | Method | Add component style classes to `ThemeData.extensions` | | Components | Conversations, MessageList, MessageComposer, MessageHeader, Users, Groups, GroupMembers | -| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, MediaRecorder | +| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, ReactionList, MediaRecorder | +| AI components | ConversationStarter, ConversationSummary, SmartReplies, AIOptionSheet, AIAssistantChatHistory | +| Option sheets | MessageOptionSheet, AttachmentOptionSheet, AIOptionSheet | | Pattern | `CometChatStyle` classes | | Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | @@ -148,6 +150,30 @@ ThemeData( ) ``` +### Group Members + +```dart +ThemeData( + extensions: [ + CometChatGroupMembersStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + titleStyle: TextStyle(color: Color(0xFFF76808)), + separatorColor: Color(0xFFF76808), + ownerMemberScopeBackgroundColor: Color(0xFFF76808), + adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), + adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), + adminMemberScopeTextColor: Color(0xFFF76808), + moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), + moderatorMemberScopeTextColor: Color(0xFFF76808), + backIconColor: Color(0xFFF76808), + ), + ], +) +``` + --- ## Base Components @@ -215,6 +241,90 @@ CometChatReactionsStyle( ) ``` +### Reaction List + +```dart +CometChatReactionListStyle( + activeTabTextColor: Color(0xFFF76808), + activeTabIndicatorColor: Color(0xFFF76808), +) +``` + +### Media Recorder + +```dart +CometChatMediaRecorderStyle( + recordIndicatorBackgroundColor: Color(0xFFF44649), + recordIndicatorBorderRadius: BorderRadius.circular(20), + pauseButtonBorderRadius: BorderRadius.circular(8), + deleteButtonBorderRadius: BorderRadius.circular(8), + stopButtonBorderRadius: BorderRadius.circular(8), +) +``` + +--- + +## Option Sheets + +### Message Option Sheet + +```dart +ThemeData( + extensions: [ + CometChatMessageOptionSheetStyle( + backgroundColor: Color(0xFFFEEDE1), + iconColor: Color(0xFFF76808), + ), + ], +) +``` + +### Attachment Option Sheet + +```dart +ThemeData( + extensions: [ + CometChatAttachmentOptionSheetStyle( + backgroundColor: Color(0xFFFEEDE1), + iconColor: Color(0xFFF76808), + ), + ], +) +``` + +### Message Information + +```dart +ThemeData( + extensions: [ + CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + CometChatMessageInformationStyle( + backgroundHighLightColor: Color(0xFFFEEDE1), + messageReceiptStyle: CometChatMessageReceiptStyle( + readIconColor: Color(0xFFF76808), + ), + ), + ], +) +``` + +### Mentions + +```dart +ThemeData( + extensions: [ + CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ], +) +``` + --- ## AI Components @@ -246,3 +356,43 @@ CometChatAISmartRepliesStyle( itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` + +### Conversation Summary + +```dart +CometChatAIConversationSummaryStyle( + backgroundColor: Color(0xFFFEEDE1), + titleStyle: TextStyle(color: Color(0xFFF76808)), +) +``` + +### AI Option Sheet + +```dart +CometChatAiOptionSheetStyle( + backgroundColor: Color(0xFFFFF9F5), + iconColor: Color(0xFFF76808), +) +``` + +### AI Assistant Chat History + +```dart +final ccColor = CometChatThemeHelper.getColorPalette(context); + +CometChatAIAssistantChatHistory( + user: user, + style: CometChatAIAssistantChatHistoryStyle( + backgroundColor: Color(0xFFFFFAF6), + headerBackgroundColor: Color(0xFFFFFAF6), + headerTitleTextColor: ccColor.textPrimary, + newChatIconColor: ccColor.iconSecondary, + newChatTextColor: ccColor.textPrimary, + dateSeparatorStyle: CometChatDateStyle( + textColor: ccColor.textTertiary, + backgroundColor: Color(0xFFFFFAF6), + ), + itemTextColor: ccColor.textPrimary, + ), +) +``` From 56b276861839e356bcff4ebc95eb7e5468958caa Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:14:05 +0530 Subject: [PATCH 18/32] Update message-bubble-styling.mdx --- ui-kit/flutter/message-bubble-styling.mdx | 62 ++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/message-bubble-styling.mdx b/ui-kit/flutter/message-bubble-styling.mdx index 4c928a04f..3b5fd03ca 100644 --- a/ui-kit/flutter/message-bubble-styling.mdx +++ b/ui-kit/flutter/message-bubble-styling.mdx @@ -10,8 +10,10 @@ description: "Customize incoming and outgoing message bubbles in CometChat Flutt | --- | --- | | Outgoing | `CometChatOutgoingMessageBubbleStyle` | | Incoming | `CometChatIncomingMessageBubbleStyle` | +| Action | `CometChatActionBubbleStyle` | +| AI Assistant | `CometChatAiAssistantBubbleStyle` | | Usage | Add to `ThemeData.extensions` or pass to `CometChatMessageListStyle` | -| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, AI Assistant (incoming only) | +| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, Action, AI Assistant | | Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/models/extension_bubble_styles) | @@ -217,6 +219,7 @@ CometChatOutgoingMessageBubbleStyle( ```dart +// Collaborative Whiteboard CometChatOutgoingMessageBubbleStyle( collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( backgroundColor: Color(0xFFF76808), @@ -226,6 +229,17 @@ CometChatOutgoingMessageBubbleStyle( dividerColor: Color(0xFFFBAA75), ), ) + +// Collaborative Document +CometChatOutgoingMessageBubbleStyle( + collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconTint: Color(0xFFFFFFFF), + titleStyle: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFFFFFFFF)), + buttonTextStyle: TextStyle(color: Color(0xFFFFFFFF)), + dividerColor: Color(0xFFFBAA75), + ), +) ``` ### Sticker Bubble @@ -251,6 +265,36 @@ CometChatOutgoingMessageBubbleStyle( ) ``` +### Action Message Bubble + +Style activity-driven notifications like "User joined" or "User left": + +```dart +ThemeData( + extensions: [ + CometChatActionBubbleStyle( + textStyle: TextStyle(color: Color(0xFFF76808)), + border: Border.all(color: Color(0xFFF76808)), + backgroundColor: Color(0xFFFEEDE1), + ), + ], +) +``` + +### AI Assistant Bubble + +```dart +ThemeData( + extensions: [ + CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + textColor: Color(0xFF141414), + textStyle: TextStyle(fontFamily: 'Roboto'), + ), + ], +) +``` + --- ## Style Properties Reference @@ -295,3 +339,19 @@ Includes all properties from `CometChatOutgoingMessageBubbleStyle` except `messa | --- | --- | --- | | `senderNameTextStyle` | `TextStyle?` | Text style for sender name | | `aiAssistantBubbleStyle` | `CometChatAIAssistantBubbleStyle?` | Style for AI assistant bubbles | + +### CometChatActionBubbleStyle + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of action bubble | +| `border` | `BoxBorder?` | Border of action bubble | +| `textStyle` | `TextStyle?` | Text style for action message | + +### CometChatAiAssistantBubbleStyle + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of AI assistant bubble | +| `textColor` | `Color?` | Text color | +| `textStyle` | `TextStyle?` | Text style for AI messages | From 4ecabe30110376e33d34209441d210e7e0d3ec74 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:26:44 +0530 Subject: [PATCH 19/32] updates { "group": "Reference", "pages": [ "ui-kit/flutter/methods", "ui-kit/flutter/events" ] }, --- ui-kit/flutter/events.mdx | 14 +++++++++++++- ui-kit/flutter/methods.mdx | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 4b0a0a06e..4d99da659 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -357,6 +357,16 @@ class _MessageEventsExampleState extends State with CometC // TODO("Not yet implemented") } + @override + void ccMessageForwarded(BaseMessage message, List? usersSent, List? groupsSent, MessageStatus status) { + // TODO("Not yet implemented") + } + + @override + void ccReplyToMessage(BaseMessage message, MessageStatus status) { + // TODO("Not yet implemented") + } + @override void onTextMessageReceived(TextMessage textMessage) { // TODO("Not yet implemented") @@ -570,7 +580,9 @@ class _CallEventsExampleState extends State with CometChatCal 1. `showPanel`: Triggered to show an additional UI panel with custom elements. 2. `hidePanel`: Triggered to hide a previously shown UI panel. 3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. -4. `ccOpenChat`: Triggered to open a chat with a specific user or group. +4. `openChat`: Triggered to open a chat with a specific user or group. +5. `ccComposeMessage`: Triggered when composing a message with a specific text and status. +6. `onAiFeatureTapped`: Triggered when an AI feature is tapped for a specific user or group. diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index d0ab76a2a..bed14c418 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -38,7 +38,7 @@ Here's the table format for the properties available in `UIKitSettings`: | **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` | Sets the AI Features that need to be added in UI Kit | +| **aiFeature** | `List` | Sets the AI Features that need to be added in UI Kit | | **extensions** | `List` | 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 | From 8f126d2a94681f476760fd5e69e4e4c6d9167907 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:09:36 +0530 Subject: [PATCH 20/32] UI Kit Guides --- ui-kit/flutter/guide-block-unblock-user.mdx | 266 ++++----- ui-kit/flutter/guide-call-log-details.mdx | 198 +++---- ui-kit/flutter/guide-group-chat.mdx | 268 ++++----- ui-kit/flutter/guide-message-agentic-flow.mdx | 512 +++++------------- ui-kit/flutter/guide-message-privately.mdx | 222 ++++---- ui-kit/flutter/guide-new-chat.mdx | 217 +++----- ui-kit/flutter/guide-overview.mdx | 33 +- ui-kit/flutter/guide-threaded-messages.mdx | 272 +++++----- ui-kit/flutter/mentions-formatter-guide.mdx | 14 + ui-kit/flutter/shortcut-formatter-guide.mdx | 14 + 10 files changed, 771 insertions(+), 1245 deletions(-) diff --git a/ui-kit/flutter/guide-block-unblock-user.mdx b/ui-kit/flutter/guide-block-unblock-user.mdx index 5a7eed5c4..8f9cecacb 100644 --- a/ui-kit/flutter/guide-block-unblock-user.mdx +++ b/ui-kit/flutter/guide-block-unblock-user.mdx @@ -1,183 +1,189 @@ --- -title: "Implementing Block/Unblock User in Flutter with CometChat UIKit" +title: "Block/Unblock Users" sidebarTitle: "Block/Unblock User" -description: "Enable users to block and unblock other users for privacy and spam control" +description: "Implement block and unblock user functionality in CometChat Flutter UI Kit with composer state management." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Block a user -await CometChatUIKit.blockUsers([user.uid]); - -// Unblock a user -await CometChatUIKit.unblockUsers([user.uid]); - -// Navigate to user info screen -Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatUserInfo(user: tappedUser), - ), -); - -// Check block status -if (user.blockedByMe) { - // Show unblock button -} else { - // Show block button -} -``` - -**Key Components & Methods:** -- `CometChatUIKit.blockUsers()` → SDK method to block users -- `CometChatUIKit.unblockUsers()` → SDK method to unblock users -- `CometChatUserInfo` → User profile screen -- `User.blockedByMe` → Block status property (SDK) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometchatUserInfo` — uses `CometChatUIKit.blockUsers()` / `CometChatUIKit.unblockUsers()` SDK methods | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Events | Block/unblock state managed via `user.blockedByMe` property | +| UI helpers | `CometChatUserInfoController`, confirmation dialogs | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) - + +Block/Unblock lets users prevent specific users from sending them messages. When blocked, the message composer is hidden and replaced with an unblock prompt. -Enable users to block and unblock other users in your Flutter chat app by integrating CometChat’s `blockUsers` and `unblockUsers` methods with a simple UI. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -## Overview +--- -The Block User feature lets one user prevent another from sending messages or interacting with them. Essential for user privacy, spam control, and moderation in public or group chats. Users tap “Block” or “Unblock,” and the CometChat SDK enforces the block state. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometchatUserInfo` | User profile screen with block/unblock controls | +| `CometChatUserInfoController` | Controller managing block/unblock state and actions | +| `CometChatUIKit.blockUsers()` | SDK method to block specific users | +| `CometChatUIKit.unblockUsers()` | SDK method to unblock previously blocked users | +| `user.blockedByMe` | Property indicating if current user blocked this user | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- Initialized CometChat credentials (`appID`, `region`, `authKey`) -- Navigation set up between your chat list and user-info screen (`lib/messages.dart`) +--- -## Components +## Integration Steps -| Component | Role | -|:------------------------------------|:--------------------------------------------------------| -| `CometChatUserInfo` | Displays user profile with block/unblock controls | -| `CometChatUIKit.blockUsers([...])` | SDK method to block specified user(s) | -| `CometChatUIKit.unblockUsers([...])` | SDK method to unblock specified user(s) | -| `ElevatedButton` | Flutter widget for block/unblock actions | +### 1. Navigate to User Info -## Integration Steps +Open the user info screen from the messages view when tapping the user profile or info icon. -### Navigate to User Info Screen +_File: [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart)_ -Open the user-info screen when tapping the info icon in chat. ```dart -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatUserInfo(user: tappedUser), - ), - ); - }, +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometchatUserInfo(user: tappedUser), + ), ); ``` -**File reference:** -[`sample_app/lib/messages/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) +--- + +### 2. Block User + +Call the block user dialog which uses `CometChatUIKit.blockUsers()` with the target UID. On success, update the UI to show the blocked state. -### Add “Block User” Button +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -Let users block another user via the SDK. ```dart -ElevatedButton( - onPressed: () async { - try { - await CometChatUIKit.blockUsers([user.uid]); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('\${user.name} has been blocked')), +listTileOptions( + controller.user?.blockedByMe != true + ? Translations.of(context).block + : Translations.of(context).unBlock, + Icon(Icons.block, color: colorPalette.error), + () { + if (controller.user?.blockedByMe != true) { + controller.blockUserDialog( + context: context, + colorPalette: colorPalette, + typography: typography, ); - } catch (e) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Error blocking user: \$e')), + } else { + controller.unblockUserDialog( + context: context, + colorPalette: colorPalette, + typography: typography, ); } }, - child: Text('Block User'), -); +) ``` -**File reference:** -[`sample_app/lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -### Add “Unblock User” Button +### 3. Unblock User + +Call `CometChatUIKit.unblockUsers()` with the target UID. On success, restore the UI to allow messaging. + +_File: [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart)_ -Allow users to undo the block. ```dart -ElevatedButton( - onPressed: () async { - try { - await CometChatUIKit.unblockUsers([user.uid]); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('\${user.name} has been unblocked')), - ); - } catch (e) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Error unblocking user: \$e')), - ); - } - }, - child: Text('Unblock User'), -); +void unblockUserDialog({ + required BuildContext context, + required CometChatColorPalette colorPalette, + required CometChatTypography typography, +}) { + // Show confirmation dialog + // On confirm: CometChatUIKit.unblockUsers([user.uid]) +} ``` -**File reference:** -[`sample_app/lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -## Customization Options +### 4. Blocked State Banner -- **Button Styling:** Use `ElevatedButton.styleFrom(...)` to customize colors, padding, and shape. -- **Conditional Rendering:** Display “Block” or “Unblock” based on `user.blockedByMe` state. -- **Modal Confirmation:** Wrap actions in `showDialog` for “Are you sure?” prompts. +Display a warning banner when viewing a blocked user's profile. -## Filtering / Edge Cases +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -- **Self-Block Prevention:** Disable the button if `user.uid == loggedInUser.uid`. -- **Offline Users:** Optionally disable or queue actions when network is unavailable. +```dart +if (value.getBlockedByMe()) + Container( + padding: EdgeInsets.symmetric( + horizontal: spacing.padding3 ?? 0, + vertical: spacing.padding2 ?? 0, + ), + color: colorPalette.warning?.withValues(alpha: 0.2), + child: Row( + children: [ + Icon(Icons.info, color: colorPalette.warning), + SizedBox(width: spacing.padding2), + Text("${Translations.of(context).youHaveBlocked} ${widget.user.name}."), + ], + ), + ), +``` + +--- + +### 5. Composer Blocked State -## Error Handling & Blocked-User Handling +When a user is blocked, the composer in thread/message views is replaced with an unblock prompt. -- **SnackBars:** Show success or error messages via `ScaffoldMessenger`. -- **Retry Logic:** Offer a “Retry” action in the SnackBar on failure. -- **UI State:** Disable the button while the SDK call is in progress to prevent duplicates. +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -## Optional Context-Specific Notes +```dart +if (controller.user?.blockedByMe == true) { + return Container( + padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20), + color: colorPalette.background4, + child: Column( + children: [ + Text(Translations.of(context).cantSendMessageBlockedUser), + ElevatedButton( + onPressed: () => controller.unBlockUser(), + child: Text(Translations.of(context).unBlock), + ), + ], + ), + ); +} +``` -**Group vs. User Blocking:** -This guide covers only user-to-user blocking. For group moderation (ban or remove members), see [`sample_app/lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) methods like `removeMembers` and `banMembers`. +--- + +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| User info screen | `CometchatUserInfo` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Block user | `blockUserDialog()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Unblock user | `unblockUserDialog()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Check blocked status | `user.blockedByMe` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Blocked banner | Warning container | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Blocked composer | `_buildBlockedUserSection()` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | -| Feature | File | Method | -|:---------------------|:---------------------------------------------|:-----------------------------------------| -| Open User Info | [sample_app/lib/messages/messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | `Navigator.push(...)` | -| Block User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.blockUsers([...])` | -| Unblock User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.unblockUsers([...])` | -| Group Management | [sample_app/lib/group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | Group-related actions (not blocking) | +--- ## Next Steps - - Display and manage user lists + + Display and manage user lists. - - View messages with blocked user handling + + Customize the message input component. - - Learn about group moderation features + + Browse all feature and formatter guides. - - Explore other implementation guides + + Full working sample application on GitHub. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-call-log-details.mdx b/ui-kit/flutter/guide-call-log-details.mdx index e7393ed16..09d09842e 100644 --- a/ui-kit/flutter/guide-call-log-details.mdx +++ b/ui-kit/flutter/guide-call-log-details.mdx @@ -1,171 +1,117 @@ --- -title: "Managing & Viewing Call Logs in Your Flutter Chat App" -sidebarTitle: "Call Logs" -description: "Display call history and detailed call information in your Flutter chat app" +title: "Call Log Details" +sidebarTitle: "Call Log Details" +description: "Display call history and detailed call information in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatCallLogs`, `CometChatCallLogDetails` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Calls tab → `CometChatCallLogs` → tap item → `CometChatCallLogDetails` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// Display call logs list -CometChatCallLogs( - onItemClick: (callLog) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatCallLogDetails(callLog: callLog), - ), - ); - }, -); + -// Show call log details -CometChatCallLogDetails( - callLog: callLog, -); -``` +Call Log Details provides a dedicated Calls tab where users can view recent audio and video calls and inspect detailed information for each call. -**Key Components:** -- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) -- `CometChatCallLogDetails` → Call details screen -- `CallLog` → Call log data model (SDK) +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -**Sample Implementation:** [call_log_details/cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) - -**Requirements:** Call functionality enabled in CometChat dashboard, microphone/camera permissions - - - -Learn how to integrate and customize CometChat’s `CometChatCallLogs` and `CometChatCallLogDetails` components to display call history and detailed call information in your Flutter chat app. - -## Overview +--- -- This feature provides a dedicated Calls tab where users can view a list of recent audio and video calls and inspect detailed information for each call. -- Enables users to review communication history, redial, or manage past calls directly within the app. -- Users access comprehensive call logs and individual call details via intuitive UI components. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatCallLogs` | Displays the list of recent calls with tap callbacks | +| `CometChatCallLogDetails` | Shows detailed information (participants, duration, type) | +| `CallLog` | Call log data model from SDK | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Call functionality enabled in your CometChat app dashboard -- Required permissions for microphone and camera in your app -- Navigation setup for tabs and detail screens +--- -## Components +## Integration Steps -| Component | Role | -|:-----------------------------------|:---------------------------------------------------------------------| -| `CometChatCallLogs` | Displays the list of recent calls with tap callbacks | -| `CometChatCallLogDetails` | Shows detailed information (participants, duration, type) | -| `dashboard.dart` | Contains the Calls tab integration in the main UI | -| `call_log_details/cometchat_call_log_details.dart` | Implements the details screen UI | +### 1. Add Calls Tab -## Integration Steps +Integrate the Calls tab into your main dashboard using `CometChatCallLogs`. -### Add Calls Tab to Main UI +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Integrate the Calls tab into your main dashboard. ```dart -// In sample_app/lib/dashboard.dart, update your PageView or BottomNavigation -_pageController.selectedIndex == 2 - ? CometChatCallLogs( - onItemClick: (callLog) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatCallLogDetails(callLog: callLog), - ), - ); - }, - ) - : SizedBox.shrink(), +CometChatCallLogs( + onItemClick: (callLog) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatCallLogDetails(callLog: callLog), + ), + ); + }, +) ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 2. Display Call Logs -### Display Call Logs +Use `CometChatCallLogs` to fetch and show recent calls with customizable styling. + +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Use `CometChatCallLogs` to fetch and show recent calls. ```dart CometChatCallLogs( onItemClick: (callLog) { - // Navigates to details screen + // Navigate to details screen }, -); + callLogsStyle: CometChatCallLogsStyle( + backgroundColor: colorPalette.background1, + ), +) ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 3. Show Call Log Details -### Show Call Log Details +Present detailed information when a call log is tapped. + +_File: [cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart)_ -Present detailed information when a call log is tapped. ```dart CometChatCallLogDetails( callLog: callLog, -); +) ``` -**File reference:** -[`sample_app/lib/call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) - -## Implementation Flow - -1. User selects the Calls tab in the dashboard -2. `CometChatCallLogs` displays recent calls -3. User taps on a call log entry -4. App navigates to `CometChatCallLogDetails` showing call details - -## Customization Options - -- **Styling:** Override colors, fonts, and list item layouts via UIKit theming -- **Call Type Filters:** Apply filters in `CometChatCallLogs` if supported -- **Empty State:** Provide custom UI when no call logs are available - -## Filtering / Edge Cases - -- **No Call Logs:** Display an empty state message when call history is empty -- **Pagination:** Handle large call logs with lazy loading or pagination controls -- **Blocked Users:** Indicate or hide entries involving blocked users - -## Error Handling & Blocked-User Handling - -- **Network Errors:** Show `SnackBar` or error widgets when fetch fails -- **Blocked Users:** Disable detail navigation or show warning if a user is blocked -- **Retry Logic:** Offer retry options for failed fetch or navigation - -## Optional Context-Specific Notes +--- -- **Group Calls:** `CometChatCallLogDetails` will list all participants for group calls -- **1:1 Calls:** Details screen focuses on the other participant +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Calls tab | `CometChatCallLogs` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Display call logs | `CometChatCallLogs` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Call details | `CometChatCallLogDetails` | [cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | -| Feature | Component / Method | File(s) | -|:--------------------------|:------------------------------------|:---------------------------------------------------------------------| -| Calls tab integration | `CometChatCallLogs(onItemClick)` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Display call logs | `CometChatCallLogs` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Show call details | `CometChatCallLogDetails(callLog)` | [`call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | +--- ## Next Steps - - Learn more about the Call Logs component + + Learn more about the Call Logs component. - - Explore all calling capabilities + + Explore all calling capabilities. - - Add call buttons to your chat interface + + Add call buttons to your chat interface. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-group-chat.mdx b/ui-kit/flutter/guide-group-chat.mdx index cdc640522..762b4b216 100644 --- a/ui-kit/flutter/guide-group-chat.mdx +++ b/ui-kit/flutter/guide-group-chat.mdx @@ -1,91 +1,50 @@ --- -title: "Managing Groups in Flutter UI Kit" -sidebarTitle: "Groups" -description: "Create groups, manage members, assign roles, and transfer ownership in your Flutter chat app" +title: "Group Management" +sidebarTitle: "Group Chat" +description: "Create groups, manage members, assign roles, and transfer ownership in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Create a group -await CometChat.createGroup( - group: Group( - guid: groupId, - name: groupName, - type: groupType, - password: groupPassword, - ), -); - -// Join a group -await CometChat.joinGroup(guid: groupId, groupType: groupType, password: password); - -// Add members -CometChatAddMembers(group: group); - -// Ban/unban members -CometChatBannedMembers(group: group); - -// Change member scope -CometChatChangeScope(group: group, user: user); - -// Transfer ownership -CometChatTransferOwnership(group: group); -``` - -**Key Components:** -- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) -- `CometChatCreateGroup` → Group creation UI -- `CometChatGroupInfo` → Group info screen -- `CometChatAddMembers` → Add members UI -- `CometChatBannedMembers` → Banned members management -- `CometChatTransferOwnership` → Ownership transfer UI -- `JoinProtectedGroupUtils` → Password group join utility (sample app) - -**Sample Implementation:** [group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatGroups`, `CometChatCreateGroup`, `CometChatGroupInfo`, `CometChatAddMembers`, `CometChatBannedMembers`, `CometChatTransferOwnership` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Groups tab → create/join group → `CometChatGroupInfo` for management | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | + -Learn how to create groups, join public/password groups, manage members, ban users, update roles, and transfer group ownership using CometChat UIKit for Flutter. +Group Management enables users to create groups, join public/password groups, manage members, ban users, update roles, and transfer ownership. -## Overview +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Enable your users to: +--- -- Create or join public/private/password-protected groups -- View and manage group members -- Assign roles and moderate participants -- Transfer group ownership for continuity +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatGroups` | Displays groups and create button | +| `CometChatCreateGroup` | UI to create new groups | +| `CometChatGroupInfo` | Shows group info and member management | +| `CometChatAddMembers` | Add members to a group | +| `CometChatBannedMembers` | View/unban banned users | +| `CometChatTransferOwnership` | Transfer group ownership | +| `CometChatChangeScope` | Change a user's group role | +| `JoinProtectedGroupUtils` | Utility to join password-protected groups | -- **CometChat UIKit for Flutter** installed via `pubspec.yaml` -- CometChat initialized with `App ID`, `Region`, and `Auth Key` -- Group chat enabled in your CometChat app -- Navigation set up between group/member screens -- Internet permissions +--- -## Components +## Integration Steps -| Component/Class | Role | -|-----------------------------|------------------------------------------------------| -| `CometChatGroups` | Displays groups and a “create” button | -| `CometChatCreateGroup` | UI to create new groups | -| `CometChatContacts` | Lets users search/join groups | -| `CometChatGroupInfo` | Shows group info and member management options | -| `CometChatAddMembers` | Add members to a group | -| `CometChatBannedMembers` | View/unban banned users | -| `CometChatTransferOwnership`| Transfer group ownership | -| `CometChatChangeScope` | Change a user’s group role | -| `JoinProtectedGroupUtils` | Utility to join password-protected groups | +### 1. Create a Group -## Integration Steps +Show the create group dialog from the dashboard. -### Create a Group +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ ```dart IconButton( @@ -98,171 +57,126 @@ IconButton( ); }, icon: Icon(Icons.group_add), -); +) ``` +_File: [cometchat_create_group.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/create_group/cometchat_create_group.dart)_ + ```dart -ElevatedButton( - onPressed: () async { - await CometChat.createGroup( - group: Group( - guid: groupId, - name: groupName, - type: groupType, - password: groupPassword, - ), - onSuccess: (Group group) => Navigator.pop(context), - onError: (e) { - // Show error - }, - ); +await CometChat.createGroup( + group: Group( + guid: groupId, + name: groupName, + type: groupType, + password: groupPassword, + ), + onSuccess: (Group group) => Navigator.pop(context), + onError: (e) { + // Show error }, - child: Text('Create Group'), ); ``` -📄 [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) - --- -### Join Public/Password Group +### 2. Join Public/Password Group + +Handle group tap to join or prompt for password. + +_File: [join_protected_group_util.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart)_ ```dart CometChatGroups( onItemTap: (context, group) { - JoinProtectedGroupUtils.onGroupItemTap(context, group, ...); + JoinProtectedGroupUtils.onGroupItemTap(context, group); }, -); +) ``` -```dart -if (group.type == GroupType.password) { - // Show password prompt - // Join via CometChat.joinGroup with password -} -``` +--- -📄 [`join_protected_group_util.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart) +### 3. View Group Info ---- +Display group details and member management options. -### View Members +_File: [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart)_ ```dart CometChatGroupInfo( group: group, -); +) ``` -📄 [`group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) - --- -### Add Members +### 4. Add Members + +Navigate to add members screen. + +_File: [cometchat_add_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_memebers/cometchat_add_members.dart)_ ```dart CometChatAddMembers( group: group, -); +) ``` -📄 [`add_members/cometchat_add_members.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_members/cometchat_add_members.dart) - --- -### Ban/Unban Members +### 5. Ban/Unban Members + +Manage banned members list. + +_File: [cometchat_banned_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart)_ ```dart CometChatBannedMembers( group: group, -); +) ``` -📄 [`banned_members/cometchat_banned_members.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart) - --- -### Change Member Scope +### 6. Transfer Ownership -```dart -CometChatChangeScope( - group: group, - user: user, -); -``` - -📄 [`group_info/cometchat_group_info_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info_controller.dart) - ---- +Transfer group ownership to another member. -### Transfer Ownership +_File: [cometchat_transfer_ownership.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart)_ ```dart CometChatTransferOwnership( group: group, -); +) ``` -📄 [`transfer_ownership/cometchat_transfer_ownership.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart) - --- -## Implementation Flow - -1. User creates or joins a group -2. Admin views group info and member list -3. Admin can add, ban, change scope, or transfer ownership - -## Customization Options +## Feature Matrix -- Modify theme using CometChat UIKit theming APIs -- Add logic to validate group name or enforce limits -- Adjust member filters or role options as needed +| Feature | Component / Method | File | +|:---|:---|:---| +| Create group | `CometChatCreateGroup` | [cometchat_create_group.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/create_group/cometchat_create_group.dart) | +| Join group | `JoinProtectedGroupUtils` | [join_protected_group_util.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart) | +| View members | `CometChatGroupInfo` | [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | +| Add members | `CometChatAddMembers` | [cometchat_add_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_memebers/cometchat_add_members.dart) | +| Ban/unban | `CometChatBannedMembers` | [cometchat_banned_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart) | +| Transfer ownership | `CometChatTransferOwnership` | [cometchat_transfer_ownership.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart) | -## Filtering / Edge Cases - -- Filter by roles or banned status -- Prevent duplicate group IDs -- Prevent banning owner or transferring to non-member - -## Error Handling & Blocked Users - -- Show UI feedback (SnackBars) on failure -- Blocked users cannot be added or may be auto-banned -- Retry logic for failed actions (create, join, etc.) - -## Group Type Notes - -- Public: anyone can join -- Password: prompt required -- Private: invite-only -- Only admins can ban, change roles, or transfer ownership - -## Summary / Feature Matrix - -| Feature | Component / Method | File Path | -|---------------------|----------------------------------|-----------------------------------------------------| -| Create group | `CometChatCreateGroup` | `create_group/cometchat_create_group.dart` | -| Join group | `CometChatGroups`, `JoinProtectedGroupUtils` | `contacts/cometchat_contacts_controller.dart`, `utils/join_protected_group_util.dart` | -| View members | `CometChatGroupInfo` | `group_info/cometchat_group_info.dart` | -| Add members | `CometChatAddMembers` | `add_members/cometchat_add_members.dart` | -| Ban/unban members | `CometChatBannedMembers` | `banned_members/cometchat_banned_members.dart` | -| Change scope | `CometChatChangeScope` | `group_info/cometchat_group_info.dart` | -| Transfer ownership | `CometChatTransferOwnership` | `transfer_ownership/cometchat_transfer_ownership.dart` | +--- ## Next Steps - - Learn more about the Groups component + + Learn more about the Groups component. - - Display and manage group members + + Display and manage group members. - - View group conversations + + View group conversations. - - Explore other implementation guides + + Browse all feature and formatter guides. diff --git a/ui-kit/flutter/guide-message-agentic-flow.mdx b/ui-kit/flutter/guide-message-agentic-flow.mdx index 545f64be1..2b3c9144c 100644 --- a/ui-kit/flutter/guide-message-agentic-flow.mdx +++ b/ui-kit/flutter/guide-message-agentic-flow.mdx @@ -1,467 +1,197 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" -description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in your Flutter app" +description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Check if user is an AI agent -bool isUserAgentic() { - return widget.user?.role == AIConstants.aiRole; -} +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatAIAssistantChatHistory`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | AI agent user → `AIAssistantChatScreen` with AI-specific styling | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// AI Assistant chat screen -AIAssistantChatScreen( - user: aiUser, - group: group, - parentMessage: message, - isHistory: true, -); - -// AI chat history -CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () => onNewChatClicked(true), - onMessageClicked: (message) => navigateToThread(message), -); - -// Custom AI bubble styling -CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - border: Border.all(color: Colors.blueAccent), - textColor: Color(0xFF141414), -); -``` + -**Key Components:** -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) -- `CometChatMessageHeader` → [Docs](/ui-kit/flutter/message-header) -- `CometChatAIAssistantChatHistory` → [Docs](/ui-kit/flutter/ai-assistant-chat-history) -- `CometChatAiAssistantBubbleStyle` → AI bubble styling -- `AIConstants.aiRole` → AI role constant +AI Agent Integration enables intelligent conversational AI capabilities with chat history, contextual responses, and seamless handoffs. -**Sample Implementation:** Custom AI Assistant chat screen (see guide for full implementation) - +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. +--- -Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v5 with AI Agent integration: - -- **AI Assistant Chat History** -- **Chat History Management** -- **Contextual Responses** -- **Agent Detection** -- **Seamless Handoffs** - -Transform your chat experience with AI-powered assistance that provides intelligent responses and offers seamless integration with your existing chat infrastructure. - -## Overview - -Users can interact with AI agents through a dedicated chat interface that: - -- Provides intelligent responses based on conversation context. -- Maintains chat history for continuity. -- Seamlessly integrates with your existing user chat system. - -The AI Agent chat interface provides a familiar messaging experience enhanced with AI capabilities, accessible through your main chat flow or as a standalone feature. +## Components - - - +| Component / Class | Role | +|:---|:---| +| `CometChatMessageHeader` | Manages message interactions with AI-specific buttons | +| `CometChatMessageList` | Displays messages with AI-specific styling | +| `CometChatMessageComposer` | Composes messages with AI placeholders | +| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history | +| `CometChatAiAssistantBubbleStyle` | Custom styling for AI chat bubbles | +| `AIConstants.aiRole` | Constant to detect AI agent users | -## Prerequisites +--- -- **CometChat UIKit for Flutter** installed via `pubspec.yaml` -- CometChat initialized with `App ID`, `Region`, and `Auth Key` -- Message chat enabled in your CometChat app -- Navigation set up between message and user/group screens -- Internet permissions +## Integration Steps -## Components +### 1. Detect AI Agent -| Component/Class | Role | -|------------------------------ |------------------------------------------------------| -| `CometChatMessageHeader` | Manages message interactions and state | -| `CometChatMessageList` | Displays a list of messages | -| `CometChatMessageComposer` | Composes and sends new messages | -| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history. | +Check if the user is an AI agent by their role. +```dart +bool isUserAgentic() { + return widget.user?.role == AIConstants.aiRole; +} +``` -## Integration Steps +--- -### Step 1 - Screen Setup +### 2. AI Chat Screen Setup -Create a screen for AI Assistant chat using `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer`. +Create a screen for AI Assistant chat using standard message components with AI-specific styling. - - ```dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart' as cc; - class AIAssistantChatScreen extends StatefulWidget { final User? user; final Group? group; final BaseMessage? parentMessage; final bool? isHistory; - const AIAssistantChatScreen( - {Key? key, this.user, this.group, this.parentMessage, this.isHistory}) - : super(key: key); + const AIAssistantChatScreen({ + Key? key, + this.user, + this.group, + this.parentMessage, + this.isHistory, + }) : super(key: key); @override State createState() => _AIAssistantChatScreenState(); } +``` -class _AIAssistantChatScreenState extends State { - late CometChatColorPalette colorPalette; - late CometChatTypography typography; - late CometChatSpacing spacing; - - @override - void initState() { - super.initState(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - typography = CometChatThemeHelper.getTypography(context); - colorPalette = CometChatThemeHelper.getColorPalette(context); - spacing = CometChatThemeHelper.getSpacing(context); - } - - bool isUserAgentic() { - return widget.user?.role == AIConstants.aiRole; - } +--- - @override - Widget build(BuildContext context) { - final ccColor = CometChatThemeHelper.getColorPalette(context); - return Scaffold( - backgroundColor: ccColor.background1, - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - messageHeaderStyle: CometChatMessageHeaderStyle( - backgroundColor: - (isUserAgentic()) ? ccColor.background1 : null, - border: (isUserAgentic()) - ? Border( - bottom: BorderSide( - color: ccColor.borderLight ?? Colors.transparent, - width: 1.0, - ), - ) - : null, - statusIndicatorStyle: CometChatStatusIndicatorStyle( - backgroundColor: colorPalette.transparent, - borderRadius: BorderRadius.zero, - border: Border.all( - width: 0, - color: colorPalette.transparent ?? Colors.transparent, - ), - ), - ), - onBack: () { - FocusManager.instance.primaryFocus?.unfocus(); - Navigator.of(context).pop(); - }, - chatHistoryButtonClick: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () { - onNewChatClicked(true); - }, - onMessageClicked: (message) { - if (message != null) { - Navigator.of(context) - ..pop() - ..pop(); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( - user: widget.user, - group: widget.group, - parentMessage: message, - isHistory: true, - ), - ), - ); - } - }, - onClose: () { - Navigator.of(context).pop(); - }, - ), - ), - ); - }, - newChatButtonClick: () { - onNewChatClicked(false); - }, - ), - resizeToAvoidBottomInset: true, - body: Container( - color: ccColor.background3, - child: Column( - children: [ - Expanded( - child: GestureDetector( - onTap: () => FocusScope.of(context).unfocus(), - child: getMessageList( - user: widget.user, - group: widget.group, - context: context, - parentMessage: widget.parentMessage, - ), - ), - ), - getComposer(), - ], - ), - ), - ); - ; - } - - Widget getComposer() { - bool agentic = isUserAgentic(); - return CometChatMessageComposer( - user: widget.user, - group: widget.group, - disableMentions: (agentic) ? true : false, - placeholderText: - (agentic) ? "${cc.Translations.of(context).askAnything}..." : null, - parentMessageId: widget.parentMessage?.id ?? 0, - messageComposerStyle: CometChatMessageComposerStyle( - dividerColor: agentic ? Colors.transparent : null, - dividerHeight: agentic ? 0 : null, - backgroundColor: agentic ? colorPalette.background1 : null, - ), - ); - } +### 3. Message Header with AI Actions - onNewChatClicked(bool isHistory) async { - if (isHistory) { - Navigator.of(context).pop(); - } +Configure the message header with chat history and new chat buttons. - Navigator.pushReplacement( +```dart +CometChatMessageHeader( + user: widget.user, + group: widget.group, + chatHistoryButtonClick: () { + Navigator.push( context, MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( + builder: (context) => CometChatAIAssistantChatHistory( user: widget.user, group: widget.group, + onNewChatButtonClicked: () => onNewChatClicked(true), + onMessageClicked: (message) => navigateToThread(message), + onClose: () => Navigator.of(context).pop(), ), ), ); - } - - Widget getMessageList({ - User? user, - Group? group, - context, - BaseMessage? parentMessage, - }) { - MessagesRequestBuilder? requestBuilder = MessagesRequestBuilder(); - - if (widget.isHistory != null && - widget.isHistory == true && - parentMessage != null && - isUserAgentic()) { - requestBuilder = MessagesRequestBuilder() - ..parentMessageId = parentMessage.id - ..withParent = true - ..hideReplies = true; - } - - return CometChatMessageList( - user: user, - group: group, - hideReplyInThreadOption: (isUserAgentic()) ? true : false, - hideThreadView: true, - messagesRequestBuilder: requestBuilder, - style: CometChatMessageListStyle( - backgroundColor: (isUserAgentic()) ? colorPalette.background3 : null, - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: - (isUserAgentic()) ? colorPalette.background4 : null, - textColor: (isUserAgentic()) ? colorPalette.textPrimary : null, - messageBubbleDateStyle: CometChatDateStyle( - textColor: (isUserAgentic()) ? colorPalette.neutral600 : null, - ), - ), - messageBubbleDateStyle: CometChatDateStyle( - textColor: (isUserAgentic()) ? colorPalette.textPrimary : null, - ), - ), - ), - ); - } -} + }, + newChatButtonClick: () => onNewChatClicked(false), +) ``` - - - - - -### Step 2 - Chat History Screen +--- -Create a screen for AI Assistant chat history using CometChatAIAssistantChatHistory. +### 4. AI Message List -Add the following code inside your widget to navigate to the chat history screen when the user taps a button or icon. +Configure the message list with AI-specific styling and options. - - ```dart -chatHistoryButtonClick: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () { - onNewChatClicked(true); - }, - onMessageClicked: (message) { - if (message != null) { - Navigator.of(context) - ..pop() // Close ChatHistory - ..pop(); // Close current AI screen - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( - user: widget.user, - group: widget.group, - parentMessage: message, - isHistory: true, - ), - ), - ); - } - }, - onClose: () { - Navigator.of(context).pop(); - }, +CometChatMessageList( + user: user, + group: group, + hideReplyInThreadOption: isUserAgentic() ? true : false, + hideThreadView: true, + messagesRequestBuilder: requestBuilder, + style: CometChatMessageListStyle( + backgroundColor: isUserAgentic() ? colorPalette.background3 : null, + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: isUserAgentic() ? colorPalette.background4 : null, + textColor: isUserAgentic() ? colorPalette.textPrimary : null, ), ), - ); -}, + ), +) ``` - - - - -This integration opens the AI Assistant Chat History screen, allowing users to: -- Browse their previous AI chat sessions. -- Resume a previous conversation (onMessageClicked). -- Start a new chat session (onNewChatButtonClicked). -- Close the chat history view (onClose). - -### Step 3 - Custom Styles +--- -Define custom styles for AI chat bubbles and the composer by using a ThemeExtension (CometChatAiAssistantBubbleStyle). +### 5. AI Composer +Configure the composer with AI-specific placeholder text. - - ```dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'AI Chat Demo', - theme: ThemeData( - // Add your custom AI Assistant bubble styles here - extensions: [ - CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - border: Border.all(color: Colors.blueAccent, width: 1), - textColor: const Color(0xFF141414), - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - ), - ], - ), - home: const AIAssistantChatScreen(), - ); - } -} +CometChatMessageComposer( + user: widget.user, + group: widget.group, + disableMentions: isUserAgentic() ? true : false, + placeholderText: isUserAgentic() + ? "${Translations.of(context).askAnything}..." + : null, + parentMessageId: widget.parentMessage?.id ?? 0, +) ``` - - - +--- -## Implementation Flow Summary +### 6. Custom AI Bubble Styling -| Step | Action | -|:-----|:-------------------------------------------- | -| 1 | User selects AI agent from chat list | -| 2 | `AIAssistantChatScreen` launches | -| 3 | Parse User data and detect agent chat (Role of user must be "@agentic") | -| 4 | Initialize UI with AI-specific styling | -| 6 | Configure chat history and navigation | -| 7 | Launch chat with AI agent | +Apply custom styles for AI chat bubbles using ThemeExtension. -## Customization Options +```dart +MaterialApp( + theme: ThemeData( + extensions: [ + CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + border: Border.all(color: Colors.blueAccent, width: 1), + textColor: const Color(0xFF141414), + ), + ], + ), +) +``` -- **Custom AI Assistant Empty Chat View:** Customize the empty state view using `emptyStateView`. -- **Streaming Speed:** Adjust AI response streaming speed via `streamingSpeed`. -- **AI Assistant Suggested Messages:** Create custom list of suggested messages and set quick prompts using `suggestedMessages`. -- **AI Assistant Tools:** Set tools for the AI agent using `setAiAssistantTools` callback. +--- ## Feature Matrix -| Feature | Implementation | UI Component | -|:-----------------------|:-------------------------------------------- |:------------------------| -| AI Chat | `AIAssistantChatScreen` | Full chat screen | -| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | +| Feature | Component / Method | Description | +|:---|:---|:---| +| AI detection | `AIConstants.aiRole` | Check if user is AI agent | +| AI chat screen | `AIAssistantChatScreen` | Full AI chat interface | +| Chat history | `CometChatAIAssistantChatHistory` | Browse previous AI sessions | +| AI styling | `CometChatAiAssistantBubbleStyle` | Custom AI bubble appearance | +| New chat | `onNewChatClicked()` | Start fresh AI conversation | --- ## Next Steps - - Explore all AI-powered features + + Explore all AI-powered features. - - Learn about message display and management + + Learn about AI chat history component. - - Compose messages with AI assistance + + Learn about message display and management. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-message-privately.mdx b/ui-kit/flutter/guide-message-privately.mdx index 245dbbf32..647f90925 100644 --- a/ui-kit/flutter/guide-message-privately.mdx +++ b/ui-kit/flutter/guide-message-privately.mdx @@ -1,163 +1,151 @@ --- -title: "Message a User Privately from a Group Chat" +title: "Message Privately" sidebarTitle: "Message Privately" -description: "Initiate private one-on-one chats with group members directly from group chat" +description: "Initiate private one-on-one chats with group members directly from group chat in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Navigate to user info from group chat -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUserInfo(user: user), - ), - ); - }, -); - -// Start private chat with user -ElevatedButton( - onPressed: () { - PageManager().navigateToMessages( - context: context, - user: user, - ); - }, - child: Text('Message'), -); -``` +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometchatUserInfo`, `CometChatMessageList`, `PageManager` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Group member tap → `CometchatUserInfo` → "Message" action | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Key Components:** -- `CometChatUserInfo` → User profile screen -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `PageManager` → Navigation utility (sample app) + -**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) - +Message Privately lets users start a direct one-on-one chat with a group member without leaving the group context. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Learn how to initiate a private one-on-one chat with a group member directly from a group chat screen. - -## Overview +--- -This feature allows users to start a private, direct chat with a member of a group without leaving the group chat context. It enables seamless, context-aware private conversations, improving collaboration and user experience. Users can tap on a group member to instantly open a private chat. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatMessageList` | Displays group messages and user avatars | +| `CometchatUserInfo` | Shows user details and actions (e.g., call, message) | +| `CometChatUserInfoController` | Manages user info state and actions | +| `PageManager` | Handles navigation to the private chat screen | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Group chat and user info screens implemented -- Navigation setup for moving between group and private chat screens +--- -## Components +## Integration Steps -| Component / Class | Role | -|:-------------------------------------|:---------------------------------------------------------------| -| `CometChatMessageList` | Displays group messages and user avatars | -| `CometChatUserInfo` | Shows user details and actions (e.g., "Message" button) | -| `PageManager` | Handles navigation to the private chat screen | -| `lib/messages.dart` | Main chat screen logic | -| `lib/user_info/cometchat_user_info.dart` | User info and action UI | +### 1. Navigate to User Info -## Integration Steps +Open the user info screen when tapping on a group member's profile or info icon. -### Add User Info/Action in Group Chat +_File: [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart)_ -Allow users to view group member info and provide a "Message" action. ```dart -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUserInfo(user: user), - ), - ); - }, +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometchatUserInfo(user: selectedUser), + ), ); ``` -**File reference:** -[`lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) +--- + +### 2. Display User Profile with Actions + +The `CometchatUserInfo` widget displays the user's profile with action tiles for voice call, video call, and messaging. -### Handle Private Message Navigation +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -Start a private chat with the selected user. ```dart -ElevatedButton( - onPressed: () { - PageManager().navigateToMessages( - context: context, - user: user, - ); - }, - child: Text('Message'), -); +Widget _getOptionTiles(CometChatUserInfoController controller) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + tile( + Icon(Icons.call_outlined, color: colorPalette.iconHighlight), + Translations.of(context).voice, + () => controller.initiateCallWorkflow(CallTypeConstants.audioCall, context), + ), + tile( + Icon(Icons.videocam_outlined, color: colorPalette.iconHighlight), + Translations.of(context).video, + () => controller.initiateCallWorkflow(CallTypeConstants.videoCall, context), + ), + ], + ); +} ``` -**File reference:** -[`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -## Implementation Flow +### 3. Start Private Chat -1. User taps a group member’s avatar or info icon -2. `CometChatUserInfo` screen opens -3. User taps "Message" -4. App navigates to the private chat screen with that user +Navigate to the private chat screen using `PageManager` when the user wants to message privately. -## Customization Options +_File: [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart)_ -- **Styling:** Customize the user info screen and action buttons using UIKit theming -- **APIs:** Add more actions (e.g., block, view profile) in the user info screen -- **Configuration:** Control which users can be messaged (e.g., block list, admin-only) +```dart +PageManager().navigateToMessages( + context: context, + user: user, +); +``` -## Filtering / Edge Cases +--- -- **Exclude Blocked Users:** Remove blocked users from selection -- **Existing Conversation:** Navigate to an existing private chat if one exists -- **User Blocked:** Disable the "Message" button if the user is blocked +### 4. Handle Mentions Navigation -## Error Handling & Blocked-User-Handling +When a user taps on a mention in a message, navigate to that user's profile or start a private chat. -- **UI States:** Disable the message button and show a tooltip if a user is blocked -- **Feedback:** Use `SnackBar` or `Toast` for error messages (e.g., "Cannot message this user") -- **Retry Logic:** Allow retrying navigation if a network error occurs +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -## Optional Context-Specific Notes +```dart +CometChatMentionsFormatter getMentionsTap() { + return CometChatMentionsFormatter( + user: widget.user, + group: widget.group, + onMentionTap: (mention, mentionedUser, {message}) { + if (mentionedUser.uid != CometChatUIKit.loggedInUser!.uid) { + PageManager().navigateToMessages( + context: context, + user: mentionedUser, + ); + } + }, + ); +} +``` -- **Group vs. User:** This flow applies only to group members; use the standard new chat flow for users outside the group +--- + +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| User info screen | `CometchatUserInfo` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Voice/video call | `initiateCallWorkflow()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Navigate to chat | `PageManager.navigateToMessages` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +| Mention tap | `CometChatMentionsFormatter` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Access from group | Group member list | [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | -| Feature | Component / Method | File(s) | -|:------------------------|:---------------------------------|:---------------------------------------------------------------------| -| Show user info | `CometChatUserInfo` | [`lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | -| Message user | `PageManager.navigateToMessages` | [`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | -| Access from group | Avatar/IconButton | [`lib/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | +--- ## Next Steps - - Display and manage group lists + + Display and manage group lists. - - View and manage group members + + View and manage group members. - - Display messages in private chats + + Display messages in private chats. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-new-chat.mdx b/ui-kit/flutter/guide-new-chat.mdx index c337f3fce..48027ccc3 100644 --- a/ui-kit/flutter/guide-new-chat.mdx +++ b/ui-kit/flutter/guide-new-chat.mdx @@ -1,83 +1,50 @@ --- -title: "New Chat / Create Conversation in Your Flutter Chat App" +title: "New Chat" sidebarTitle: "New Chat" -description: "Enable users to start one-on-one or group chats with a searchable contact list" +description: "Enable users to start one-on-one or group chats with a searchable contact list in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Add avatar menu with "Create Conversation" option -PopupMenuButton( - icon: CometChatAvatar( - image: CometChatUIKit.loggedInUser?.avatar, - name: CometChatUIKit.loggedInUser?.name, - ), - itemBuilder: (context) => [ - PopupMenuItem(value: '/Create', child: Text("Create Conversation")), - ], - onSelected: (value) { - if (value == '/Create') { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => CometChatContacts()), - ); - } - }, -); - -// Handle user/group selection -CometChatUsers( - onItemTap: (context, user) => PageManager.navigateToMessages(context: context, user: user), -); -``` +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatContacts`, `CometChatUsers`, `CometChatGroups`, `CometChatAvatar` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Avatar menu → "Create Conversation" → `CometChatContacts` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Key Components:** -- `CometChatAvatar` → Avatar display widget -- `CometChatContacts` → Contact selection screen -- `CometChatUsers` → [Docs](/ui-kit/flutter/users) -- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) -- `CometChatContactsController` → Tab switching controller (sample app) + -**Sample Implementation:** [contacts/cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) - +New Chat enables users to start one-on-one or group conversations by selecting from a searchable contact list. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Enable users to start one-on-one or group chats by integrating CometChat’s avatar menu and `CometChatContacts` screen, providing a seamless flow from the dashboard to a conversation. - -## Overview +--- -- Users can start a new one-on-one or group chat by tapping the avatar in the top bar, selecting “Create Conversation,” and choosing a contact from a searchable list. -- Streamlines finding contacts or groups and initiating conversations, improving user experience and engagement. -- Quick creation or opening of chats directly from the main screen. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatAvatar` | Displays the user avatar in the app bar | +| `PopupMenuButton` | Shows menu options when the avatar is tapped | +| `CometChatContacts` | UI for the "Start Conversation" screen with tabs | +| `CometChatContactsController` | Manages tab switching and item selection | +| `CometChatUsers` | Lists users with search and selection | +| `CometChatGroups` | Lists groups with search and selection | +| `PageManager` | Handles navigation to the chat screen | -- Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Navigation configured in your app -- Internet/network permissions granted +--- -## Components +## Integration Steps -| Component / Class | Role | -|:-------------------------------|:--------------------------------------------------------------| -| `CometChatAvatar` | Displays the user avatar in the app bar | -| `PopupMenuButton` | Shows menu options when the avatar is tapped | -| `CometChatContacts` | UI for the “Start Conversation” screen | -| `CometChatContactsController` | Manages tab switching and item selection | -| `CometChatUsers` / `CometChatGroups` | Lists users or groups with search and selection | -| `PageManager` | Handles navigation to the chat screen | +### 1. Add Avatar Menu -## Integration Steps +Show the avatar in the app bar and open a menu on tap with "Create Conversation" option. -### Add Avatar Menu +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Show the avatar in the app bar and open a menu on tap. ```dart PopupMenuButton( icon: CometChatAvatar( @@ -90,17 +57,24 @@ PopupMenuButton( PopupMenuItem(value: '/Create', child: Text("Create Conversation")), ], onSelected: (value) { - if (value == '/Create') openCreateConversation(context); + if (value == '/Create') { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatContacts()), + ); + } }, ); ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 2. Open Contacts Screen -### Open Start Conversation Screen +Navigate to the `CometChatContacts` screen which provides tabs for Users and Groups. + +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Navigate to the “Start Conversation” screen when “Create Conversation” is selected. ```dart void openCreateConversation(BuildContext context) { Navigator.push( @@ -110,33 +84,34 @@ void openCreateConversation(BuildContext context) { } ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 3. Handle User/Group Selection + +Wire up the `onItemTap` callback to navigate to the chat screen when a user or group is selected. -### Select User or Group +_File: [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart)_ -Let the user pick a contact or group to chat with. ```dart -CometChatContactsController( - currentView: [ - CometChatUsers( - hideAppbar: true, - onItemTap: (context, user) => _onItemTap(context: context, user: user), - ), - CometChatGroups( - hideAppbar: true, - onItemTap: (context, group) => _onItemTap(context: context, group: group), - ), - ], +CometChatUsers( + hideAppbar: true, + onItemTap: (context, user) => _onItemTap(context: context, user: user), +); + +CometChatGroups( + hideAppbar: true, + onItemTap: (context, group) => _onItemTap(context: context, group: group), ); ``` -**File reference:** -[`sample_app/lib/contacts/cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) +--- + +### 4. Navigate to Chat + +Open the chat screen for the selected user or group using `PageManager`. -### Navigate to Chat +_File: [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart)_ -Open the chat screen for the selected user or group. ```dart void _onItemTap({required BuildContext context, User? user, Group? group}) { if (user != null) { @@ -147,62 +122,34 @@ void _onItemTap({required BuildContext context, User? user, Group? group}) { } ``` -**File reference:** -[`sample_app/lib/utils/page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) - -## Implementation Flow - -1. User taps avatar → menu opens -2. User selects “Create Conversation” → navigates to `CometChatContacts` -3. User searches and selects a user or group → triggers `_onItemTap` -4. App navigates to the chat screen for the selected user or group - -## Customization Options - -- **Styling:** Customize avatar, menu, and contact list appearance via UIKit theming -- **APIs:** Use callbacks like `onSearch` and `onItemTap` for custom logic -- **Configuration:** Adjust tab visibility, search placeholder, or add custom menu actions - -## Filtering / Edge Cases - -- **Filtering:** `CometChatUsers` and `CometChatGroups` provide real-time search -- **Empty Results:** Display an empty state if no matches are found -- **Blocked Users:** Exclude blocked users from search and messaging - -## Error Handling & Blocked-User Handling - -- **UI States:** Default UIKit states handle network errors or empty results -- **Feedback:** Use `SnackBar` or `Toast` for custom error messages -- **Blocked Users:** Blocked users cannot be selected or messaged - -## Optional Context-Specific Notes +--- -- **User vs. Group:** The flow is identical; only the data source changes +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Avatar menu | `PopupMenuButton`, `CometChatAvatar` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Contacts screen | `CometChatContacts` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| List users | `CometChatUsers` | [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | +| List groups | `CometChatGroups` | [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | +| Handle selection | `_onItemTap` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +| Navigate to chat | `PageManager.navigateToMessages` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -| Feature | Component / Method | File(s) | -|------------------------|-------------------------------------------------|-------------------------------------------------| -| Show avatar/menu | `PopupMenuButton`, `CometChatAvatar` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Open conversation UI | `CometChatContacts` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| List/search users | `CometChatUsers` | [`cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | -| List/search groups | `CometChatGroups` | [`cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | -| Handle selection | `_onItemTap` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -| Navigate to chat | `PageManager.navigateToMessages` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +--- ## Next Steps - - Display and search user lists + + Display and search user lists. - - Display and manage group lists + + Display and manage group lists. - - View and manage conversation history + + View and manage conversation history. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 0cecb9a9c..46f3dc93b 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -4,32 +4,17 @@ sidebarTitle: "Overview" description: "Task-oriented feature guides for implementing specific capabilities in the Flutter UI Kit" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -Available implementation guides for Flutter UI Kit: +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Purpose | Index of task-oriented feature guides for the Flutter UI Kit | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Components | [Components Overview](/ui-kit/flutter/components-overview) | +| Guides | [Block/Unblock](/ui-kit/flutter/guide-block-unblock-user) · [Call Log Details](/ui-kit/flutter/guide-call-log-details) · [Group Chat](/ui-kit/flutter/guide-group-chat) · [Message Privately](/ui-kit/flutter/guide-message-privately) · [New Chat](/ui-kit/flutter/guide-new-chat) · [Search Messages](/ui-kit/flutter/guide-search-messages) · [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) · [AI Agent](/ui-kit/flutter/guide-message-agentic-flow) | -**Feature Guides:** -- [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) → `CometChatThreadedMessageList` -- [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` -- [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` -- [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` -- [Search Messages](/ui-kit/flutter/guide-search-messages) → `CometChatSearch` -- [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` -- [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` -- [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` - -**Formatter Guides:** -- [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) → `CometChatTextFormatter` -- [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) → `CometChatMentionsFormatter` -- [URL Formatter](/ui-kit/flutter/url-formatter-guide) → `CometChatUrlFormatter` -- [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) → `ShortcutFormatter` - -**Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - -Each guide provides end-to-end implementation with code examples and component references. - + This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. diff --git a/ui-kit/flutter/guide-threaded-messages.mdx b/ui-kit/flutter/guide-threaded-messages.mdx index 510f2dc63..967135bdc 100644 --- a/ui-kit/flutter/guide-threaded-messages.mdx +++ b/ui-kit/flutter/guide-threaded-messages.mdx @@ -1,212 +1,194 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" -description: "Enable threaded replies in your Flutter chat app with focused sub-conversations" +description: "Implement threaded message replies with parent context, reply list, and focused thread composer in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatThread`, `CometChatThreadedHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | `CometChatMessageList.onThreadRepliesClick` opens thread view from messages | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// Enable thread replies in message list -CometChatMessageList( - onThreadRepliesClick: (BaseMessage message) { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatThread(parentMessage: message), - ), - ); - }, -); - -// Display threaded messages -CometChatThreadedMessageList( - parentMessageId: parentMessage.id, -); + -// Send threaded reply -CometChatMessageComposer( - parentMessageId: parentMessage.id, -); -``` +Threaded messages let users create sub-conversations by replying to specific messages. This reduces clutter and keeps discussions focused. -**Key Components:** -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `CometChatThreadedMessageList` → Displays threaded messages -- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) -- `CometChatThreadedHeader` → [Docs](/ui-kit/flutter/threaded-messages-header) +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -**Sample Implementation:** [thread_screen/cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) - - - -Enhance your Flutter chat app with threaded messaging by integrating CometChat’s `CometChatThreadedMessageList` and `CometChatMessageList` components to reply to messages in threads and view focused sub-conversations seamlessly. - -## Overview +--- -The sample app demonstrates how to enable threaded messaging in Flutter using CometChat’s UI Kit: +## Components -- Reply to specific messages to start focused sub-conversations. -- View all replies grouped under the parent message. -- Seamlessly switch back to the main conversation. +| Component / Class | Role | +|:---|:---| +| `CometChatThread` | Main container widget for threaded messages | +| `CometChatThreadedHeader` | Displays parent message and thread context | +| `CometChatMessageList` | Shows messages filtered by `parentMessageId` | +| `CometChatMessageComposer` | Input for composing threaded replies | +| `MessagesRequestBuilder` | Builds request to fetch thread replies | -## Prerequisites +--- -- A Flutter project with **CometChat UIKit Flutter v5** installed. -- Initialized CometChat credentials (`appID`, `region`, `authKey`). - -## Components +## Integration Steps -| Component | Role | -|:-----------------------------------|:-------------------------------------------------------------| -| `CometChatMessageList` | Displays main chat; provides `onThreadRepliesClick` callback.| -| `CometChatThreadedMessageList` | Fetches and displays replies for a parent message. | -| `CometChatMessageComposer` | Sends new messages; pass `parentMessageId` to send replies. | -| `CometChatThreadedHeader` | Shows the parent message and thread context at the top. | +### 1. Thread Trigger in Messages -## Integration Steps +Wire the `onThreadRepliesClick` callback on `CometChatMessageList`. When a user clicks the thread reply icon on any message, this fires with the parent message object. -### Show the “Reply in Thread” Option +_File: [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart)_ -Trigger thread view when tapping the thread icon. ```dart CometChatMessageList( onThreadRepliesClick: (BaseMessage message) { Navigator.push( context, MaterialPageRoute( - builder: (_) => CometChatThread(parentMessage: message), + builder: (_) => CometChatThread( + message: message, + user: user, + group: group, + ), ), ); }, - // …other props ); ``` -**File reference:** -[`sample_app/lib/messages/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) +--- -Captures the user's intent to view or add to a thread. +### 2. Thread Screen Widget -### Navigate to the Thread Screen +Create the thread screen with header, message list, and composer. The `CometChatThread` widget handles the complete thread UI. -Display a dedicated thread view. -```dart -class CometChatThread extends StatelessWidget { - final BaseMessage parentMessage; +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ - CometChatThread({required this.parentMessage}); +```dart +class CometChatThread extends StatefulWidget { + const CometChatThread({ + this.user, + this.group, + required this.message, + super.key, + }); + + final User? user; + final Group? group; + final BaseMessage message; @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: Text("Thread")), - body: Column( - children: [ - CometChatThreadedHeader(message: parentMessage), - Expanded( - child: CometChatThreadedMessageList( - parentMessageId: parentMessage.id, - ), - ), - CometChatMessageComposer( - parentMessageId: parentMessage.id, - ), - ], - ), - ); - } + State createState() => _CometChatThreadState(); } ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) +--- + +### 3. Thread Header and Message List -Provides a focused UI for thread interactions. +Display the parent message context and threaded replies using `CometChatThreadedHeader` and `CometChatMessageList` with `parentMessageId`. -### Send a Threaded Message +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -Send replies in the context of a thread. ```dart -CometChatMessageComposer( - parentMessageId: parentMessage.id, - // …other composer props -); +Column( + children: [ + CometChatThreadedHeader( + parentMessage: widget.message, + loggedInUser: CometChatUIKit.loggedInUser!, + ), + Expanded( + child: CometChatMessageList( + user: widget.user, + group: widget.group, + messagesRequestBuilder: MessagesRequestBuilder() + ..parentMessageId = widget.message.id, + ), + ), + ], +) ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) +--- -Automatically associates new messages with the parent thread. +### 4. Thread Composer -### Fetch & Display Thread Replies +Add the message composer with `parentMessageId` to send replies in the thread context. -Retrieve and show all replies under a parent message. -```dart -MessagesRequest request = MessagesRequestBuilder() - .setParentMessageId(parentMessageId) - .build(); +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -request.fetchPrevious().then((replies) { - // Render these replies in the list -}); +```dart +CometChatMessageComposer( + user: widget.user, + group: widget.group, + parentMessageId: widget.message.id, +) ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) - -Ensures only relevant threaded messages are shown. - -## Customization Options - -- **Header Styling:** Customize `CometChatThreadedHeader` appearance (colors, fonts). -- **List Pagination:** Adjust `limit` in `MessagesRequestBuilder`. -- **Composer Placeholder:** Change placeholder text based on thread context. +--- -## Filtering / Edge Cases +### 5. Blocked User Handling -- **Parent Deleted:** Show a fallback message or disable composer if parent is deleted. -- **No Replies:** Display an empty state (e.g., “No replies yet”). -- **Offline Mode:** Queue thread operations or show connectivity indicators. +When a user is blocked, replace the composer with an unblock prompt. -## Error Handling & Edge Cases +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -- **Fetch Failures:** Show error UI with retry option on `fetchPrevious` errors. -- **Send Failures:** Display SnackBar on composer send errors; allow retry. -- **Loading States:** Show loading indicators during fetch/send operations. +```dart +Widget getComposer(CometChatThreadController controller) { + if (controller.user?.blockedByMe == true) { + return Container( + padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20), + child: Column( + children: [ + Text(Translations.of(context).cantSendMessageBlockedUser), + ElevatedButton( + onPressed: () => controller.unBlockUser(), + child: Text(Translations.of(context).unBlock), + ), + ], + ), + ); + } + return CometChatMessageComposer( + user: widget.user, + group: widget.group, + parentMessageId: widget.message.id, + ); +} +``` -## Optional Context-Specific Notes +--- -- **Group vs. Direct Threads:** Threads work the same for groups and 1:1 chats. -- **Blocked Users:** Threading respects block state; blocked users cannot send replies. +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Show thread option | `onThreadRepliesClick` | [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | +| Thread screen | `CometChatThread` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Thread header | `CometChatThreadedHeader` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Display thread msgs | `CometChatMessageList` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Compose reply | `CometChatMessageComposer` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Thread controller | `CometChatThreadController` | [cometchat_thread_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread_controller.dart) | -| Feature | Component / Method | -|:------------------------------|:-----------------------------------------------| -| Show thread option | `CometChatMessageList.onThreadRepliesClick` | -| Thread view screen | `CometChatThread` widget | -| Display threaded messages | `CometChatThreadedMessageList(parentMessageId)`| -| Send threaded message | `CometChatMessageComposer(parentMessageId)` | -| Fetch thread replies | `MessagesRequestBuilder.setParentMessageId` | +--- ## Next Steps - - Display and manage conversation messages + + Render real-time message threads. - - Compose and send messages with threading support + + Customize the thread header component. - - Display thread context and parent message + + Browse all feature and formatter guides. - - Explore other implementation guides + + Full working sample application on GitHub. - \ No newline at end of file + diff --git a/ui-kit/flutter/mentions-formatter-guide.mdx b/ui-kit/flutter/mentions-formatter-guide.mdx index 97a49cfed..b5977e760 100644 --- a/ui-kit/flutter/mentions-formatter-guide.mdx +++ b/ui-kit/flutter/mentions-formatter-guide.mdx @@ -1,7 +1,21 @@ --- title: "Mentions Formatter" +description: "Add @mentions with user suggestions and styled tokens in CometChat Flutter UI Kit." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatMentionsFormatter` (extends `CometChatTextFormatter`) | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Purpose | Add @mentions with user suggestions, styled tokens, and click handling | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) · [All Guides](/ui-kit/flutter/guide-overview) | + + + ## Overview The `CometChatMentionsFormatter` class is a part of the CometChat UI Kit, a ready-to-use chat UI widget library for integrating CometChat into your Android applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. diff --git a/ui-kit/flutter/shortcut-formatter-guide.mdx b/ui-kit/flutter/shortcut-formatter-guide.mdx index cae25ad9e..e5c79f044 100644 --- a/ui-kit/flutter/shortcut-formatter-guide.mdx +++ b/ui-kit/flutter/shortcut-formatter-guide.mdx @@ -1,7 +1,21 @@ --- title: "Shortcut Formatter" +description: "Provide !shortcut style expansions invoking extension APIs or dialogs before inserting content in CometChat Flutter UI Kit." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `ShortcutFormatter` (extends `CometChatTextFormatter`) | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Purpose | Provide !shortcut style expansions invoking extension APIs | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) · [All Guides](/ui-kit/flutter/guide-overview) | + + + ## Introduction The `ShortcutFormatter` class extends the `CometChatTextFormatter` class to provide a mechanism for handling shortcuts within messages. This guide will walk you through the process of using ShortcutFormatter to implement shortcut extensions in your CometChat application. From 39f30310951f1caccdebe690f262a353243c0447 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:28:05 +0530 Subject: [PATCH 21/32] updates Reference { "group": "Reference", "pages": [ "ui-kit/flutter/methods", "ui-kit/flutter/events" ] }, --- ui-kit/flutter/events.mdx | 15 +++ ui-kit/flutter/methods.mdx | 259 ++++++++++++++++++++++++++++++------- 2 files changed, 226 insertions(+), 48 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 4d99da659..022885d91 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -3,6 +3,21 @@ title: "Events" description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | +| User events | `ccUserBlocked`, `ccUserUnblocked` | +| Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccReplyToMessage`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, plus SDK listener events | +| Call events | `ccOutgoingCall`, `ccCallAccepted`, `ccCallRejected`, `ccCallEnded` | +| UI events | `ccActiveChatChanged`, `showPanel`, `hidePanel`, `openChat`, `ccComposeMessage`, `onAiFeatureTapped` | +| Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | + + + {/* TL;DR for Agents and Quick Reference */} **Quick Reference for AI Agents & Developers** diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index bed14c418..222a617cf 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -1,7 +1,25 @@ --- title: "Methods" +description: "Reference for CometChat Flutter UI Kit methods including init, login, logout, and message-sending wrappers." --- + + +| 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 | + + + ## 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. @@ -20,10 +38,16 @@ As a developer, you need to invoke this method every time before you use any oth 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. + -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. + +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](#login-using-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`. @@ -51,20 +75,24 @@ The concluding code block: -```dart +```dart highlight={3-5} 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 + ..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 { - // TODO("Not yet implemented") -}, onError: (error) { - // TODO("Not yet implemented") -}); +CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) async { + // Initialization successful, proceed to login + }, + onError: (error) { + // Handle initialization error + }, +); ``` @@ -79,12 +107,18 @@ Only the `UID` of a user is needed to log in. This simple authentication procedu -```dart -CometChatUIKit.login(uid, onSuccess: (s) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +```dart highlight={1} +String uid = "user1"; + +CometChatUIKit.login( + uid, + onSuccess: (user) { + // Login successful, mount your app + }, + onError: (e) { + // Handle login error + }, +); ``` @@ -95,7 +129,7 @@ CometChatUIKit.login(uid, onSuccess: (s) { ### Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +Production-safe authentication that does not expose the Auth Key in client code. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. @@ -105,12 +139,18 @@ This advanced authentication procedure does not use the Auth Key directly in you -```dart -CometChatUIKit.loginWithAuthToken("authToken", onSuccess: (user) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +```dart highlight={1} +String authToken = "AUTH_TOKEN"; + +CometChatUIKit.loginWithAuthToken( + authToken, + onSuccess: (user) { + // Login successful, mount your app + }, + onError: (e) { + // Handle login error + }, +); ``` @@ -351,16 +391,53 @@ CometChatUIKit.init( #### Text Message -As a developer, if you need to send a text message to a single user or a group, you'll need to utilize the `sendMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object. - -```dart -CometChatUIKit.sendTextMessage(textMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1-2} +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 + }, +); +``` + + + + +```dart highlight={1-2} +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 + }, +); ``` @@ -371,16 +448,55 @@ CometChatUIKit.sendTextMessage(textMessageObject, onSuccess: (p0) { #### Media Message -As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object. - -```dart -CometChatUIKit.sendMediaMessage(mediaMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1-2} +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 + }, +); +``` + + + + +```dart highlight={1-2} +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 + }, +); ``` @@ -391,16 +507,63 @@ CometChatUIKit.sendMediaMessage(mediaMessageObject, onSuccess: (p0) { #### Custom Message -As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object. - -```dart -CometChatUIKit.sendCustomMessage(customMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1,3-4} +String receiverID = "UID"; +Map 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 + }, +); +``` + + + + +```dart highlight={1,3-4} +String receiverID = "GUID"; +Map 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 + }, +); ``` From cc08203b2f9ce5d91cc156543933be3b8563d4a7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:36:12 +0530 Subject: [PATCH 22/32] updates features --- ui-kit/flutter/ai-features.mdx | 49 ++------ ui-kit/flutter/call-features.mdx | 55 +++------ ui-kit/flutter/core-features.mdx | 29 ++--- ui-kit/flutter/extensions.mdx | 190 ++++++++++++++++++++++--------- 4 files changed, 169 insertions(+), 154 deletions(-) diff --git a/ui-kit/flutter/ai-features.mdx b/ui-kit/flutter/ai-features.mdx index 8ffcac57f..034555fd8 100644 --- a/ui-kit/flutter/ai-features.mdx +++ b/ui-kit/flutter/ai-features.mdx @@ -1,44 +1,21 @@ --- title: "AI Features" +sidebarTitle: "Smart Chat" description: "Enhance user interaction with AI-powered conversation starters, smart replies, and conversation summaries in your Flutter app" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Enable AI features in UIKitSettings -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..aiFeature = [ - AISmartRepliesExtension(), - AIConversationStarterExtension(), - AIAssistBotExtension(), - AIConversationSummaryExtension() - ] -).build(); - -// Initialize with AI features -CometChatUIKit.init(uiKitSettings: uiKitSettings); -``` - -**Key AI Extensions:** -- `AISmartRepliesExtension` → Smart reply suggestions -- `AIConversationStarterExtension` → Conversation starters -- `AIAssistBotExtension` → AI assistant bot -- `AIConversationSummaryExtension` → Conversation summaries - -**Components:** -- Conversation Starters → Auto-displayed in `CometChatMessageList` ([Docs](/ui-kit/flutter/message-list)) -- Smart Replies → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) -- Conversation Summary → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` + AI features enabled in [CometChat Dashboard](/fundamentals/ai-user-copilot/overview) | +| AI features | Conversation Starter, Smart Replies, Conversation Summary, AI Assist Bot | +| Key components | `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list) (Conversation Starter), `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer) (Smart Replies, Summary) | +| AI Extensions | `AISmartRepliesExtension()`, `AIConversationStarterExtension()`, `AIAssistBotExtension()`, `AIConversationSummaryExtension()` | +| Activation | Enable each AI feature from the CometChat Dashboard — UI Kit auto-integrates them after configuration | -Activate features from [CometChat Dashboard](https://app.cometchat.com) → Extensions → AI - - -## Overview + CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the Flutter UI Kit achieves these features. @@ -46,10 +23,6 @@ CometChat's AI capabilities greatly enhance user interaction and engagement in y - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) - - *** ## Usage diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index 2322a5c28..dd278bde9 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -1,53 +1,24 @@ --- title: "Call Features" +sidebarTitle: "Calls" description: "Integrate one-on-one and group audio/video calling capabilities into your Flutter app with CometChat UI Kit" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; - -// Enable calling features in UIKitSettings -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "APP_ID" - ..authKey = "AUTH_KEY" - ..region = "REGION" - ..callingExtension = CometChatCallingExtension() -).build(); - -// Initialize with calling support -CometChatUIKit.init(uiKitSettings: uiKitSettings); - -// Set navigation key for incoming calls -CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey) - -// Add call listener -CometChat.addCallListener(listenerId, this); -``` - -**Key Calling Components:** -- `CometChatCallButtons` → [Docs](/ui-kit/flutter/call-buttons) -- `CometChatIncomingCall` → [Docs](/ui-kit/flutter/incoming-call) -- `CometChatOutgoingCall` → [Docs](/ui-kit/flutter/outgoing-call) -- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) -- `CometChatCallingExtension` → Calling extension -- `CallNavigationContext` → Navigation context for calls - -**Requirements:** `cometchat_calls_uikit` package, minSdkVersion 24 (Android), iOS 12+ - - -## Overview +| Field | Value | +| --- | --- | +| Packages | `cometchat_chat_uikit` + `cometchat_calls_uikit` (add to `pubspec.yaml`) | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` — Calls SDK must also be installed | +| Call features | Incoming Call, Outgoing Call, Call Logs, Call Buttons | +| Key components | `CometChatCallButtons` → [Call Buttons](/ui-kit/flutter/call-buttons), `CometChatIncomingCall` → [Incoming Call](/ui-kit/flutter/incoming-call), `CometChatOutgoingCall` → [Outgoing Call](/ui-kit/flutter/outgoing-call), `CometChatCallLogs` → [Call Logs](/ui-kit/flutter/call-logs) | +| Auto-detection | UI Kit automatically detects the Calls SDK and enables call UI components | +| Requirements | minSdkVersion 24 (Android), iOS 12+ | + + CometChat's Calls feature is an advanced functionality that allows you to seamlessly integrate one-on-one as well as group audio and video calling capabilities into your application. This document provides a technical overview of these features, as implemented in the Flutter UI Kit. - - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) - - + ## Integration First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/flutter/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your Flutter project. diff --git a/ui-kit/flutter/core-features.mdx b/ui-kit/flutter/core-features.mdx index fc991048d..12d9dd625 100644 --- a/ui-kit/flutter/core-features.mdx +++ b/ui-kit/flutter/core-features.mdx @@ -4,27 +4,18 @@ sidebarTitle: "Core" description: "Comprehensive guide to CometChat's core messaging features including instant messaging, media sharing, read receipts, and more" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -Key components for core features: -- **Instant Messaging** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Media Sharing** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Read Receipts** → [Conversations](/ui-kit/flutter/conversations) | [MessageList](/ui-kit/flutter/message-list) -- **Typing Indicators** → [Conversations](/ui-kit/flutter/conversations) | [MessageHeader](/ui-kit/flutter/message-header) -- **User Presence** → [Conversations](/ui-kit/flutter/conversations) | [Users](/ui-kit/flutter/users) -- **Reactions** → [MessageList](/ui-kit/flutter/message-list) -- **Mentions** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Threaded Messages** → [Threaded Messages](/ui-kit/flutter/threaded-messages-header) -- **Group Chat** → [Groups](/ui-kit/flutter/groups) - + -The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` — must complete before rendering any component | +| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Quoted Reply, Search, Threaded Conversations, Moderation, Report Message, Group Chat | +| Key components | `CometChatConversations` → [Conversations](/ui-kit/flutter/conversations), `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list), `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer), `CometChatMessageHeader` → [Message Header](/ui-kit/flutter/message-header), `CometChatUsers` → [Users](/ui-kit/flutter/users), `CometChatGroups` → [Groups](/ui-kit/flutter/groups), `CometChatGroupMembers` → [Group Members](/ui-kit/flutter/group-members) | - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [REST API](https://api-explorer.cometchat.com) - + + +The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. Here's how different UI Kit widgets work together to achieve CometChat's Core features: diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 6a8a01c01..82511a0ca 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -1,54 +1,104 @@ --- title: "Extensions" +sidebarTitle: "Extensions" description: "Enhance your chat with built-in extensions including stickers, polls, collaborative tools, message translation, and link previews" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Enable extensions during initialization -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() -).build(); +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` + Extensions enabled in [CometChat Dashboard](/fundamentals/extensions-overview) | +| Extension categories | User Experience, User Engagement, Collaboration, Security | +| Key components | `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer) (Stickers, Polls, Whiteboard, Document), `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list) (Translation, Link Preview, Thumbnails) | +| Activation | Enable each extension from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required | -await CometChatUIKit.init(uiKitSettings: uiKitSettings); -``` + -**Built-in Extensions:** -- **Stickers** → Express emotions with pre-designed stickers -- **Polls** → Create polls for group discussions -- **Collaborative Whiteboard** → Real-time drawing and brainstorming -- **Collaborative Document** → Shared document editing -- **Message Translation** → Translate messages to local locale -- **Link Preview** → Show URL summaries with thumbnails -- **Thumbnail Generation** → Auto-generate image previews +CometChat's UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. -**Enable from:** [CometChat Dashboard](https://app.cometchat.com) → Extensions - +Activating any of the extensions in CometChat is a simple process done through your application's dashboard. Refer to our guide for detailed information on [Extensions](/fundamentals/extensions-overview). -CometChat's UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. +Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. The extension features will only be available if they are supported by CometChat UI Kit. - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) - +*** -Activating any of the extensions in CometChat is a simple process done through your application's dashboard. Refer to our guide For detailed information on [Extensions](/fundamentals/extensions-overview) +## Built-in Extensions -Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. Please note, that the extension features will only be available if they are supported by CometChat UI Kit. +The grouping below mirrors the CometChat Dashboard. -CometChat's UI Kit offers built-in support for 12 powerful extensions. This seamless integration makes it easy for you to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant widgets of your application, providing a richer and more engaging experience for your users. +### User Experience + +#### Link Preview + +The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). + +Once you have successfully activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + *** -## Built-in Extensions +#### Thumbnail Generation + +The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). + +Once you have successfully activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + + +*** + +#### Bitly + +Shortens long URLs in text messages using Bitly. See [Bitly Extension](/fundamentals/bitly). + +*** + +#### TinyURL + +URL shortening using TinyURL. See [TinyURL Extension](/fundamentals/tinyurl). + +*** + +#### Message Shortcuts + +Sends predefined messages using short codes (e.g., `!hb` expands to `Happy birthday!`). See [Message Shortcuts Extension](/fundamentals/message-shortcuts). + +*** + +#### Pin Message + +Pins important messages in a conversation for easy access. See [Pin Message Extension](/fundamentals/pin-message). + +*** + +#### Save Message + +Bookmarks messages for later reference. Saved messages are private to the user. See [Save Message Extension](/fundamentals/save-message). + +*** + +#### Rich Media Preview + +Generates rich preview panels for URLs using iFramely. See [Rich Media Preview Extension](/fundamentals/rich-media-preview). -Here's a guide on how you can enable and integrate these extensions: +*** + +#### Voice Transcription -### Stickers +Converts audio messages to text. See [Voice Transcription Extension](/fundamentals/voice-transcription). + +*** + +### User Engagement + +#### Stickers The Stickers extension allows users to express their emotions more creatively. It adds a much-needed fun element to the chat by allowing users to send various pre-designed stickers. For a comprehensive understanding and guide on implementing and using the Sticker Extension, refer to our specific guide on the [Sticker Extension](/fundamentals/stickers). @@ -60,7 +110,7 @@ Once you have successfully activated the [Sticker Extension](/fundamentals/stick *** -### Polls +#### Polls The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive understanding and guide on implementing and using the Polls Extension, refer to our specific guide on the [Polls Extension](/fundamentals/polls). @@ -72,7 +122,45 @@ Once you have successfully activated the [Polls Extension](/fundamentals/polls) *** -### Collaborative Whiteboard +#### Message Translation + +The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). + +Once you have successfully activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + + +*** + +#### Giphy + +Search and share GIFs from Giphy. See [Giphy Extension](/fundamentals/giphy). + +*** + +#### Tenor + +Search and share GIFs from Tenor. See [Tenor Extension](/fundamentals/tenor). + +*** + +#### Stipop + +Integrates Stipop's sticker library. See [Stipop Extension](/fundamentals/stickers-stipop). + +*** + +#### Reminders + +Sets reminders for messages or creates personal reminders. A bot sends a notification when due. See [Reminders Extension](/fundamentals/reminders). + +*** + +### Collaboration + +#### Collaborative Whiteboard The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive understanding and guide on implementing and using the Collaborative Whiteboard Extension, refer to our specific guide on the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard). @@ -84,7 +172,7 @@ Once you have successfully activated the [Collaborative Whiteboard Extension](/f *** -### Collaborative Document +#### Collaborative Document With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive understanding and guide on implementing and using the Collaborative Document Extension, refer to our specific guide on the [Collaborative Document Extension](/fundamentals/collaborative-document). @@ -96,39 +184,31 @@ Once you have successfully activated the [Collaborative Document Extension](/fun *** -### Message Translation +### Security -The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). - -Once you have successfully activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. +#### Disappearing Messages - - - +Messages auto-delete after a specified interval. Works for 1:1 and group messages. See [Disappearing Messages Extension](/fundamentals/disappearing-messages). *** -### Link Preview +### Customer Support -The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). +#### Chatwoot -Once you have successfully activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. - - - - +Routes user messages to Chatwoot for customer support. See [Chatwoot Extension](/fundamentals/chatwoot). *** -### Thumbnail Generation +#### Intercom -The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). +Integrates Intercom for in-app customer support. See [Intercom Extension](/fundamentals/intercom). -Once you have successfully activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Widget](/ui-kit/flutter/message-list) widget of UI Kits. +*** - - - +### Smart Chat Features + +For AI-powered features like Conversation Starter, Smart Replies, and Conversation Summary, see [AI Features](/ui-kit/flutter/ai-features). *** From dec59b5d447cab7e8317ce38c206eaa25adf2cd3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:40:15 +0530 Subject: [PATCH 23/32] Update call-features.mdx --- ui-kit/flutter/call-features.mdx | 210 +++++++++++++++---------------- 1 file changed, 98 insertions(+), 112 deletions(-) diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index dd278bde9..f674c8b37 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -25,118 +25,104 @@ First, make sure that you've correctly integrated the UI Kit library into your p Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit. Here's how you do it: -Step 1 - -### Add Dependency - -Add the following dependency to your `pubspec.yaml` file: - - - -```dart -dependencies: - cometchat_calls_uikit: ^5.0.12 -``` - - - -*** - -Step 2 - -### Update build.gradle - -If your Flutter project's minimum Android SDK version (minSdkVersion) is below API level 24, you should update it to at least 24. To achieve this, navigate to the `android/app/build.gradle` file and modify the `minSdkVersion` property within the `defaultConfig` section. - - - -```gradle -defaultConfig { - minSdkVersion 24 - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName -} -``` - - - - -If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. - - -*** - -Step 3 - -### Update iOS Podfile - -In your Podfile located at `ios/Podfile`, update the minimum iOS version that your project supports to 12. - - - -```xml -platform :ios, '12.0' -``` - - - -*** - -Step 4 - -### Modify UIKitSettings - -To activate the calling features, you'll need to modify the UIKitSettings using `callingExtension` and pass the key in the widget. - -Example - - - -```dart -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..region = "REGION" // Replace with your App Region - ..appId = "APP_ID" // Replace with your App ID - ..authKey = "AUTH_KEY" // Replace with your app Auth Key - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension() // Enable calling feature -).build(); - -CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) { - // TODO("Not yet implemented") - }, - onError: (e) { - // TODO("Not yet implemented") - } -); -``` - - - -To allow launching of Incoming Call screen from any widget whenever a call is received provide set key: CallNavigationContext.navigatorKey in the top most widget of your project (the widget that appears first of your app launch). - - - -```dart -CometChatUIKit.login(uid, onSuccess: (s) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUsersWithMessages( - key: CallNavigationContext.navigatorKey - ) - ) - ); -}, onError: (e) { - // TODO("Not yet implemented") -}); -``` - - + + + Add the following dependency to your `pubspec.yaml` file: + + + + ```yaml + dependencies: + cometchat_calls_uikit: ^5.0.12 + ``` + + + + + + If your Flutter project's minimum Android SDK version (minSdkVersion) is below API level 24, you should update it to at least 24. Navigate to the `android/app/build.gradle` file and modify the `minSdkVersion` property within the `defaultConfig` section. + + + + ```gradle + defaultConfig { + minSdkVersion 24 + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + ``` + + + + + If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. + + + + + In your Podfile located at `ios/Podfile`, update the minimum iOS version that your project supports to 12. + + + + ```ruby + platform :ios, '12.0' + ``` + + + + + + To activate the calling features, you'll need to modify the UIKitSettings using `callingExtension` and pass the key in the widget. + + + + ```dart highlight={8} + UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..region = "REGION" // Replace with your App Region + ..appId = "APP_ID" // Replace with your App ID + ..authKey = "AUTH_KEY" // Replace with your app Auth Key + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Enable calling feature + ).build(); + + CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) { + // Initialization successful + }, + onError: (e) { + // Handle error + } + ); + ``` + + + + To allow launching of Incoming Call screen from any widget whenever a call is received, set `key: CallNavigationContext.navigatorKey` in the top most widget of your project (the widget that appears first on app launch). + + + + ```dart highlight={6} + CometChatUIKit.login(uid, onSuccess: (s) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUsersWithMessages( + key: CallNavigationContext.navigatorKey + ) + ) + ); + }, onError: (e) { + // Handle error + }); + ``` + + + + After adding this dependency, the Flutter UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/flutter/call-buttons) widget rendered in [MessageHeader](/ui-kit/flutter/message-header) Widget. From 274453a0b18f6693d4f1a3af06216c6e364b3f4a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:49:01 +0530 Subject: [PATCH 24/32] Update components-overview.mdx --- ui-kit/flutter/components-overview.mdx | 41 +++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/components-overview.mdx b/ui-kit/flutter/components-overview.mdx index f549bf175..7fc03fe55 100644 --- a/ui-kit/flutter/components-overview.mdx +++ b/ui-kit/flutter/components-overview.mdx @@ -26,10 +26,49 @@ The UI Kit is a set of independent widgets that compose into chat layouts. A typ - **CometChatMessageList** — scrollable message feed with reactions, receipts, and threads - **CometChatMessageComposer** — rich text input with attachments, mentions, and voice notes -Data flow: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. +**Data flow**: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. + +```mermaid +flowchart LR + subgraph Sidebar + A[CometChatConversations] + end + + subgraph "Chat Panel" + B[CometChatMessageHeader] + C[CometChatMessageList] + D[CometChatMessageComposer] + end + + subgraph SDK + E[CometChat SDK] + end + + A -->|"User/Group object"| B + A -->|"User/Group object"| C + A -->|"User/Group object"| D + D -->|"sendMessage()"| E + E -->|"Real-time listeners"| C +``` Components communicate through a publish/subscribe event bus (`CometChatMessageEvents`, `CometChatConversationEvents`, `CometChatGroupEvents`, etc.). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/flutter/events) for the full list. +```mermaid +flowchart TB + subgraph "Event Bus" + E1[CometChatMessageEvents] + E2[CometChatConversationEvents] + E3[CometChatGroupEvents] + end + + C1[Component A] -->|"emit"| E1 + E1 -->|"subscribe"| C2[Component B] + E1 -->|"subscribe"| C3[App Code] + + C4[Component C] -->|"emit"| E2 + E2 -->|"subscribe"| C5[Component D] +``` + Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and style class overrides via `CometChatStyle`. --- From f7af525a14437359f842cad2f3e9ba138c516b47 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:52:56 +0530 Subject: [PATCH 25/32] Removed all 3 references to community.cometchat.com --- ui-kit/flutter/guide-overview.mdx | 2 +- ui-kit/flutter/overview.mdx | 3 --- ui-kit/flutter/troubleshooting.mdx | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 46f3dc93b..390da3adb 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -44,7 +44,7 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [URL Formatter](/ui-kit/flutter/url-formatter-guide) | Auto-detect and style URLs as clickable links. | | [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) | Create keyboard shortcuts for quick text insertion. | -Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. +Need another guide? Request one via [CometChat Support](https://www.cometchat.com/support). --- diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index e1391ba86..815576fdb 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -71,7 +71,4 @@ The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding Open a support ticket - - Developer community forum - diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx index afde830f4..51c28fda8 100644 --- a/ui-kit/flutter/troubleshooting.mdx +++ b/ui-kit/flutter/troubleshooting.mdx @@ -208,4 +208,3 @@ If you're still experiencing issues: 1. Check the [CometChat Documentation](https://www.cometchat.com/docs) 2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) 3. Contact [CometChat Support](https://www.cometchat.com/support) -4. Join the [CometChat Community](https://community.cometchat.com) From daa0432174826629345905b8979e01be6bed5e49 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 16:35:04 +0530 Subject: [PATCH 26/32] updates ignore files --- .gitignore | 1 + .mintignore | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 19273fa01..51b40734f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .kiro/ /codebase +/doc-auditor diff --git a/.mintignore b/.mintignore index a2bfd86bc..15ada5362 100644 --- a/.mintignore +++ b/.mintignore @@ -1,2 +1,3 @@ .kiro/ -/codebase \ No newline at end of file +/codebase +/doc-auditor \ No newline at end of file From c547a9c1ad7faa2bcb04a72b30a94b1ad57eae85 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:20:28 +0530 Subject: [PATCH 27/32] updates components --- ui-kit/flutter/call-buttons.mdx | 32 +++++++++++++++++ ui-kit/flutter/call-logs.mdx | 55 +++++++++++++++++++++++++++++ ui-kit/flutter/incoming-call.mdx | 51 ++++++++++++++++++++++++++ ui-kit/flutter/message-template.mdx | 29 +++++++++++++++ ui-kit/flutter/outgoing-call.mdx | 45 +++++++++++++++++++++++ 5 files changed, 212 insertions(+) diff --git a/ui-kit/flutter/call-buttons.mdx b/ui-kit/flutter/call-buttons.mdx index 0f404d59b..e39b6b0c2 100644 --- a/ui-kit/flutter/call-buttons.mdx +++ b/ui-kit/flutter/call-buttons.mdx @@ -1,6 +1,38 @@ --- title: "Call Buttons" +description: "Widget that provides users with the ability to make voice and video calls with customizable icons and styles." --- + +```json +{ + "component": "CometChatCallButtons", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that provides users with the ability to make voice and video calls with customizable icons and styles.", + "props": { + "data": { + "user": { "type": "User?", "default": "null" }, + "group": { "type": "Group?", "default": "null" } + }, + "visibility": { + "hideVoiceCallButton": { "type": "bool?", "default": "false" }, + "hideVideoCallButton": { "type": "bool?", "default": "false" } + }, + "icons": { + "voiceCallIcon": "Widget?", + "videoCallIcon": "Widget?" + }, + "style": { + "callButtonsStyle": "CometChatCallButtonsStyle?" + }, + "configuration": { + "outgoingCallConfiguration": "CometChatOutgoingCallConfiguration?", + "callSettingsBuilder": "CallSettingsBuilder Function(User? user, Group? group, bool? isAudioOnly)?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/call-logs.mdx b/ui-kit/flutter/call-logs.mdx index 053d4db84..1c65634c3 100644 --- a/ui-kit/flutter/call-logs.mdx +++ b/ui-kit/flutter/call-logs.mdx @@ -1,6 +1,61 @@ --- title: "Call Logs" +description: "Widget that shows the list of Call Logs available with filtering, call-back actions, and custom views." --- + +```json +{ + "component": "CometChatCallLogs", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that shows the list of Call Logs available with filtering, call-back actions, and custom views.", + "props": { + "data": { + "callLogsRequestBuilder": { "type": "CallLogRequestBuilder?", "default": "null" }, + "callLogsBuilderProtocol": { "type": "CallLogsBuilderProtocol?", "default": "null" } + }, + "callbacks": { + "onItemClick": "Function(CallLog callLog)?", + "onItemLongPress": "Function(CallLog callLog)?", + "onCallLogIconClicked": "Function(CallLog callLog)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "hideAppbar": { "type": "bool?", "default": "false" }, + "showBackButton": { "type": "bool?", "default": "true" } + }, + "viewSlots": { + "listItemView": "Widget? Function(CallLog callLog, BuildContext context)?", + "subTitleView": "Widget? Function(CallLog callLog, BuildContext context)?", + "trailingView": "Function(BuildContext context, CallLog callLog)?", + "leadingStateView": "Widget? Function(BuildContext, CallLog)?", + "titleView": "Widget? Function(BuildContext, CallLog)?", + "backButton": "Widget?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "loadingStateView": "WidgetBuilder?" + }, + "style": { + "callLogsStyle": "CometChatCallLogsStyle?" + }, + "icons": { + "audioCallIcon": "Widget?", + "videoCallIcon": "Widget?", + "incomingCallIcon": "Widget?", + "outgoingCallIcon": "Widget?", + "missedCallIcon": "Widget?" + }, + "formatting": { + "datePattern": "String?", + "dateSeparatorPattern": "String?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/incoming-call.mdx b/ui-kit/flutter/incoming-call.mdx index 41895e4ae..7891817c9 100644 --- a/ui-kit/flutter/incoming-call.mdx +++ b/ui-kit/flutter/incoming-call.mdx @@ -1,6 +1,57 @@ --- title: "Incoming Call" +description: "Widget that serves as a visual representation when the user receives an incoming call, providing options to answer or decline." --- + +```json +{ + "component": "CometChatIncomingCall", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that serves as a visual representation when the user receives an incoming call, providing options to answer or decline.", + "props": { + "data": { + "call": { "type": "Call", "required": true }, + "user": { "type": "User?", "default": "null" } + }, + "callbacks": { + "onDecline": "Function(BuildContext, Call)?", + "onAccept": "Function(BuildContext, Call)?", + "onError": "OnError?" + }, + "viewSlots": { + "titleView": "Widget? Function(BuildContext context, Call call)?", + "subTitleView": "Widget? Function(BuildContext context, Call call)?", + "leadingView": "Widget? Function(BuildContext context, Call call)?", + "itemView": "Widget? Function(BuildContext context, Call call)?", + "trailingView": "Widget? Function(BuildContext context, Call call)?" + }, + "style": { + "incomingCallStyle": "CometChatIncomingCallStyle?" + }, + "layout": { + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "icons": { + "callIcon": "Widget?" + }, + "text": { + "declineButtonText": "String?", + "acceptButtonText": "String?" + }, + "sound": { + "disableSoundForCalls": { "type": "bool?", "default": "false" }, + "customSoundForCalls": "String?", + "customSoundForCallsPackage": "String?" + }, + "configuration": { + "callSettingsBuilder": "CallSettingsBuilder?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/message-template.mdx b/ui-kit/flutter/message-template.mdx index 6be26a674..c70fc6a66 100644 --- a/ui-kit/flutter/message-template.mdx +++ b/ui-kit/flutter/message-template.mdx @@ -1,7 +1,36 @@ --- title: "Message Template" +description: "Data structure defining how message bubbles render in CometChatMessageList — controls header, content, footer, bottom, status info, reply, and bubble views per message type and category." --- + +```json +{ + "component": "CometChatMessageTemplate", + "kind": "model-class", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Data structure defining how message bubbles render in CometChatMessageList. Each template maps a type+category pair to view functions.", + "usage": "Pass a list of CometChatMessageTemplate instances to CometChatMessageList via the templates property.", + "properties": { + "type": { "type": "String", "required": true, "description": "CometChat message type" }, + "category": { "type": "String", "default": "\"\"", "description": "CometChat message category" }, + "headerView": { "type": "Function?", "default": "null", "description": "Custom header view builder function" }, + "contentView": { "type": "Function?", "default": "null", "description": "Custom content view builder function" }, + "footerView": { "type": "Function?", "default": "null", "description": "Custom footer view builder function" }, + "bottomView": { "type": "Function?", "default": "null", "description": "Custom bottom view builder function" }, + "bubbleView": { "type": "Function?", "default": "null", "description": "Replaces entire bubble" }, + "statusInfoView": { "type": "Function?", "default": "null", "description": "Custom status info view builder function" }, + "replyView": { "type": "Function?", "default": "null", "description": "Custom reply preview builder function" }, + "threadView": { "type": "Function?", "default": "null", "description": "Custom thread view builder function" }, + "options": { "type": "Function", "description": "Returns action sheet items for long-press" } + }, + "relatedComponents": ["CometChatMessageList"], + "events": null +} +``` + + ## Overview A MessageTemplate provides you with the capability to define and customize both the structure and the behavior of the [MessageBubble](/ui-kit/flutter/message-bubble-styling). It acts as a schema or design blueprint for the creation of a variety of [MessageBubble](/ui-kit/flutter/message-bubble-styling) widgets, allowing you to manage the appearance and interactions of [MessageBubble](/ui-kit/flutter/message-bubble-styling) within your application effectively and consistently. diff --git a/ui-kit/flutter/outgoing-call.mdx b/ui-kit/flutter/outgoing-call.mdx index 2bbc3a3fa..1a73ce2eb 100644 --- a/ui-kit/flutter/outgoing-call.mdx +++ b/ui-kit/flutter/outgoing-call.mdx @@ -1,6 +1,51 @@ --- title: "Outgoing Call" +description: "Widget that serves as a visual representation of a user-initiated call, providing options to control the call experience." --- + +```json +{ + "component": "CometChatOutgoingCall", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that serves as a visual representation of a user-initiated call, providing options to control the call experience.", + "props": { + "data": { + "call": { "type": "Call", "required": true }, + "user": { "type": "User?", "default": "null" } + }, + "callbacks": { + "onCancelled": "Function(BuildContext context, Call call)?", + "onError": "OnError?" + }, + "viewSlots": { + "subtitleView": "Widget? Function(BuildContext context, Call call)?", + "avatarView": "Widget? Function(BuildContext context, Call call)?", + "titleView": "Widget? Function(BuildContext context, Call call)?", + "cancelledView": "Widget? Function(BuildContext context, Call call)?" + }, + "style": { + "outgoingCallStyle": "CometChatOutgoingCallStyle?" + }, + "layout": { + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "icons": { + "declineButtonIcon": "Widget?" + }, + "sound": { + "disableSoundForCalls": { "type": "bool?", "default": "false" }, + "customSoundForCalls": "String?", + "customSoundForCallsPackage": "String?" + }, + "configuration": { + "callSettingsBuilder": "CallSettingsBuilder?" + } + } +} +``` + ## Overview From cc6825592283a3f4ad197d47681f9df7a8d7d2fe Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:48:25 +0530 Subject: [PATCH 28/32] Update troubleshooting.mdx --- ui-kit/flutter/troubleshooting.mdx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx index 51c28fda8..dd24b6e9f 100644 --- a/ui-kit/flutter/troubleshooting.mdx +++ b/ui-kit/flutter/troubleshooting.mdx @@ -204,7 +204,4 @@ void dispose() { ## Getting Help If you're still experiencing issues: - -1. Check the [CometChat Documentation](https://www.cometchat.com/docs) -2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) -3. Contact [CometChat Support](https://www.cometchat.com/support) +- Contact [CometChat Support](https://www.cometchat.com/support) From d37dbde8a4deda323c8a3255e2a07df1b899ca64 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:58:22 +0530 Subject: [PATCH 29/32] from V4 to V5 --- ui-kit/flutter/property-changes.mdx | 2 +- ui-kit/flutter/upgrading-from-v4.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/property-changes.mdx b/ui-kit/flutter/property-changes.mdx index c38585b34..8014bc558 100644 --- a/ui-kit/flutter/property-changes.mdx +++ b/ui-kit/flutter/property-changes.mdx @@ -1,5 +1,5 @@ --- -title: "Property Changes" +title: "Property changes from V4 to V5" --- ## Conversations diff --git a/ui-kit/flutter/upgrading-from-v4.mdx b/ui-kit/flutter/upgrading-from-v4.mdx index c2e9183e0..201b44f7c 100644 --- a/ui-kit/flutter/upgrading-from-v4.mdx +++ b/ui-kit/flutter/upgrading-from-v4.mdx @@ -1,5 +1,5 @@ --- -title: "Upgrading From V4" +title: "Upgrading from V4 to V5" --- From db4b840e9428b37a43deceeac408a199577d7ae7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:59:17 +0530 Subject: [PATCH 30/32] mintlify component --- ui-kit/flutter/color-resources.mdx | 12 ++++ ui-kit/flutter/component-styling.mdx | 92 ++++++++++++++++++++++++++ ui-kit/flutter/message-header.mdx | 68 +++++++++++++++++++ ui-kit/flutter/theme-introduction.mdx | 27 ++++++-- ui-kit/flutter/url-formatter-guide.mdx | 28 ++++++++ 5 files changed, 220 insertions(+), 7 deletions(-) diff --git a/ui-kit/flutter/color-resources.mdx b/ui-kit/flutter/color-resources.mdx index 5ac72fe51..4ec539b47 100644 --- a/ui-kit/flutter/color-resources.mdx +++ b/ui-kit/flutter/color-resources.mdx @@ -124,6 +124,8 @@ description: "Complete reference for CometChatColorPalette tokens in Flutter UI + + ```dart ThemeData( extensions: [ @@ -147,6 +149,8 @@ ThemeData( ], ) ``` + + --- @@ -156,6 +160,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -178,6 +184,8 @@ ThemeData( ], ) ``` + + --- @@ -187,6 +195,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -209,3 +219,5 @@ ThemeData( ], ) ``` + + diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 5ca6af35a..c3fd79f62 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -30,6 +30,8 @@ Style individual components by adding their style classes to `ThemeData.extensio + + ```dart ThemeData( extensions: [ @@ -45,6 +47,8 @@ ThemeData( ], ) ``` + + ### Message List @@ -52,6 +56,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -64,6 +70,8 @@ ThemeData( ], ) ``` + + ### Message Composer @@ -71,6 +79,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -82,6 +92,8 @@ ThemeData( ], ) ``` + + ### Message Header @@ -89,6 +101,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -105,6 +119,8 @@ ThemeData( ], ) ``` + + ### Users @@ -112,6 +128,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -127,6 +145,8 @@ ThemeData( ], ) ``` + + ### Groups @@ -134,6 +154,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -149,9 +171,13 @@ ThemeData( ], ) ``` + + ### Group Members + + ```dart ThemeData( extensions: [ @@ -173,6 +199,8 @@ ThemeData( ], ) ``` + + --- @@ -184,12 +212,16 @@ ThemeData( + + ```dart CometChatAvatarStyle( borderRadius: BorderRadius.circular(8), backgroundColor: Color(0xFFFBAA75), ) ``` + + ### Badge @@ -197,12 +229,16 @@ CometChatAvatarStyle( + + ```dart CometChatBadgeStyle( borderRadius: BorderRadius.circular(4), backgroundColor: Color(0xFFF44649), ) ``` + + ### Status Indicator @@ -210,12 +246,16 @@ CometChatBadgeStyle( + + ```dart CometChatStatusIndicatorStyle( backgroundColor: Color(0xFFFFAB00), borderRadius: BorderRadius.circular(2), ) ``` + + ### Receipts @@ -223,11 +263,15 @@ CometChatStatusIndicatorStyle( + + ```dart CometChatMessageReceiptStyle( readIconColor: Color(0xFFFFAB00), ) ``` + + ### Reactions @@ -235,23 +279,33 @@ CometChatMessageReceiptStyle( + + ```dart CometChatReactionsStyle( borderRadius: BorderRadius.circular(8), ) ``` + + ### Reaction List + + ```dart CometChatReactionListStyle( activeTabTextColor: Color(0xFFF76808), activeTabIndicatorColor: Color(0xFFF76808), ) ``` + + ### Media Recorder + + ```dart CometChatMediaRecorderStyle( recordIndicatorBackgroundColor: Color(0xFFF44649), @@ -261,6 +315,8 @@ CometChatMediaRecorderStyle( stopButtonBorderRadius: BorderRadius.circular(8), ) ``` + + --- @@ -268,6 +324,8 @@ CometChatMediaRecorderStyle( ### Message Option Sheet + + ```dart ThemeData( extensions: [ @@ -278,9 +336,13 @@ ThemeData( ], ) ``` + + ### Attachment Option Sheet + + ```dart ThemeData( extensions: [ @@ -291,9 +353,13 @@ ThemeData( ], ) ``` + + ### Message Information + + ```dart ThemeData( extensions: [ @@ -309,9 +375,13 @@ ThemeData( ], ) ``` + + ### Mentions + + ```dart ThemeData( extensions: [ @@ -324,6 +394,8 @@ ThemeData( ], ) ``` + + --- @@ -335,12 +407,16 @@ ThemeData( + + ```dart CometChatAIConversationStarterStyle( backgroundColor: Color(0xFFFEEDE1), border: Border.all(color: Color(0xFFFBBB90)), ) ``` + + ### Smart Replies @@ -348,6 +424,8 @@ CometChatAIConversationStarterStyle( + + ```dart CometChatAISmartRepliesStyle( backgroundColor: Color(0xFFFEEDE1), @@ -356,27 +434,39 @@ CometChatAISmartRepliesStyle( itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` + + ### Conversation Summary + + ```dart CometChatAIConversationSummaryStyle( backgroundColor: Color(0xFFFEEDE1), titleStyle: TextStyle(color: Color(0xFFF76808)), ) ``` + + ### AI Option Sheet + + ```dart CometChatAiOptionSheetStyle( backgroundColor: Color(0xFFFFF9F5), iconColor: Color(0xFFF76808), ) ``` + + ### AI Assistant Chat History + + ```dart final ccColor = CometChatThemeHelper.getColorPalette(context); @@ -396,3 +486,5 @@ CometChatAIAssistantChatHistory( ), ) ``` + + diff --git a/ui-kit/flutter/message-header.mdx b/ui-kit/flutter/message-header.mdx index ab5ee45dc..3cc79020d 100644 --- a/ui-kit/flutter/message-header.mdx +++ b/ui-kit/flutter/message-header.mdx @@ -1,6 +1,74 @@ --- title: "Message Header" +description: "Widget that showcases the User or Group details in the toolbar with typing indicator and back navigation button." --- + +```json +{ + "component": "CometChatMessageHeader", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Widget that showcases the User or Group details in the toolbar with typing indicator and back navigation button.", + "props": { + "data": { + "user": { "type": "User?", "default": "null" }, + "group": { "type": "Group?", "default": "null" } + }, + "callbacks": { + "onBack": "VoidCallback?", + "newChatButtonClick": "VoidCallback?", + "chatHistoryButtonClick": "VoidCallback?" + }, + "visibility": { + "showBackButton": { "type": "bool?", "default": "true" }, + "hideVideoCallButton": { "type": "bool?", "default": "false" }, + "hideVoiceCallButton": { "type": "bool?", "default": "false" }, + "usersStatusVisibility": { "type": "bool?", "default": "true" }, + "hideNewChatButton": { "type": "bool?", "default": "false" }, + "hideChatHistoryButton": { "type": "bool?", "default": "false" } + }, + "viewSlots": { + "backButton": "WidgetBuilder?", + "subtitleView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "listItemView": "Widget Function(Group? group, User? user, BuildContext context)?", + "trailingView": "List? Function(User? user, Group? group, BuildContext context)?", + "leadingStateView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "titleView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "auxiliaryButtonView": "Widget? Function(Group? group, User? user, BuildContext context)?" + }, + "style": { + "messageHeaderStyle": "CometChatMessageHeaderStyle?", + "listItemStyle": "ListItemStyle?" + }, + "layout": { + "avatarHeight": { "type": "double?", "default": "null" }, + "avatarWidth": { "type": "double?", "default": "null" }, + "height": { "type": "double?", "default": "65" }, + "padding": { "type": "EdgeInsetsGeometry?", "default": "null" } + }, + "icons": { + "menuIcon": "Widget?", + "newChatIcon": "IconData?", + "chatHistoryIcon": "IconData?" + }, + "formatting": { + "dateTimeFormatterCallback": "DateTimeFormatterCallback?" + } + }, + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "onTypingStarted", + "onTypingEnded", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ] +} +``` + ## Overview diff --git a/ui-kit/flutter/theme-introduction.mdx b/ui-kit/flutter/theme-introduction.mdx index 984444790..417ff033b 100644 --- a/ui-kit/flutter/theme-introduction.mdx +++ b/ui-kit/flutter/theme-introduction.mdx @@ -60,6 +60,8 @@ Theming controls the look and feel of the chat UI — colors, fonts, and spacing Override theme properties in your `MaterialApp`: + + ```dart title="main.dart" MaterialApp( theme: ThemeData( @@ -75,6 +77,8 @@ MaterialApp( home: MyApp(), ) ``` + + --- @@ -84,7 +88,9 @@ MaterialApp( -```dart title="Light Theme" + + +```dart ThemeData( extensions: [ CometChatColorPalette( @@ -97,12 +103,9 @@ ThemeData( ], ) ``` - - - - - -```dart title="Dark Theme" + + +```dart ThemeData( extensions: [ CometChatColorPalette( @@ -115,6 +118,12 @@ ThemeData( ], ) ``` + + + + + + --- @@ -124,6 +133,8 @@ ThemeData( + + ```dart ThemeData( fontFamily: 'Times New Roman', @@ -136,6 +147,8 @@ ThemeData( ], ) ``` + + --- diff --git a/ui-kit/flutter/url-formatter-guide.mdx b/ui-kit/flutter/url-formatter-guide.mdx index 6627d0be0..b66fe6a6e 100644 --- a/ui-kit/flutter/url-formatter-guide.mdx +++ b/ui-kit/flutter/url-formatter-guide.mdx @@ -48,17 +48,23 @@ The `CometChatUrlFormatter` is automatically applied to messages. URLs are: The URL formatter is included by default. No additional setup required. + + ```dart CometChatMessageList( user: chatUser, // URL formatter is automatically included ) ``` + + ### Custom URL Formatter Create a custom URL formatter with your own styling and behavior. + + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; @@ -113,9 +119,13 @@ class CustomUrlFormatter extends CometChatUrlFormatter { } } ``` + + ### Apply Custom Formatter + + ```dart CometChatMessageList( user: chatUser, @@ -125,6 +135,8 @@ CometChatMessageList( ], ) ``` + + --- @@ -134,6 +146,8 @@ CometChatMessageList( Override `getMessageBubbleTextStyle` to customize link appearance: + + ```dart @override TextStyle getMessageBubbleTextStyle( @@ -155,11 +169,15 @@ TextStyle getMessageBubbleTextStyle( ); } ``` + + ### Custom URL Pattern Use a custom regex pattern to match specific URL formats: + + ```dart CometChatUrlFormatter( pattern: RegExp( @@ -167,11 +185,15 @@ CometChatUrlFormatter( ), ) ``` + + ### Handle URL Clicks Override `getAttributedText` to add custom click handling: + + ```dart @override List getAttributedText( @@ -213,6 +235,8 @@ List getAttributedText( ); } ``` + + --- @@ -229,6 +253,8 @@ List getAttributedText( ## Complete Example + + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; @@ -279,6 +305,8 @@ class _UrlFormatterExampleState extends State { } } ``` + + --- From 314a74f9ce34cbd8464818f5f69f64e78bbc24eb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 19:29:52 +0530 Subject: [PATCH 31/32] Update docs.json --- docs.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs.json b/docs.json index f12ad9f4f..359a41f34 100644 --- a/docs.json +++ b/docs.json @@ -1839,12 +1839,7 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "ui-kit/flutter/overview" - ] - }, + "ui-kit/flutter/overview", { "group": "Getting Started", "pages": [ From 4d0b1e1764c5bcecb6f456cd26a001ac78fac4b1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 6 Mar 2026 12:20:59 +0530 Subject: [PATCH 32/32] Update .mintignore --- .mintignore | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.mintignore b/.mintignore index 15ada5362..9ddbca1cf 100644 --- a/.mintignore +++ b/.mintignore @@ -1,3 +1,8 @@ .kiro/ /codebase -/doc-auditor \ No newline at end of file +/doc-auditor +/prompts +/docs-templates +/mintignore +/doc-auditor +/docs-test-suite \ No newline at end of file