Tencent Chat Logo

Tencent Cloud Chat SDK


Globally interconnected In-App Chat, user profile and relationship chains and offline push.


More languages: 简体中文 한국어 日本語


This pure Chat SDK do not contain UI components, you can choose our UI and business logic library tim_ui_kit if you tend to integrate quickly.


Experience DEMO

You can experience our Chat and Voice/Video Call modules via the following demo apps.

Those versions of demo has been build by the same Flutter project with our SDKs and extensions.

Mobile APP WEB - H5
[Recommend] iOS/Android APP
Scan for the Web DEMO

Environment Requirements

Version
Flutter Flutter 2.2.0 or later for the Chat SDK; Flutter 2.10.0 or later for the TUIKit integration component library.
Android Android Studio 3.5 or later; devices with Android 4.1 or later for apps
iOS Xcode 11.0 or later. Ensure that your project has a valid developer signature.

Supported Platforms

We are aiming to build a Chat SDK and TUIKit that supports all platforms of Flutter, helping you to develop once and deploy it on all platforms.

Platform non-UI Chat SDK (this package) UI components library (TUIKit)
iOS Supports Supports
Android Supports Supports
Web Supports since 4.1.1+2 version Supports since 0.1.5 version
macOS Supports since 4.1.9 version Coming soon
Windows Supports since 4.1.9 version Coming soon

Some extra steps are needed for Web/macOS/Windows, you can refer to "Flutter for Web support" and "Flutter for Desktop support" in this tutorial.

Preparation

  1. You have signed up for a Tencent Cloud account and completed identity verification.
  2. You have created an application as instructed in Creating and Upgrading an Application and recorded the SDKAppID.

Part 1. Creating a Test Account

In the IM console, select your application and click Auxiliary Tools > UserSig Generation & Verification on the left sidebar. Create two UserID and their corresponding UserSig, and copy the UserID, Key, and UserSig for subsequent logins.

? The account is for development and testing only. Before the application release, the correct UserSig distribution method is to generate UserSig on the 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.

Part 2. Selecting a Proper Scheme to Integrate the SDK for Flutter

Tencent Cloud Chat offers three integration schemes:

Use Case
Using the demo Our demo is a complete chat application with open-source code. If you need to implement chat scenarios, you can use the demo for secondary development. Try it out here.
Using UI library The Chat UI components library TUIKit provides common UI components, such as conversation list, chat page, and contact list. You can use those components to build an In-APP chat module to your Flutter APP quickly. This solution is recommended.
Self-implementing with this package Use this solution if TUIKit cannot meet your needs.

To better understand Chat SDK APIs, see API examples here, which shows how to call APIs and trigger listeners.

Part 3. Using the Demo

Running the demo

  1. Download the source code and install dependencies:
# Clone the code
git clone https://github.com/TencentCloud/TIMSDK.git

# Enter the demo directory of Flutter
cd TIMSDK/Flutter/Demo/im-flutter-uikit

# Install dependencies
flutter pub get
  1. Run the demo:
# Start the demo. Replace `SDK_APPID` and `KEY`
flutter run --dart-define=SDK_APPID={YOUR_SDKAPPID} --dart-define=ISPRODUCT_ENV=false --dart-define=KEY={YOUR_KEY}
  • --dart-define=SDK_APPID={YOUR_SDKAPPID}. Here, {YOUR_SDKAPPID} needs to be replaced with the SDKAppID of your application.
  • --dart-define=ISPRODUCT_ENV=false. Set it to false for a development environment.
  • --dart-define=KEY={YOUR_KEY}. Here, {YOUR_KEY} needs to be replaced with the Key recorded in Part 1. Creating a Test User.

Demo code structure

The TUIKit for Flutter is used for build the UI and business logic of the demo. The demo layer itself is only used to build the application, process navigation redirects, and call instantiated TUIKit components.

Folder Description
lib Core application directory
lib/i18n Internationalization code, excluding the internationalization capabilities and strings of TUIKit, which can be imported as needed.
lib/src Main application directory
lib/src/pages Important navigation pages of the demo. After the application is initialized, app.dart displays the loading animation, judges the login status, and redirects the user to login.dart or home_page.dart. After the user logs in, the login information will be stored locally through the shared_preference plugin and used for automatic login upon future application launch. If there is no such information or the login fails, the user will be redirected to the login page. During automatic login, the user is still on app.dart and can see the loading animation. home_page.dart has a bottom tab to switch between the four main feature pages of the demo.
lib/utils Some tool function classes.

