### Configuration Options Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt APIs for configuring SDK behavior, including custom headers, sync intervals, and HTTP interceptors. ```APIDOC ## Configuration Options ### Description Configure SDK behavior including custom headers, sync intervals, and HTTP interceptors. ### Methods - **setCustomHeader(Map headers)**: Sets custom HTTP headers for all SDK requests. - **setSyncInterval(int intervalMillis)**: Sets the interval (in milliseconds) for automatic synchronization. - **addHttpInterceptors(Function interceptor)**: Adds custom interceptors to the SDK's HTTP client. ### Setting Custom Headers ```dart qiscus.setCustomHeader({ 'X-Custom-Header': 'custom-value', 'Authorization': 'Bearer additional-token', }); ``` ### Setting Synchronization Interval ```dart qiscus.setSyncInterval(10000); // 10 seconds ``` ### Adding HTTP Interceptors ```dart import 'package:dio/dio.dart'; qiscus.addHttpInterceptors((RequestOptions options, RequestInterceptorHandler handler) { // Log all outgoing requests print('Request: ${options.method} ${options.uri}'); // Add custom logic options.headers['X-Request-Time'] = DateTime.now().toIso8601String(); return handler.next(options); }); ``` ### Accessing SDK Properties ```dart String? appId = qiscus.appId; String? token = qiscus.token; bool isLoggedIn = qiscus.isLogin; QAccount? currentUser = qiscus.currentUser; ``` ``` -------------------------------- ### SDK Initialization Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Methods to initialize the Qiscus SDK with an App ID or custom server configuration. ```APIDOC ## SDK Initialization ### Description Initializes the Qiscus SDK instance to enable chat features. ### Methods - `QiscusSDK.withAppId(String appId)` - `QiscusSDK.withCustomServer(String appId, {String baseUrl, String brokerUrl, String brokerLbUrl, int syncInterval, int syncIntervalWhenConnected})` ### Request Example ```dart final qiscus = await QiscusSDK.withAppId('your-app-id'); ``` ``` -------------------------------- ### Initialize Qiscus Chat SDK Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Configure the SDK with your application ID and optional custom server settings. Debug mode can be enabled to assist with development. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Initialize with default Qiscus server final qiscus = await QiscusSDK.withAppId('your-app-id'); // Or initialize with custom server configuration final qiscus = await QiscusSDK.withCustomServer( 'your-app-id', baseUrl: 'https://custom-api.example.com', brokerUrl: 'custom-realtime.example.com', brokerLbUrl: 'https://custom-realtime-lb.example.com', syncInterval: 5000, syncIntervalWhenConnected: 30000, ); // Enable debug logging qiscus.enableDebugMode(enable: true, level: QLogLevel.verbose); ``` -------------------------------- ### Configure SDK Settings Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Configures custom headers, synchronization intervals, and HTTP interceptors. Provides access to current session properties. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; import 'package:dio/dio.dart'; // Set custom HTTP headers for all requests qiscus.setCustomHeader({ 'X-Custom-Header': 'custom-value', 'Authorization': 'Bearer additional-token', }); // Set synchronization interval (in milliseconds) qiscus.setSyncInterval(10000); // 10 seconds // Add custom HTTP interceptors qiscus.addHttpInterceptors((RequestOptions options, RequestInterceptorHandler handler) { // Log all outgoing requests print('Request: ${options.method} ${options.uri}'); // Add custom logic options.headers['X-Request-Time'] = DateTime.now().toIso8601String(); return handler.next(options); }); // Access SDK properties String? appId = qiscus.appId; String? token = qiscus.token; bool isLoggedIn = qiscus.isLogin; QAccount? currentUser = qiscus.currentUser; ``` -------------------------------- ### Upload Files and Generate Thumbnails Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Uploads files with progress tracking and generates thumbnail URLs for images. Requires dart:io for file access. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; import 'dart:io'; // Upload a file with progress tracking File file = File('/path/to/file.pdf'); Stream> uploadStream = qiscus.upload(file); uploadStream.listen( (QUploadProgress progress) { if (progress.data != null) { print('Upload complete! URL: ${progress.data}'); } else { print('Uploading: ${progress.progress.toStringAsFixed(1)}%'); } }, onError: (error) { print('Upload failed: $error'); }, ); // Generate thumbnail URL for uploaded images String originalUrl = 'https://example.qiscus.com/upload/images/photo.jpg'; String thumbnailUrl = qiscus.getThumbnailURL(originalUrl); String blurryThumbnailUrl = qiscus.getBlurryThumbnailURL(originalUrl); print('Thumbnail: $thumbnailUrl'); print('Blurry placeholder: $blurryThumbnailUrl'); ``` -------------------------------- ### Connection Management Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt APIs for managing the real-time connection state and handling connection events. ```APIDOC ## Connection Management ### Description Manage real-time connection state and handle connection events. ### Methods - **onConnected()**: Returns a stream that emits when the connection is established. - **onDisconnected()**: Returns a stream that emits when the connection is lost. - **onReconnecting()**: Returns a stream that emits when the SDK is attempting to reconnect. - **closeRealtimeConnection()**: Manually closes the real-time connection. - **openRealtimeConnection()**: Manually opens the real-time connection. - **synchronize(lastMessageId: String?)**: Triggers a manual synchronization of messages. - **synchronizeEvent(lastEventId: String?)**: Triggers a manual synchronization of events. ### Event Streams #### onConnected Listens for connection established events. ```dart qiscus.onConnected().listen((_) { print('Connected to realtime server'); }); ``` #### onDisconnected Listens for connection lost events. ```dart qiscus.onDisconnected().listen((_) { print('Disconnected from realtime server'); }); ``` #### onReconnecting Listens for reconnection attempts. ```dart qiscus.onReconnecting().listen((_) { print('Reconnecting to realtime server...'); }); ``` ### Manual Connection Control #### closeRealtimeConnection Manually closes the real-time connection. ```dart bool closed = await qiscus.closeRealtimeConnection(); ``` #### openRealtimeConnection Manually opens the real-time connection. ```dart bool opened = await qiscus.openRealtimeConnection(); ``` ### Synchronization #### synchronize Triggers a manual synchronization of messages, starting from the specified last message ID. ```dart qiscus.synchronize(lastMessageId: '1000'); ``` #### synchronizeEvent Triggers a manual synchronization of events, starting from the specified last event ID. ```dart qiscus.synchronizeEvent(lastEventId: '500'); ``` ``` -------------------------------- ### Manage Real-time Connection Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Handles connection state listeners and manual connection control. Includes methods for manual synchronization of messages and events. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Listen for connection status changes qiscus.onConnected().listen((_) { print('Connected to realtime server'); }); qiscus.onDisconnected().listen((_) { print('Disconnected from realtime server'); }); qiscus.onReconnecting().listen((_) { print('Reconnecting to realtime server...'); }); // Manually close realtime connection bool closed = await qiscus.closeRealtimeConnection(); print('Connection closed: $closed'); // Manually reopen realtime connection bool opened = await qiscus.openRealtimeConnection(); print('Connection opened: $opened'); // Trigger manual synchronization qiscus.synchronize(lastMessageId: '1000'); qiscus.synchronizeEvent(lastEventId: '500'); ``` -------------------------------- ### Create and Manage Chat Rooms Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Initialize 1-on-1 chats, group chats, or public channels. Existing channels can be retrieved using their unique identifiers. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Start a 1-on-1 chat with another user QChatRoom singleChat = await qiscus.chatUser( userId: 'other-user@example.com', extras: {'source': 'contact_list'}, ); print('Chat room ID: ${singleChat.id}'); // Create a group chat with multiple participants QChatRoom groupChat = await qiscus.createGroupChat( name: 'Project Team', userIds: ['user1@example.com', 'user2@example.com', 'user3@example.com'], avatarUrl: 'https://example.com/group-avatar.png', extras: {'project_id': 'proj-123', 'type': 'work'}, ); // Create a public channel (users can join without invitation) QChatRoom channel = await qiscus.createChannel( uniqueId: 'announcements-channel', name: 'Company Announcements', avatarUrl: 'https://example.com/channel-avatar.png', extras: {'visibility': 'public'}, ); // Get an existing channel by unique ID QChatRoom existingChannel = await qiscus.getChannel(uniqueId: 'announcements-channel'); ``` -------------------------------- ### File Upload and Thumbnails Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt APIs for uploading files and generating thumbnail URLs for images. ```APIDOC ## File Upload and Thumbnails ### Description Upload files and generate thumbnail URLs for images. ### Methods - **upload(File file)**: Uploads a file and returns a stream of upload progress. - **getThumbnailURL(String originalUrl)**: Generates a thumbnail URL for a given image URL. - **getBlurryThumbnailURL(String originalUrl)**: Generates a blurry placeholder thumbnail URL. ### File Upload #### upload Uploads a file with progress tracking. ### Parameters - **file** (File) - Required - The file to upload. ### Request Example ```dart import 'dart:io'; File file = File('/path/to/file.pdf'); Stream> uploadStream = qiscus.upload(file); uploadStream.listen( (QUploadProgress progress) { if (progress.data != null) { print('Upload complete! URL: ${progress.data}'); } else { print('Uploading: ${progress.progress.toStringAsFixed(1)}%'); } }, onError: (error) { print('Upload failed: $error'); }, ); ``` ### Thumbnail Generation #### getThumbnailURL Generates a standard thumbnail URL. ```dart String thumbnailUrl = qiscus.getThumbnailURL(originalUrl); ``` #### getBlurryThumbnailURL Generates a blurry placeholder thumbnail URL. ```dart String blurryThumbnailUrl = qiscus.getBlurryThumbnailURL(originalUrl); ``` ### Response Example (Upload) ```json { "progress": 50.0, "data": null } // or on completion { "progress": 100.0, "data": "https://example.qiscus.com/upload/files/document.pdf" } ``` ### Response Example (Thumbnail URLs) ```json { "thumbnailUrl": "https://example.qiscus.com/upload/images/photo_thumbnail.jpg", "blurryThumbnailUrl": "https://example.qiscus.com/upload/images/photo_blurry.jpg" } ``` ``` -------------------------------- ### Initialize and Use Qiscus Chat SDK in Flutter Source: https://github.com/qiscus/qiscus-chat-sdk-flutter/blob/master/README.md This snippet shows how to initialize the Qiscus SDK with an App ID and handle potential errors. It also demonstrates clearing user data upon widget disposal. Ensure the SDK is initialized before use. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; import 'package:flutter/widgets.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) => MyHomepage(); } class MyHomepage extends StatefulWidget { @override _MyHomepageState createState() => _MyHomepageState(); } class _MyHomepageState extends State { QiscusSDK _qiscusSDK; @override void initState() { super.initState(); Future.microtask(() { _qiscusSDK = QiscusSDK.withAppId('sdksample', callback: (error) { if (error != null) { return print('Error happend while initializing qiscus sdk: $error'); } print('Qiscus SDK Ready to use'); }); }); } @override void dispose() { super.dispose(); _qiscusSDK?.clearUser(callback: (error) { // ignore error }); } @override Widget build(BuildContext context) { return Container(); } } ``` -------------------------------- ### Subscribe to Chat Room Events Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Subscribe to a chat room to receive real-time updates for messages, read receipts, typing indicators, and room clearing. Use `.listen()` on the returned stream to process events. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Subscribe to a chat room for real-time events qiscus.subscribeChatRoom(room); // Listen for new messages qiscus.onMessageReceived().listen((QMessage message) { print('New message from ${message.sender.name}: ${message.text}'); }); // Listen for message read status qiscus.onMessageRead().listen((QMessage message) { print('Message ${message.id} was read'); }); // Listen for message delivered status qiscus.onMessageDelivered().listen((QMessage message) { print('Message ${message.id} was delivered'); }); // Listen for message updates qiscus.onMessageUpdated().listen((QMessage message) { print('Message ${message.id} was updated'); }); // Listen for deleted messages qiscus.onMessageDeleted().listen((QMessage message) { print('Message ${message.id} was deleted'); }); // Listen for typing indicators qiscus.onUserTyping().listen((QUserTyping typing) { if (typing.isTyping) { print('${typing.userId} is typing in room ${typing.roomId}'); } }); // Listen for cleared rooms qiscus.onChatRoomCleared().listen((int roomId) { print('Room $roomId was cleared'); }); // Unsubscribe from room when done qiscus.unsubscribeChatRoom(room); ``` -------------------------------- ### Retrieve Chat Rooms and Messages in Flutter Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Fetch chat rooms, messages, and room details with pagination and filtering options. Ensure the Qiscus SDK is initialized. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Get all chat rooms with pagination List allRooms = await qiscus.getAllChatRooms( showParticipant: true, showRemoved: false, showEmpty: false, limit: 20, page: 1, ); // Get specific rooms by IDs List rooms = await qiscus.getChatRooms( roomIds: [123, 456, 789], showParticipants: true, ); // Get room with its messages QChatRoomWithMessages roomWithMessages = await qiscus.getChatRoomWithMessages( roomId: 123, ); print('Room: ${roomWithMessages.room.name}'); print('Messages count: ${roomWithMessages.messages.length}'); // Load previous messages (pagination) List previousMessages = await qiscus.getPreviousMessagesById( roomId: 123, messageId: 1000, // Load messages before this ID limit: 20, ); // Load newer messages List newerMessages = await qiscus.getNextMessagesById( roomId: 123, messageId: 500, // Load messages after this ID limit: 20, ); // Get file list from rooms List files = await qiscus.getFileList( roomIds: [123, 456], fileType: 'image', includeExtensions: ['jpg', 'png', 'gif'], excludeExtensions: ['svg'], limit: 50, ); // Get total unread message count int unreadCount = await qiscus.getTotalUnreadCount(); print('Total unread messages: $unreadCount'); ``` -------------------------------- ### Authenticate Users Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Manage user sessions using basic credentials or identity tokens. Includes methods for checking authentication status and logging out. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Set user with basic authentication QAccount account = await qiscus.setUser( userId: 'user@example.com', userKey: 'secure-password', username: 'John Doe', avatarUrl: 'https://example.com/avatar.png', extras: {'role': 'premium', 'department': 'sales'}, ); print('Logged in as: ${account.name}'); print('User ID: ${account.id}'); // Or authenticate with identity token (JWT) String nonce = await qiscus.getJWTNonce(); // Send nonce to your backend, get identity token back String identityToken = await yourBackend.getIdentityToken(nonce); QAccount account = await qiscus.setUserWithIdentityToken(token: identityToken); // Check if user is authenticated bool isLoggedIn = qiscus.hasSetupUser(); QAccount? currentUser = qiscus.currentUser; // Get current user data from server QAccount userData = await qiscus.getUserData(); // Clear user session (logout) await qiscus.clearUser(); ``` -------------------------------- ### Chat Room Management Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Methods for creating and retrieving different types of chat rooms. ```APIDOC ## Chat Room Management ### Description Create and manage single chats, group chats, and public channels. ### Methods - `chatUser({String userId, Map extras})` - `createGroupChat({String name, List userIds, String avatarUrl, Map extras})` - `createChannel({String uniqueId, String name, String avatarUrl, Map extras})` ### Parameters #### Request Body - **userId** (String) - Required (for chatUser) - Target user ID - **userIds** (List) - Required (for createGroupChat) - List of participant IDs - **name** (String) - Required (for group/channel) - Room name - **uniqueId** (String) - Required (for createChannel) - Unique identifier for the channel ``` -------------------------------- ### Push Notifications Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt APIs for registering and managing device tokens for receiving push notifications. ```APIDOC ## Push Notifications ### Description Register and manage device tokens for push notifications. ### Method POST (for registration), DELETE (for removal) ### Endpoint `/users/me/devices` (Hypothetical endpoint, actual SDK methods are `registerDeviceToken` and `removeDeviceToken`) ### Parameters #### Request Body (for registration) - **token** (string) - Required - The device token obtained from the push notification service (e.g., FCM). - **isDevelopment** (boolean) - Required - Specifies if the token is for a development (true) or production (false) environment. #### Request Body (for removal) - **token** (string) - Required - The device token to remove. - **isDevelopment** (boolean) - Required - Specifies if the token is for a development (true) or production (false) environment. ### Request Example (Register) ```dart bool registered = await qiscus.registerDeviceToken( token: 'firebase-device-token-here', isDevelopment: false, // Set true for development/sandbox ); ``` ### Request Example (Remove) ```dart bool removed = await qiscus.removeDeviceToken( token: 'firebase-device-token-here', isDevelopment: false, ); ``` ### Response #### Success Response (200) - **registered** (boolean) - True if the token was successfully registered, false otherwise. - **removed** (boolean) - True if the token was successfully removed, false otherwise. ``` -------------------------------- ### Managing Room Participants API Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt This section explains how to add and remove participants from group chat rooms, and retrieve participant lists. ```APIDOC ## Managing Room Participants Add or remove participants from group chat rooms. ### Add Participants to a Group Chat ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; List addedParticipants = await qiscus.addParticipants( roomId: 123, userIds: ['newuser1@example.com', 'newuser2@example.com'], ); print('Added ${addedParticipants.length} participants'); ``` ### Get Participants List ```dart List participants = await qiscus.getParticipants( roomUniqueId: 'room-unique-id', page: 1, limit: 100, sorting: 'asc', ); for (var participant in participants) { print('${participant.name} - Last read: ${participant.lastReadMessageId}'); } ``` ### Remove Participants from a Group Chat ```dart List removedIds = await qiscus.removeParticipants( roomId: 123, userIds: ['user-to-remove@example.com'], ); print('Removed users: $removedIds'); ``` ``` -------------------------------- ### Search and Manage Users Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Search for users by username, update your profile information, block or unblock users, and retrieve a list of blocked users. These operations help in managing user interactions within the chat. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Search for users List users = await qiscus.getUsers( searchUsername: 'john', page: 1, limit: 20, ); for (var user in users) { print('${user.name} (${user.id})'); } // Update current user profile QAccount updatedAccount = await qiscus.updateUser( name: 'John Smith', avatarUrl: 'https://example.com/new-avatar.png', extras: {'bio': 'Software developer', 'location': 'NYC'}, ); // Block a user QUser blockedUser = await qiscus.blockUser(userId: 'spammer@example.com'); print('Blocked: ${blockedUser.name}'); // Get list of blocked users List blockedUsers = await qiscus.getBlockedUsers( page: 1, limit: 50, ); // Unblock a user QUser unblockedUser = await qiscus.unblockUser(userId: 'spammer@example.com'); ``` -------------------------------- ### Subscribe to Custom Events Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Subscribe to custom real-time events within a specific chat room. You can define and listen for any custom event payload, such as reactions or notifications. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Subscribe to custom events in a room Stream> customEventStream = qiscus.subscribeCustomEvent( roomId: 123, ); customEventStream.listen((Map payload) { print('Received custom event: $payload'); if (payload['type'] == 'reaction') { print('User ${payload['user_id']} reacted with ${payload['emoji']}'); } }); // Unsubscribe when done qiscus.unsubscribeCustomEvent(roomId: 123); ``` -------------------------------- ### Sending Messages API Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt This section covers how to generate and send various types of messages, including text, files, custom payloads, and replies, as well as uploading files with progress tracking. ```APIDOC ## Sending Messages Generate and send different types of messages including text, files, custom payloads, and replies. ### Text Message ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; QMessage textMessage = qiscus.generateMessage( chatRoomId: room.id, text: 'Hello, how are you?', extras: {'custom_field': 'value'}, ); QMessage sentMessage = await qiscus.sendMessage(message: textMessage); print('Message sent with ID: ${sentMessage.id}'); print('Status: ${sentMessage.status}'); ``` ### Custom Message ```dart QMessage customMessage = qiscus.generateCustomMessage( chatRoomId: room.id, text: 'Product Card', type: 'product', payload: { 'product_id': 'SKU-12345', 'name': 'Wireless Headphones', 'price': 99.99, 'image_url': 'https://example.com/product.jpg', }, extras: {'source': 'catalog'}, ); await qiscus.sendMessage(message: customMessage); ``` ### File Attachment Message ```dart QMessage fileMessage = qiscus.generateFileAttachmentMessage( chatRoomId: room.id, caption: 'Check out this document', url: 'https://example.com/files/document.pdf', filename: 'document.pdf', size: 1024000, ); await qiscus.sendMessage(message: fileMessage); ``` ### Reply Message ```dart QMessage replyMessage = qiscus.generateReplyMessage( chatRoomId: room.id, text: 'Yes, I agree with this!', repliedMessage: originalMessage, ); await qiscus.sendMessage(message: replyMessage); ``` ### Upload and Send File with Progress Tracking ```dart import 'dart:io'; File imageFile = File('/path/to/image.jpg'); Stream> uploadStream = qiscus.sendFileMessage( message: qiscus.generateMessage(chatRoomId: room.id, text: 'Image'), file: imageFile, ); uploadStream.listen((progress) { if (progress.data != null) { print('File sent: ${progress.data!.id}'); } else { print('Upload progress: ${progress.progress}%'); } }); ``` ``` -------------------------------- ### User Authentication Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Endpoints for managing user sessions, including login, JWT authentication, and logout. ```APIDOC ## User Authentication ### Description Handles user authentication using credentials or identity tokens. ### Methods - `setUser({String userId, String userKey, String username, String avatarUrl, Map extras})` - `setUserWithIdentityToken({String token})` - `clearUser()` ### Parameters #### Request Body - **userId** (String) - Required - Unique identifier for the user - **userKey** (String) - Required - User authentication key - **username** (String) - Optional - Display name - **avatarUrl** (String) - Optional - URL for user avatar - **extras** (Map) - Optional - Additional user metadata ``` -------------------------------- ### Retrieving Chat Rooms and Messages API Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt This section details how to fetch chat rooms, messages, and room details with various filtering and pagination options. ```APIDOC ## Retrieving Chat Rooms and Messages Fetch chat rooms, messages, and room details with various filtering options. ### Get All Chat Rooms ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; List allRooms = await qiscus.getAllChatRooms( showParticipant: true, showRemoved: false, showEmpty: false, limit: 20, page: 1, ); ``` ### Get Specific Rooms by IDs ```dart List rooms = await qiscus.getChatRooms( roomIds: [123, 456, 789], showParticipants: true, ); ``` ### Get Room with its Messages ```dart QChatRoomWithMessages roomWithMessages = await qiscus.getChatRoomWithMessages( roomId: 123, ); print('Room: ${roomWithMessages.room.name}'); print('Messages count: ${roomWithMessages.messages.length}'); ``` ### Load Previous Messages (Pagination) ```dart List previousMessages = await qiscus.getPreviousMessagesById( roomId: 123, messageId: 1000, // Load messages before this ID limit: 20, ); ``` ### Load Newer Messages ```dart List newerMessages = await qiscus.getNextMessagesById( roomId: 123, messageId: 500, // Load messages after this ID limit: 20, ); ``` ### Get File List from Rooms ```dart List files = await qiscus.getFileList( roomIds: [123, 456], fileType: 'image', includeExtensions: ['jpg', 'png', 'gif'], excludeExtensions: ['svg'], limit: 50, ); ``` ### Get Total Unread Message Count ```dart int unreadCount = await qiscus.getTotalUnreadCount(); print('Total unread messages: $unreadCount'); ``` ``` -------------------------------- ### Manage Push Notification Tokens Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Registers or removes device tokens for push notifications. Set isDevelopment to true for sandbox environments. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Register device token for push notifications bool registered = await qiscus.registerDeviceToken( token: 'firebase-device-token-here', isDevelopment: false, // Set true for development/sandbox ); if (registered) { print('Device token registered successfully'); } // Remove device token (e.g., on logout) bool removed = await qiscus.removeDeviceToken( token: 'firebase-device-token-here', isDevelopment: false, ); ``` -------------------------------- ### Publish and Manage Typing Indicators Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Publish typing indicators to notify others when you are typing in a room, and stop publishing when you are done. This helps in providing a real-time chat experience. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Publish typing indicator await qiscus.publishTyping(roomId: 123, isTyping: true); // Stop typing indicator await qiscus.publishTyping(roomId: 123, isTyping: false); ``` -------------------------------- ### Publish Custom Events Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Publish custom events to a specific chat room. This allows for real-time communication of custom data, such as user reactions or specific notifications. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Publish a custom event await qiscus.publishCustomEvent( roomId: 123, payload: { 'type': 'reaction', 'message_id': 456, 'emoji': '👍', 'user_id': 'current-user', }, ); ``` -------------------------------- ### Subscribe to User Online Presence Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Subscribe to receive real-time updates on a specific user's online status. You can also publish your own online presence status. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Subscribe to a user's online presence qiscus.subscribeUserOnlinePresence('user@example.com'); // Listen for presence updates qiscus.onUserOnlinePresence().listen((QUserPresence presence) { print('${presence.userId} is ${presence.isOnline ? 'online' : 'offline'}'); print('Last seen: ${presence.lastSeen}'); }); // Publish your online status await qiscus.publishOnlinePresence(isOnline: true); // Unsubscribe from presence qiscus.unsubscribeUserOnlinePresence('user@example.com'); ``` -------------------------------- ### Manage Room Participants in Flutter Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Add or remove participants from group chat rooms. Requires a valid room ID and user IDs. Ensure the Qiscus SDK is initialized. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Add participants to a group chat List addedParticipants = await qiscus.addParticipants( roomId: 123, userIds: ['newuser1@example.com', 'newuser2@example.com'], ); print('Added ${addedParticipants.length} participants'); // Get participants list List participants = await qiscus.getParticipants( roomUniqueId: 'room-unique-id', page: 1, limit: 100, sorting: 'asc', ); for (var participant in participants) { print('${participant.name} - Last read: ${participant.lastReadMessageId}'); } // Remove participants from a group chat List removedIds = await qiscus.removeParticipants( roomId: 123, userIds: ['user-to-remove@example.com'], ); print('Removed users: $removedIds'); ``` -------------------------------- ### Update an Existing Message Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Update the content of an existing message. Pass the `QMessage` object representing the message to be updated. ```dart // Update an existing message QMessage updatedMessage = await qiscus.updateMessage(message: existingMessage); ``` -------------------------------- ### Update Chat Room Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Allows updating properties of an existing chat room, such as its name, avatar, and custom extras. ```APIDOC ## Update Chat Room ### Description Update chat room properties like name, avatar, and extras. ### Method POST (or PUT, depending on SDK implementation) ### Endpoint `/chat/rooms/{roomId}` (Hypothetical endpoint, actual SDK method is `updateChatRoom`) ### Parameters #### Path Parameters - **roomId** (integer) - Required - The unique identifier of the chat room to update. #### Request Body - **name** (string) - Optional - The new name for the chat room. - **avatarUrl** (string) - Optional - The URL for the new avatar of the chat room. - **extras** (Map) - Optional - A map of additional custom data to associate with the chat room. ### Request Example ```dart QChatRoom updatedRoom = await qiscus.updateChatRoom( roomId: 123, name: 'Updated Room Name', avatarUrl: 'https://example.com/new-room-avatar.png', extras: { 'description': 'This is our project room', 'created_by': 'admin', 'tags': ['work', 'important'], }, ); ``` ### Response #### Success Response (200) - **QChatRoom** (object) - The updated chat room object. #### Response Example ```json { "id": 123, "name": "Updated Room Name", "avatarUrl": "https://example.com/new-room-avatar.png", "extras": { "description": "This is our project room", "created_by": "admin", "tags": ["work", "important"] } } ``` ``` -------------------------------- ### Send Various Message Types in Flutter Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Use this to send text, custom, file attachment, or reply messages. Ensure you have initialized the Qiscus SDK and have a valid room object. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; import 'dart:io'; // Send a text message QMessage textMessage = qiscus.generateMessage( chatRoomId: room.id, text: 'Hello, how are you?', extras: {'custom_field': 'value'}, ); QMessage sentMessage = await qiscus.sendMessage(message: textMessage); print('Message sent with ID: ${sentMessage.id}'); print('Status: ${sentMessage.status}'); // sending -> sent -> delivered -> read // Send a custom message with structured payload QMessage customMessage = qiscus.generateCustomMessage( chatRoomId: room.id, text: 'Product Card', type: 'product', payload: { 'product_id': 'SKU-12345', 'name': 'Wireless Headphones', 'price': 99.99, 'image_url': 'https://example.com/product.jpg', }, extras: {'source': 'catalog'}, ); await qiscus.sendMessage(message: customMessage); // Send a file attachment message QMessage fileMessage = qiscus.generateFileAttachmentMessage( chatRoomId: room.id, caption: 'Check out this document', url: 'https://example.com/files/document.pdf', filename: 'document.pdf', size: 1024000, ); await qiscus.sendMessage(message: fileMessage); // Send a reply to an existing message QMessage replyMessage = qiscus.generateReplyMessage( chatRoomId: room.id, text: 'Yes, I agree with this!', repliedMessage: originalMessage, ); await qiscus.sendMessage(message: replyMessage); // Upload and send a file with progress tracking File imageFile = File('/path/to/image.jpg'); Stream> uploadStream = qiscus.sendFileMessage( message: qiscus.generateMessage(chatRoomId: room.id, text: 'Image'), file: imageFile, ); uploadStream.listen((progress) { if (progress.data != null) { print('File sent: ${progress.data!.id}'); } else { print('Upload progress: ${progress.progress}%'); } }); ``` -------------------------------- ### Mark Messages as Delivered or Read Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Use these methods to update the status of messages to delivered or read within a specific room. Requires room and message identifiers. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Mark a message as delivered await qiscus.markAsDelivered( roomId: 123, messageId: 456, ); // Mark a message as read await qiscus.markAsRead( roomId: 123, messageId: 456, ); ``` -------------------------------- ### Update Chat Room Properties Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Updates room details such as name, avatar, and custom extras. Requires a valid roomId. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Update room details QChatRoom updatedRoom = await qiscus.updateChatRoom( roomId: 123, name: 'Updated Room Name', avatarUrl: 'https://example.com/new-room-avatar.png', extras: { 'description': 'This is our project room', 'created_by': 'admin', 'tags': ['work', 'important'], }, ); print('Room updated: ${updatedRoom.name}'); ``` -------------------------------- ### Message Interceptors Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt APIs for intercepting messages before they are sent or received for custom processing. ```APIDOC ## Message Interceptors ### Description Intercept messages before they are sent or received for custom processing. ### Methods - **intercept(interceptor: QInterceptor, callback: Function)**: Registers an interceptor for message processing. ### Interceptor Types - **QInterceptor.messageBeforeSent**: Intercepts messages just before they are sent. - **QInterceptor.messageBeforeReceived**: Intercepts messages just before they are received by the client. ### Registering Interceptors #### Message Before Sent ```dart var removeBeforeSentHook = qiscus.intercept( interceptor: QInterceptor.messageBeforeSent, callback: (QMessage message) async { // Modify message before sending message.extras ??= {}; message.extras!['client_timestamp'] = DateTime.now().toIso8601String(); message.extras!['app_version'] = '1.0.0'; return message; }, ); ``` #### Message Before Received ```dart var removeBeforeReceivedHook = qiscus.intercept( interceptor: QInterceptor.messageBeforeReceived, callback: (QMessage message) async { // Process or filter incoming messages print('Incoming message: ${message.text}'); return message; }, ); ``` ### Removing Interceptors Interceptors can be removed by calling the function returned when registering them. ```dart removeBeforeSentHook(); removeBeforeReceivedHook(); ``` ``` -------------------------------- ### Delete and Clear Messages Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Delete specific messages by their unique IDs or clear all messages within specified chat rooms. Ensure you have the correct unique IDs for messages and rooms. ```dart // Delete messages List deletedMessages = await qiscus.deleteMessages( messageUniqueIds: ['unique-id-1', 'unique-id-2'], ); // Clear all messages in a room await qiscus.clearMessagesByChatRoomId( roomUniqueIds: ['room-unique-id-1', 'room-unique-id-2'], ); ``` -------------------------------- ### Intercept Messages Source: https://context7.com/qiscus/qiscus-chat-sdk-flutter/llms.txt Hooks into message lifecycle to modify or process messages before sending or after receiving. Returns a function to remove the interceptor. ```dart import 'package:qiscus_chat_sdk/qiscus_chat_sdk.dart'; // Intercept messages before sending var removeBeforeSentHook = qiscus.intercept( interceptor: QInterceptor.messageBeforeSent, callback: (QMessage message) async { // Modify message before sending message.extras ??= {}; message.extras!['client_timestamp'] = DateTime.now().toIso8601String(); message.extras!['app_version'] = '1.0.0'; return message; }, ); // Intercept messages before receiving var removeBeforeReceivedHook = qiscus.intercept( interceptor: QInterceptor.messageBeforeReceived, callback: (QMessage message) async { // Process or filter incoming messages print('Incoming message: ${message.text}'); return message; }, ); // Remove interceptors when no longer needed removeBeforeSentHook(); removeBeforeReceivedHook(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.