tencent cloud

Feedback

Last updated: 2024-04-16 17:23:46
    This document describes how to integrate the SDK for Flutter.

    Environment Requirements

    Environment
    Version
    Flutter
    Flutter 3.0.0 or later for the Chat SDK; Flutter 3.16.0 or later for the TUIKit component library.
    Android
    Android Studio Dolphin | 2021.3.1 or later; and devices with Android 7.0 or later for apps
    iOS
    Xcode 12.0 or later. Ensure that your project has a valid developer signature.

    Supported Platforms

    We offer a set of Chat SDK and UIKit for all Flutter platforms, allowing you to run one set of code on all platforms.
    Platform
    Low-level SDK (tencent_cloud_chat_sdk)
    UIKit
    iOS
    Supported
    Supported
    Supported
    Android
    Supported
    Supported
    Supported
    Supported from v4.1.1+2
    Supported from v0.1.5
    Coming Soon...
    Supported from v4.1.9
    Supported from v2.0.0
    Supported
    Windows
    Supported from v4.1.9
    Supported from v2.0.0
    Supported
    Hybrid development (Add the SDK for Flutter to your existing native app)
    Supported from v5.0.0
    Supported from v1.0.0
    Supported
    Note:
    For Web and macOS integration requires a few extra steps. For more information, see Expanding to More Platforms.

    Prerequisites

    2. You have created an application as instructed in Creating and Upgrading an Application and recorded the SDKAppID.
    3. In the Chat console, select your application and click Auxiliary Tools > UserSig Generation & Verification on the left sidebar. Create two UserID values and their UserSig values, and copy the UserID, Key, and UserSig so they can be used to log in later.
    Note:
    This account is for development and testing only. Before the application is launched, the correct UserSig distribution method is to use the server to generate UserSig and provide an application-oriented API. When UserSig is needed, your application can send a request to the business server for a dynamic UserSig. For more information, see Generating UserSig.

    Selecting a Suitable Scheme to Integrate the SDK for Flutter

    
    Chat
    offers three integration schemes:
    Integration Scheme
    Applicable Scenario
    The Chat sample app is a complete chat application built with UIKit. If you need to implement chat scenarios, you can use the sample app for secondary development. Try it out here.
    The Chat UI component library UIKit provides common UI components, such as conversation list, chat UI, and contacts. You can use the component library to quickly build a custom Chat application as needed. This scheme is recommended.
    You can use the Low-level SDK, if UIKit cannot meet your UI requirements or you want to further customize your UI.

    Scheme 1. Modifying the Sample App

    This sample app is built with the UIKit V2.

    Running Sample App

    1. Download the source code and install dependencies:
    # Clone the code
    git clone https://github.com/TencentCloud/chat-demo-flutter.git
    
    # Checkout the 'v2' branch
    git checkout v2
    
    # Clean the project. Important
    flutter clean
    
    # Install dependencies
    flutter pub get
    2. Configure the user info for login.
    Open lib/config.dart, and specify the sdkappid, userid, and usersig obtained and generated in the previous step.
    3. Run the app.
    flutter run

    Sample app code structure

    Folder
    Features
    lib
    Program core directory
    lib/desktop
    Desktop adaptation related code
    lib/setting
    The related code for Profile and Settings pages
    The lib directory's lib/main.dart file is the core file of this sample app program. As you can see, there are several lines of key code. The List<Widget> pages component list is passed into bottomNavigation for page switching.
    pages = [ const TencentCloudChatConversation(), const TencentCloudChatContact(), TencentCloudChatSettings( removeSettings: removeLocalSetting, setLoginState: changeLoginState, ), ];
    Although the new version of UIKit has many components, these components are built-in support for routing and navigation. That is, to minimize the use, only manually use the TencentCloudChatConversation conversation list component and TencentCloudChatContact contacts component, you can use all associated UIKit components, including the Message, Contact, and Group Profile components, etc. These components can be navigated to through the components you manually import.
    If you have more advanced customization requirements for using the UIKit, you can refer to the quick start document of UIKit.

    Scheme 2. Using UIKit Component Library to Quickly Integrate Chat Capabilities

    Our new Flutter Chat UIKit V2 provides developers with a comprehensive set of tools to easily create feature-rich chat applications.
    It is built with a modular approach, allowing you to pick and choose the components you need while keeping your application lightweight and efficient.
    The UIKit includes a wide range of capabilities, such as Conversation List, Message handling, Contact lists, User and Group Profiles, Search functionality, and more.
    
    
    
    This section provides a brief overview of how to integrate and use the UIKit. For a more comprehensive guide, please refer to the Quick Start documentation provided Integrating Basic Features - Flutter.

    Compatibility

    Our UIKit supports both mobile, tablet and desktop UI styles, and is compatible with Android, iOS, macOS, Windows, and Web (will be supported in future versions).
    It comes with built-in support for English, Simplified Chinese, Traditional Chinese, Japanese, Korean, and Arabic languages (with support for Arabic RTL interface), and light and dark appearance styles.

    Requirements

    Flutter version: 3.16 or above
    Dart version: 3.0 or above

    Getting Started

    To start using our UIKit, first import the base package, tencent_cloud_chat.
    Next, import the required UI component packages that suit your needs from the following list:
    tencent_cloud_chat_group_search (In Beta)
    The architecture of our UIKit is shown below:
    
    
    
    Before you start using each Modular Package UI component, there are some initial setup steps you need to follow in your project.
    1. Prepare the necessary Tencent Cloud Chat configuration information, such as sdkappid, test userID, userSig, etc. You can refer to this document: https://www.tencentcloud.com/document/product/1047/45907#.E5.89.8D.E5.BA.8F.E5.B7.A5.E4.BD.9C
    2. In your Flutter project, install the main package and the optional Modular Packages mentioned in the Getting Started section above.
    3. Import TencentCloudChatMaterialApp:
    Replace your project's MaterialApp with TencentCloudChatMaterialApp. This will automatically manage and configure the language, theme (with material3), themeMode, and other settings, ensuring that the UIKit's interface parameters are consistent with your project.
    This step will take over the language, theme, and themeMode configuration of your project. If you do not want us to automatically manage all these configurations for your project, you can open TencentCloudChatMaterialApp, check its source code and implementation, and manually import the necessary capabilities in your project's MaterialApp.
    4. Initialization and Login:
    Call the TencentCloudChat.controller.initUIKit method to initialize and log in. The call instructions and reference code are as follows:
    await TencentCloudChat.controller.initUIKit(
    context: context,
    config: TencentCloudChatConfig(
    usedComponentsRegister: [
    TencentCloudChatConversationInstance.register,
    TencentCloudChatMessageInstance.register,
    /// The above registers are examples.
    /// In this field, pass in the register of each sub Modular UI Package.
    /// After installing each sub Modular UI Package, you need to declare it here before you can use it.
    ],
    preloadDataConfig: TencentCloudChatInitDataConfig(
    /// Config related to preloading data, used to improve performance
    ),
    userConfig: TencentCloudChatUserConfig(
    /// Config related to the user
    ),
    ),
    /// **[Critical]**: It's strongly advised to incorporate the following callback listeners for effectively managing SDK API errors and specific UIKit events that demand user attention. /// For detailed usage, please refer to the guide at https://pub.dev/packages/tencent_cloud_chat#introducing-callbacks-for-uikit . callbacks: TencentCloudChatCallbacks( onTencentCloudChatSDKFailCallback: (apiName, code, desc) {}, /// Handles SDK API errors. onTencentCloudChatUIKitUserNotificationEvent: (TencentCloudChatComponentsEnum component, TencentCloudChatUserNotificationEvent event) {}, /// Handles specific UIKit events that require user attention on a global scale. ),
    options: TencentCloudChatInitOptions(
    sdkAppID: , /// The SDKAppID of your Tencent Cloud Chat application
    userID: , /// The userID of the logged-in user
    userSig: , /// The userSig of the logged-in user
    sdkListener: V2TimSDKListener(), /// Event listener registered with the Chat SDK
    ),
    plugins: [], /// Used plugins, such as tencent_cloud_chat_robot, etc. For specific usage, refer to the README of each plugin.
    );
    Once you have completed the basic integration process of the UIKit, you can proceed to explore the documentations of each Modular Package to complete the integration of the individual UI components.
    This will help you understand the specific usage and customization options for each component, allowing you to create a tailored chat application that meets your requirements.
    For the integration of each individual modular UI components, see Integrating Basic Features - Flutter.

    Scheme 3. Implementing Your Own UI

    Prerequisites

    
    You
    have created a Flutter application or have an existing application that can be based on Flutter.

    Directions

    Installing the Chat SDK

    In this scheme, the term "Chat SDK" refers to the Low-level SDK.
    Run the following command to install the latest version of the Chat SDK for Flutter.
    flutter pub add tencent_cloud_chat_sdk
    Note: If your project also needs to be applied to web or desktop (macOS/Windows) platforms, you need to perform a few extra steps for SDK integration.

    Initializing the SDK

    Call initSDK to initialize the SDK.
    Pass in your sdkAppID.
    import 'package:tencent_cloud_chat_sdk/enum/V2TimSDKListener.dart';
    import 'package:tencent_cloud_chat_sdk/enum/log_level_enum.dart';
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    TencentImSDKPlugin.v2TIMManager.initSDK(
    sdkAppID: 0, // Replace 0 with the SDKAppID of your Chat application when integrating
    loglevel: LogLevelEnum.V2TIM_LOG_DEBUG, // Log
    listener: V2TimSDKListener(),
    );
    In this step, you can mount some listeners to the Chat SDK, mainly including those for network status and user information changes. For more information, see here.

    Logging in with a test account

    Log in with a test account initially generated for login verification.
    Call the TencentImSDKPlugin.v2TIMManager.login method to log in with the test account.
    If the returned res.code is 0, the login is successful.
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager.login (
    userID: userID,
    userSig: userSig,
    );
    Note:
    The test account is for development and testing only. Before the application is launched, the correct method for generating a UserSig is to integrate the UserSig calculation code into your server and provide an application-oriented API. When UserSig is needed, your application can send a request to the business server for a dynamic UserSig. For more information, see Generating UserSig.

    Sending a message

    The following shows how to send a text message:
    1. Call createTextMessage(String) to create a text message.
    2. Get the message ID from the returned value.
    3. Call sendMessage() and pass in the id, while receiver can be the ID of the other test account created earlier, groupID is not required for sending a one-to-one message.
    Sample code:
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    
    V2TimValueCallback<V2TimMsgCreateInfoResult> createMessage =
    await TencentImSDKPlugin.v2TIMManager
    .getMessageManager()
    .createTextMessage(text: "The text to create");
    
    String id = createMessage.data!.id!; // The message creation ID
    
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin.v2TIMManager
    .getMessageManager()
    .sendMessage(
    id: id, // Pass in the message creation ID to
    receiver: "The userID of the destination user",
    groupID: "The groupID of the destination group",
    );
    Note:
    If sending fails, it may be that your `sdkAppID` doesn't support sending messages to strangers. In this case, you can disable the relationship check feature in the console.
    Disable the friend relationship chain check here.

    Obtaining the conversation list

    Log in with the second test account to load the conversation list.
    The conversation list can be obtained in two ways:
    1. Listen for the persistent connection callback to update the conversation list in real time.
    2. Call an API to get the conversation list at certain time points.
    Common use cases include:
    Getting the conversation list when the application starts and listening for the persistent connection callback to update the conversation list in real time.
    Requesting the conversation list at certain time points
    To get the conversation list, you need to maintain nextSeq and record its current position.
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    
    String nextSeq = "0";
    
    getConversationList() async {
    V2TimValueCallback<V2TimConversationResult> res = await TencentImSDKPlugin
    .v2TIMManager
    .getConversationManager()
    .getConversationList(nextSeq: nextSeq, count: 10);
    
    nextSeq = res.data?.nextSeq ?? "0";
    }
    At this point, you can see the message sent by the first test account in the previous step.
    Listening for the persistent connection to get the conversation list in real time
    Mount the conversation list listener, process the callback event, and update the UI.
    1. Mount the listener.
    await TencentImSDKPlugin.v2TIMManager
    .getConversationManager()
    .setConversationListener(
    listener: new V2TimConversationListener(
    onConversationChanged: (List<V2TimConversation> list){
    _onConversationListChanged(list);
    },
    onNewConversation:(List<V2TimConversation> list){
    _onConversationListChanged(list);
    },
    2. Process the callback event and display the latest conversation list on the UI.
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    
    List<V2TimConversation> _conversationList = [];
    
    _onConversationListChanged(List<V2TimConversation> list) {
    for (int element = 0; element < list.length; element++) {
    int index = _conversationList.indexWhere(
    (item) => item!.conversationID == list[element].conversationID);
    if (index > -1) {
    _conversationList.setAll(index, [list[element]]);
    } else {
    _conversationList.add(list[element]);
    }
    }

    Receiving messages

    There are two methods to receive messages in the Chat SDK for Flutter:
    1. Listen for the persistent connection callback to get message changes and update and render the historical message list in real time.
    2. Call an API to load the message history at certain time points.
    Common use cases include:
    1. Requesting a certain number of historical messages to be displayed when a new conversation is opened in the UI.
    2. Listening for the persistent connection callback to receive messages in real time and adding them to the historical message list.
    Requesting the historical message list at certain time points
    To avoid affecting the loading speed, we recommend you limit the number of messages loaded to 20 per page.
    You need to dynamically record the current number of pages for the next request.
    Sample code:
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    
    V2TimValueCallback<List<V2TimMessage>> res = await TencentImSDKPlugin
    .v2TIMManager
    .getMessageManager()
    .getGroupHistoryMessageList(
    groupID: "groupID",
    count: 20,
    lastMsgID: "",
    );
    
    List<V2TimMessage> msgList = res.data ?? [];
    
    // here you can use msgList to render your message list
    }
    Listening for the persistent connection callback to get new messages in real time
    After the historical message list is initialized, new messages are from the persistent connection V2TimAdvancedMsgListener.onRecvNewMessage.
    After the onRecvNewMessage callback is triggered, you can add new messages to the historical message list as needed.
    Sample code for binding a listener:
    import 'package:tencent_cloud_chat_sdk/tencent_cloud_chat_sdk.dart';
    
    final adVancesMsgListener = V2TimAdvancedMsgListener(
    onRecvNewMessage: (V2TimMessage newMsg) {
    _onReceiveNewMsg(newMsg);
    },
    /// ... other listeners related to message
    );
    
    TencentImSDKPlugin.v2TIMManager
    .getMessageManager()
    .addAdvancedMsgListener(listener: adVancesMsgListener);
    At this point, you have completed the Chat module development, and now users can send and receive messages and enter different conversations.
    You can develop more features, such as group, user profile, relationship chain, offline push, and local search.
    For more information, see Integration Solution (No UI).

    Expanding to More Platforms

    Tencent Cloud Chat for Flutter SDKs support Android, iOS and Windows platforms by default. You can also expand to more platforms (web and macOS).

    Web

    To enable support for web, you need to perform the following extra steps in addition to those for enabling support for Android and iOS:

    Upgrading to Flutter 3.x

    Flutter 3.x has been dramatically optimized for web performance and is highly recommended for Flutter web project development.

    Importing JS

    Note:
    If your existing Flutter project does not support web, run flutter create . in the root directory of the project to add web support.
    Go to the web/ directory of your project and run npm or yarn to install relevant JS dependencies. Initialize the project as instructed.
    cd web
    
    npm init
    
    npm i @tencentcloud/chat
    
    npm i tim-upload-plugin
    Open web/index.html and import the JS files in <head> </head>. See below:
    <script src="./node_modules/tim-upload-plugin/index.js"></script>
    <script src="./node_modules/@tencentcloud/chat/index.js"></script> <script src="./node_modules/@tencentcloud/chat/modules/group-module.js"></script> <script src="./node_modules/@tencentcloud/chat/modules/relationship-module.js"></script> <script src="./node_modules/@tencentcloud/chat/modules/signaling-module.js"></script>
    
    
    

    macOS

    Additional configurations are required for the macOS platform. Follow the steps below to configure the macOS platform:
    1. Open the macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements files in your project.
    2. Add the following lines to each file:
    <key>com.apple.security.network.client</key>
    <true/>
    
    These lines grant your app the necessary permissions to access the network as a client.
    This configuration is essential for ensuring proper communication between your app and the backend services on the macOS platform.

    FAQs

    What should I do if Pods dependency installation fails in iOS devices?

    Solution 1: If an error occurs after the configuration, click Product > Clean Build Folder, clear the product, and run pod install or flutter run again.
    Solution 2: Manually delete the ios/Pods folder and the ios/Podfile.lock file and run the following command to reinstall the dependencies
    cd ios
    sudo gem install ffi
    pod install --repo-update

    Flutter environment

    If you want to check the Flutter environment, run Flutter doctor to detect whether the Flutter environment is ready.

    What should I do if an error occurs when I run the Demo on a Windows platform?

    Nuget.exe not found, trying to download or use cached version.
    This error message indicates that nuget.exe was not found on your system, so the program is attempting to download or use a cached one. Nuget.exe is a command-line utility for the NuGet Package Manager and is used to manage dependencies in .NET projects.
    To fix this issue, you can manually download and install nuget.exe by following these steps:
    1. Go to the download page on the NuGet official website: https://www.nuget.org/downloads
    2. Find the Windows x86 Commandline section and download nuget.exe as needed.
    3. Save the downloaded nuget.exe file to an appropriate location, for example, C:\\NuGet.
    4. Add the folder where you placed nuget.exe to your PATH environment variable to make the nuget.exe globally available in the command line.

    How do I query error codes?

    For Chat SDK API error codes, see here.
    For the UIKit errors and specific User Notification event calls, see here.
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support