Basically, a TUIKit component is imported into each dart file in lib/src. After the component is instantiated in the file, the page can be rendered.

Below are main files:

Main File in lib/src Description
add_friend.dart Friend request page that uses the TIMUIKitAddFriend component.
add_group.dart Group joining request page that uses the TIMUIKitAddGroup component.
blacklist.dart Blocklist page that uses the TIMUIKitBlackList component.
chat.dart Main chat page that uses all the chat capabilities of TUIKit and the TIMUIKitChat component.
chatv2.dart Main chat page that uses atomic capabilities and the TIMUIKitChat component.
contact.dart Contacts page that uses the TIMUIKitContact component.
conversation.dart Conversation list page that uses the TIMUIKitConversation component.
create_group.dart Group chat page that is implemented in the demo with no component used.
group_application_list.dart Group application list page that uses the TIMUIKitGroupApplicationList component.
group_list.dart Group list page that uses the TIMUIKitGroup component.
group_profile.dart Group profile and management page that uses the TIMUIKitGroupProfile component.
newContact.dart New contact request page that uses the TIMUIKitNewContact component.
routes.dart Demo route that navigates users to the login page login.dart or homepage home_page.dart.
search.dart Global search and in-conversation search page that uses the TIMUIKitSearch (global search) and TIMUIKitSearchMsgDetail (in-conversation search) components.
user_profile.dart User information and relationship chain maintenance page that uses the TIMUIKitProfile component.

You can modify the above demo for secondary development or implement your business needs based on it.

Part 4. Using TUIKit Component Library to implement In-App Chat module in Half a Day

TUIKit is a UI components library for Tencent Cloud Chat SDK. It provides common UI components, such as conversation list, chat page, and contact list.

It's suggested to use those components to build an In-APP chat module to your Flutter APP quickly.

img

For more details and tutorial, see TUIKit Quick Integration and get started.

Part 5. Self-Implementing Integration with this Chat SDK

Prerequisites

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

Directions

Installing the Chat SDK

For detailed directions involved in this section, see SDK Integration (Flutter).

Run the following command to install the latest Chat SDK for Flutter.

Run the following command:

flutter pub add tencent_im_sdk_plugin

Some extra steps are needed for Web/macOS/Windows, you can refer to "Flutter for Web support" and "Flutter for Desktop support" in this tutorial.

Initializing the SDK

For detailed directions involved in this section, see here.

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_im_sdk_plugin.dart';
    TencentImSDKPlugin.v2TIMManager.initSDK(
    sdkAppID: 0, // Replace `0` with the `SDKAppID` of your IM application during integration
    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 change. For more information, see V2TimSDKListener class.

Logging in with the test account

For detailed directions involved in this section, see Flutter.

Complete login verification using the test account created at the beginning.

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_im_sdk_plugin.dart';
 V2TimCallback res = await TencentImSDKPlugin.v2TIMManager.login (
    userID: userID,
    userSig: userSig, 
  );

? The account is for development and testing only. Before the application release, the correct UserSig distribution method is to integrate the UserSig calculation code into the 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

For detailed directions involved in this section, see here.

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() to send the message with the ID. receiver can be the ID of the other test account created earlier. groupID doesn't need to be entered for sending one-to-one messages.

Sample code:

import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.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",
          );

If sending failed, it may be that your sdkAppID doesn't support sending messages to strangers. In this case, enable the feature in the console for test.

Disable the friend relationship chain check here .

Getting the conversation list

For detailed directions involved in this section, see here.

After sending the test message in the previous step, log in with the other test account to load the conversation list.

There are two methods to load the conversation list:

  1. Listen on the persistent connection callback to update the conversation list in real time.
  2. Send a request through an API to get the paginated conversation list at one time.

Common use cases:

Get the conversation list upon application launch and listen on the persistent connection to update the conversation list in real time.

Requesting the conversation list at one time

To get the conversation list, you need to maintain nextSeq and record its current position.

import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.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 other test account in the previous step.

Listening on the persistent connection to get the real-time conversation list

Mount listeners to the SDK, process the callback event, and update the UI.

  1. Mount listeners.
await TencentImSDKPlugin.v2TIMManager
      .getConversationManager()
      .setConversationListener(
        listener: new V2TimConversationListener(
          onConversationChanged: (List<V2TimConversation> list){
            _onConversationListChanged(list);
    },
          onNewConversation:(List<V2TimConversation> list){
            _onConversationListChanged(list);
    },
  1. Process the callback event to display the latest conversation list on the UI.
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.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 a message

For detailed directions involved in this section, see here.

There are two methods to receive messages in the Chat SDK for Flutter:

  1. Listen on the persistent connection callback to get message changes and update and render the historical message list in real time.
  2. Send a request through an API to get paginated message history at one time.

Common use cases:

  1. When entering a new conversation, request a certain number of historical messages at one time to display the historical message list.
  2. Listen on the persistent connection to receive messages in real time and add them to the historical message list.
Requesting the historical message list at one time

We recommend you limit the number of messages loaded per page to 20 to avoid affecting the speed.

Dynamically record the current number of pages for the next request.

The sample code is as follows:

import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.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 on the persistent connection 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, add new messages to the historical message list as needed.

Below is the sample code for binding a listener:

import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.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. You 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.

Flutter for Web support

Web is supported since version of 4.1.1+2.

Some extra steps, as following, are needed for Web support.

Upgrade to Flutter 3.x

We strongly recommend you to upgrade to Flutter 3.x, as numerous optimizations for Web, since Flutter 3.0.

Install Flutter for Web Chat SDK

flutter pub add tencent_im_sdk_plugin_web

Import JS

Please execute flutter create . to add Web support to your project.

Download these two JS files from the following GitHub link, and placed them to web folder.

Add these lines to web/index.html between <head> </head>.

<script src='./tim-upload-plugin.js'></script>
<script src="./tim-js-friendship.js"></script>

Flutter for Desktop support

Desktop platforms, including Windows and macOS, are supported since version of 4.1.9.

Some extra steps, as following, are needed for Desktop support.

Upgrade to Flutter 3.x

Desktop platforms are only available since Flutter 3.0, thus you are supposed to upgrade first.

Install Flutter for Desktop Chat SDK

flutter pub add tencent_im_sdk_plugin_desktop

FAQs

What should I do if clicking Build And Run for an Android device triggers an error, stating no available device is found?

Check that the device is not occupied by other resources. Alternatively, click Build to generate an APK package, drag it to the simulator, and run it.

What should I do if an error occurs during the first run for an iOS device?

If an error occurs after the configuration, click Product > Clean Build Folder, clean the product, and run pod install or flutter run again.

20220714152720

What should I do if an error occurs during debugging on a real iOS device when I am wearing an Apple Watch?

20220714152340

Turn on Airplane Mode on your Apple Watch, and go to Settings > Bluetooth on your iPhone to turn off Bluetooth.

Restart Xcode (if opened) and run flutter run again.

What should I do when an error occurs on an Android device after TUIKit is imported into the application automatically generated by Flutter?

  1. Open android\app\src\main\AndroidManifest.xml and complete xmlns:tools="http://schemas.android.com/tools" / android:label="@string/android_label" / tools:replace="android:label" as follows.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Replace it with your Android package name"
    xmlns:tools="http://schemas.android.com/tools">
    <application
        android:label="@string/android_label"
        tools:replace="android:label"
        android:icon="@mipmap/ic_launcher" // Specify an icon path
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true">
  1. Open android\app\build.gradle and complete minSdkVersion and targetSdkVersion in defaultConfig.
defaultConfig {
  applicationId "" // Replace it with your Android package name
  minSdkVersion 21
  targetSdkVersion 30
}

What's more

In addition to Flutter SDK, we have numerous SDKs that covering all platforms. The following platforms can communicate with each other and provide services across devices and platforms.

Platform Introduction Demo Download UI Components library
Android Compatible with JDK 1.6 and Android SDK version 14 and later Get Get Get
iOS Compatible with iOS 8.0 and later Get Get Get
Mac Compatible with OS X 10.10 and later - Get -
Windows C and C++ are included. Compatible with Windows 7, Windows 8 and 8.1, and Windows 10. Both 32-bit and 64-bit programs can be connected - Get -
Web Supports Internet Explorer 11+, Chrome 7+, Firefox 3.6+, Opera 12+ and Safari 6+ Get Get Get
Unity Supports 2020.2.7f1c1 or later - Get -
Flutter Supports Flutter 2 & dart 2.12 and later, deploying to Android, iOS, Web, macOS and Windows. Get Here Get
Electron Electron SDK - Get -

Contact Us

Please do not hesitate to contact us in the following place, if you have any further questions or tend to learn more about the use cases.

Our Website: www.tencentcloud.com/products/im?from=pub

Libraries

enum/at_info_types
enum/callbacks
enum/conversation_type
enum/friend_application_type_enum
enum/friend_response_type_enum
enum/friend_type
enum/friend_type_enum
enum/get_group_message_read_member_list_filter
enum/group_add_opt_enum
enum/group_add_opt_type
enum/group_application_handle_result
enum/group_application_handle_status
enum/group_application_type
enum/group_application_type_enum
enum/group_change_info_type
enum/group_member_filter_enum
enum/group_member_filter_type
enum/group_member_role
enum/group_member_role_enum
enum/group_tips_elem_type
enum/group_type
enum/history_message_get_type
enum/history_msg_get_type_enum
enum/image_types
enum/listener_type
enum/log_level
enum/log_level_enum
enum/message_elem_type
enum/message_priority
enum/message_priority_enum
enum/message_status
enum/offlinePushInfo
enum/receive_message_opt_enum
enum/simpleMsgListenerType
enum/user_info_allow_type
enum/utils
enum/v2_signaling_action_type
enum/v2_tim_conversation_marktype
enum/v2_tim_keyword_list_match_type
enum/v2_tim_plugins
enum/V2TimAdvancedMsgListener
enum/V2TimCommunityListener
enum/V2TimConversationListener
enum/V2TimFriendshipListener
enum/V2TimGroupListener
enum/V2TIMManager
enum/V2TimSDKListener
enum/V2TimSignalingListener
enum/V2TimSimpleMsgListener
enum/V2TimUIKitListener
manager/v2_tim_community_manager
manager/v2_tim_conversation_manager
manager/v2_tim_friendship_manager
manager/v2_tim_group_manager
manager/v2_tim_manager
manager/v2_tim_message_manager
manager/v2_tim_offline_push_manager
manager/v2_tim_signaling_manager
models/user_status_type
models/v2_tim_application_processed
models/v2_tim_callback
models/v2_tim_conversation
models/v2_tim_conversation_filter
models/v2_tim_conversation_operation_result
models/v2_tim_conversation_result
models/v2_tim_conversationList_filter
models/v2_tim_create_group_member_info
models/v2_tim_custom_elem
models/v2_tim_elem
models/v2_tim_face_elem
models/v2_tim_file_elem
models/v2_tim_follow_info
models/v2_tim_follow_operation_result
models/v2_tim_follow_type_check_result
models/v2_tim_friend_application
models/v2_tim_friend_application_result
models/v2_tim_friend_check_result
models/v2_tim_friend_group
models/v2_tim_friend_info
models/v2_tim_friend_info_result
models/v2_tim_friend_operation_result
models/v2_tim_friend_search_param
models/v2_tim_grant_administrator
models/v2_tim_group_application
models/v2_tim_group_application_result
models/v2_tim_group_at_info
models/v2_tim_group_attribute_changed
models/v2_tim_group_change_info
models/v2_tim_group_created
models/v2_tim_group_dismissed
models/v2_tim_group_info
models/v2_tim_group_info_changed
models/v2_tim_group_info_result
models/v2_tim_group_member
models/v2_tim_group_member_change_info
models/v2_tim_group_member_full_info
models/v2_tim_group_member_info
models/v2_tim_group_member_info_result
models/v2_tim_group_member_operation_result
models/v2_tim_group_member_search_param
models/v2_tim_group_member_search_result
models/v2_tim_group_message_read_member_list
models/v2_tim_group_recycled
models/v2_tim_group_search_param
models/v2_tim_group_tips_elem
models/v2_tim_image
models/v2_tim_image_elem
models/v2_tim_location_elem
models/v2_tim_member
models/v2_tim_member_enter
models/v2_tim_member_info_changed
models/v2_tim_member_invited
models/v2_tim_member_kicked
models/v2_tim_member_leave
models/v2_tim_merger_elem
models/v2_tim_message
models/v2_tim_message_change_info
models/v2_tim_message_download_progress
models/v2_tim_message_extension
models/v2_tim_message_extension_result
models/v2_tim_message_list_result
models/v2_tim_message_online_url
models/v2_tim_message_reaction
models/v2_tim_message_reaction_change_info
models/v2_tim_message_reaction_result
models/v2_tim_message_reaction_user_result
models/v2_tim_message_receipt
models/v2_tim_message_search_param
models/v2_tim_message_search_result
models/v2_tim_message_search_result_item
models/v2_tim_msg_create_info_result
models/v2_tim_official_account_info
models/v2_tim_official_account_info_result
models/v2_tim_offline_push_info
models/v2_tim_permission_group_info
models/v2_tim_permission_group_info_result
models/v2_tim_permission_group_member_info_result
models/v2_tim_permission_group_member_operation_result
models/v2_tim_permission_group_operation_result
models/v2_tim_quit_from_group
models/v2_tim_receive_message_opt_info
models/v2_tim_receive_rest_custom_data
models/v2_tim_recv_c2c_custom_message
models/v2_tim_recv_c2c_text_message
models/v2_tim_recv_group_custom_message
models/v2_tim_recv_group_text_message
models/v2_tim_revoke_administrator
models/v2_tim_signaling_info
models/v2_tim_sound_elem
models/v2_tim_text_elem
models/v2_tim_topic_info
models/v2_tim_topic_info_result
models/v2_tim_topic_operation_result
models/v2_tim_topic_permission_result
models/v2_tim_user_full_info
models/v2_tim_user_info
models/v2_tim_user_info_result
models/v2_tim_user_status
models/v2_tim_value_callback
models/v2_tim_video_elem
tencent_cloud_chat_sdk_method_channel
tencent_cloud_chat_sdk_platform_interface
tencent_cloud_chat_sdk_web
tencent_im_sdk_plugin
utils/const
utils/utils
web/enum/conversation_type
web/enum/event_enum
web/enum/friend_type
web/enum/group_add_opt
web/enum/group_member_role
web/enum/group_receive_message_opt
web/enum/group_tips_type
web/enum/group_type
web/enum/message_priority
web/enum/message_type
web/manager/im_sdk_plugin_js
web/manager/v2_tim_conversation_manager
web/manager/v2_tim_friendship_manager
web/manager/v2_tim_group_manager
web/manager/v2_tim_manager
web/manager/v2_tim_message_manager
web/manager/v2_tim_signaling_manager
web/models/v2_tim_add_friend
web/models/v2_tim_check_friend
web/models/v2_tim_create_message
web/models/v2_tim_delete_conversation
web/models/v2_tim_delete_group_attributes
web/models/v2_tim_friend_black_list
web/models/v2_tim_friend_group
web/models/v2_tim_friend_info
web/models/v2_tim_friend_list
web/models/v2_tim_get_conversation
web/models/v2_tim_get_conversation_list
web/models/v2_tim_get_conversation_list_by_id
web/models/v2_tim_get_group_attributes
web/models/v2_tim_get_group_member_list
web/models/v2_tim_get_group_members_info
web/models/v2_tim_get_message_list
web/models/v2_tim_group_create
web/models/v2_tim_group_join
web/models/v2_tim_handle_group_application
web/models/v2_tim_init_sdk
web/models/v2_tim_invite_user_to_group
web/models/v2_tim_js_message
web/models/v2_tim_kick_group_member
web/models/v2_tim_login
web/models/v2_tim_message
web/models/v2_tim_message_status
web/models/v2_tim_mute_group_member
web/models/v2_tim_notice_message_listiner
web/models/v2_tim_pin_conversation
web/models/v2_tim_profile
web/models/v2_tim_set_group_attributes
web/models/v2_tim_set_group_member_info
web/models/v2_tim_set_group_member_role
web/models/v2_tim_transfer_group_owner
web/models/V2TIMMessageReactionChangeInfoWeb
web/models/V2TimMessageReactionResultWeb
web/models/V2TimMessageReactionUserResultWeb
web/models/V2TimMessageReactionWeb
web/models/V2TimUserInfoWeb
web/utils/utils