How to Build a Flutter Chat App With the CometChat SDK

In this tutorial, we will learn how to build a cross-platform Flutter chat application for Android & iOS using CometChat’s Flutter Chat SDK.

Santosh Kumar • Apr 1, 2022

Flutter is one of the most popular open-source technologies for developing cross-platform mobile and web applications. It is used to develop cross-platform apps for Android, iOS, Linux, macOS, Windows, Google Fuchsia, and the web from a single codebase.

In this tutorial, we will learn how to build a cross-platform mobile chat application for Android & iOS using CometChat’s Flutter Chat SDK. You will also learn how to set up and configure a CometChat account, how to authenticate your users and run a sample app using Flutter SDK. The Flutter SDK includes core chat features such as

  • Login

  • Private(1-on-1) & Group Conversations

  • Rich Media Attachments

  • Typing Indicators

  • Text, Media and Custom messages

  • Read receipts

  • Online Presence Indicators

  • Message History

  • Users & Friends List

  • Groups List

  • Conversations List

Let’s get started!

Setting  the Environment

  1. To run this app, you must have the Android Studio/Xcode/Visual studio and Flutter SDK already installed and setup. If you don't, this documentation will help you in setting up editor and Flutter SDK Flutter - Setup Development Environment.

Configure CometChat Account

  1. Head to CometChat Dashboard to login (or) create an account.

  2. After logging into the CometChat dashboard, create a new app called Flutter SDK chat app

  3. Select the newly created chat app and note your App ID, Auth Key and Region details.

Steps to Run the Sample App

  1. Clone the CometChat Flutter Sample app repository from here as shown below:

git clone <repo-name>

  1. Navigate to the flutter-chat-app/lib directory and select the constants.dart file. Replace the values of appId, region, and authkey with values obtained from your CometChat AppID, AuthKey and Region.

  2. Install dependencies and run the app.

The next section provides more information on different methods of the Flutter SDK which are used to implement authentication, user list, group list, conversations list and messages component in the sample app.

Authenticate Your Users

CometChat’s Flutter SDK supports single sign-on, so your users only need to login to your app and they will be automatically authenticated with CometChat. The sample app provides a login page which helps you understand on how to authenticate your users.

The Login

The Login Component - Flutter Chat App SDK

This screen represents the login page which uses our default list of sample users having UIDs -  SuperHero1, SuperHero2, SuperHero3, SuperHero4, SuperHero5.

This page utilizes the SDK methods - login() and a user can login using either the Auth key or Auth Token.

Auth Key

Auth Token

To learn more about how this specific page has been implemented in our sample app please follow this link.

Visit the Authentication section in our Flutter documentation to learn more and implement authentication to your specific use-case

The next section of this tutorial explains how you can build UI components for your chat app. As you read along, the components mentioned below explain how different chat features can be implemented using Flutter SDK.

User List

This screen represents the user list page which retrieves a list of users (contacts) and displays in your app.

User List

Our Flutter SDK has 3 main functionalities around Users:

Retrieve Users

You can get the details of the logged-in user using the getLoggedInUser() method. This method can also be used to check if the user is logged in or not. This method will return a User object containing all the information related to the logged-in user.

Besides, you can get a list of all users, set a limit on the number of users to be fetched at any single iteration, set status, search by keyword, set roles, friends only and on the basis of Tags. You can also specifically fetch the number of online users count and retrieve specific user details.

User Management

These should be ideally achieved at your backend using our REST Apis, but Cometchat also provides you to manage your users at the SDK level.

There are 3 scenarios to managing users in the SDK. Creating a user, Updating a user and a logged-in user, Deleting a user.

Please visit the User Management section of our documentation to learn more.

Block Users

You can block users using the blockUsers() method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The blockUsers() method takes a List<String> as a parameter which holds the list of UIDs to be blocked.

You can also unblock users, Get a list of blocked users and set limits, search by keywords and set direction.

Please visit the Block Users section in Users of our documentation to learn more.

Conversations List

This screen represents the conversation list page which retrieves a list of recent conversations the signed-in user has had with other users or groups.

Conversation List

To fetch the list of conversations, the ConversationsRequest class is used and we can use several methods to achieve the following:

Set Limit

This method sets the limit i.e., number of conversations that should be fetched in a single iteration.

Set Conversation Type

This method can be used to fetch group and/or user conversations specifically.

User and Group Tags

This method can be used to fetch the user/group tags in the Conversations Object.

Tags

This method makes sure that the tags associated with the conversations are returned along with the other details of the conversations.

To learn more about how this specific screen has been implemented in our sample app please follow this link.

Visit the Retrieve Conversations under Messaging of our Flutter documentation to learn more.

Messages

Messaging is one of Cometchat Flutter SDK’s core features and we have thoughtfully created methods that help you send, receive and fetch message history. At the minimum, you must add code for sending and receiving messages. Once you’ve implemented that, you can proceed to implement advanced features like typing indicators, delivery receipts and more.

This screen represents the message list page which helps the signed-in user to have conversations with another user or another group.

build-flutter-chat-app-img-1

Send a Message

CometChat’s Flutter SDK allows you to send 3 kinds of messages:

  1. A Text Message, the most common and standard message type.

  2. A Media Message, for sending photos, videos and files.

  3. A Custom Message, for sending completely custom data using Map structures.

Text Message

Once the text message object is ready, you need to use the sendMessage() method to send messages to your intended recipient.

Media Message

Similar to sending text messages to any user, you can send a media message to any user/group using the sendMediaMessage() method and pass a MediaMessage object to it.

You can send Media messages in 2 ways - either by providing the file or by providing the URL of the file.

Let us explore the former, i.e. directly sharing the file with your intended recipient. When the media message is sent using the sendMediaMessage() method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the sendMediaMessage() function.

Custom Message

You can also send custom messages which are neither text nor media messages, for eg. map coordinates to share your location with another user/group.

You can send custom messages by using the sendCustomMessage() method. On success, you will receive an object of CustomMessage class.

Receive a Message

Receiving messages with CometChat Flutter SDK consists of 2 parts:

  1. Adding a listener to receive Real-time Messages when your app is running

  2. Calling a method to retrieve Missed Messages when your app was not running

Real-time Messages

For every activity or fragment you wish to receive messages in, you need to register the MessageListener using the addMessageListener() method.

Missed Messages

For most use cases, you need to add functionality to load missed messages. We will see how to implement this functionality with group and 1-on-1 conversations.

Using the same MessagesRequest class and the filters provided by the MessagesRequestBuilder class, you can fetch the message that we sent to the logged-in user but were not delivered to them as they were offline. For this, you will require the ID of the last message received. You can either maintain it at your end or use the getLastDeliveredMessageId() method provided by the CometChat class. This ID needs to be passed to the setMessageId() method of the builder class. Now using the fetchNext() method, you can fetch all the messages that were sent to the user when they were offline.

  • For a 1-on-1 Conversation

  • For a Group Conversation

Additionally, you can fetch Unread Messages, fetch the Message history, Search Messages using a searchKeyword parameter, get the count of unread messages for the logged in-user per group or users they interact with.

Also, this screen allows you to not just send and receive messages, but also enables you to add additional features such as message filtering, edit a message, delete a message, delete a conversation, show typing indicators and read & delivery receipts.

To learn more about how this specific page has been implemented in our sample app. please follow this link.

Visit the Messaging section in our Flutter documentation to learn more about the various features our SDK supports and several methods you can implement to suit your specific use-case

Group List

CometChat’s Flutter SDK allows you to create and take part in group conversations. You have 3 types of groups, namely - private, public and password-protected. It also allows its users to assume 3 kinds of roles - admin, moderator and member.

Group List

The above screen shows you the logged in member engaging in a conversation with a group - Comic Hero’s Hangout.

Lets dive into the basic features of groups provided by our SDK and how to implement them.

Retrieve Groups

Once the parameters such as - Set Limit, Search Keyword, Joined Only, Set Tags and With Tags are set to the builder class, you need to call the build() method to get the object of the GroupsRequest class.

Once you have the object of the GroupsRequest class, you need to call the fetchNext() method. Calling this method will return a list of Group objects containing 'n' number of groups depending on the limit set.

The list of groups fetched will only have the public and password type groups. The private groups will only be available if the user is a member of that private group.

Additionally, you can retrieve particular Group Details, Get online group member count using the methods provided under the Retrieve Groups section.

Join a Group

In order to start participating in group conversations, you will have to join a group. You can do so using the joinGroup() method.

Once you have joined a group successfully, you can send and receive messages in that group. You can identify if a group is joined using the hasJoined parameter in the Group object.

Additionally, this screen allows you to perform the following Groups features provided by our SDK, i.e. Create a group, Update a Group, Leave a Group, Delete a Group, Retrieve Group Members, Add Members to a group, and also perform advanced features such as Ban/Kick Members from a group, Transfer Group ownership and Change member scope.

To learn more about how this specific page has been implemented in our sample app please follow this link.

Visit the Groups Section in our Flutter documentation to learn more about the various Groups features our SDK supports and several methods you can implement to suit your specific use-case.

Extensions Capability

CometChat’s Flutter SDK is compatible with all the extensions available in the CometChat’s extensions marketplace which makes it easy to customise the experience for your users, increase engagement, manage data, integrate with other services, and more.

Every extension is built for quick integration with your existing tech stack and to ensure easy implementation and management.

In this particular sample app we have added the Polls extensions which makes it easy for users to quickly record their opinions directly in the conversation window and also view the results after they cast their vote.

Extensions Capability

build-flutter-chat-app-img-2

build-flutter-chat-app-img-3

You can enable any extension to the Flutter SDK using the callExtension method and in this particular sample app we have used the Polls Extension.

The Polls extension has 4 components to it:

Creating a Poll

Receiving a Poll

Polls are custom messages. So, you have to implement our onCustomMessageReceived listener in order to receive the Poll-related message. Please refer to our Receive Messages documentation under the SDK of your choice.

The metadata stores all the information about the poll. You will find the following details in metadata -> @injected -> extensions -> polls.

Voting in a Poll

Voting in a poll simply requires you to provide the id of the poll and the option you intend to vote for. The vote parameter is basically the option number.

Getting Results

There are 2 ways to fetch the results of the poll:

  • Real-time updates from the metadata

  • Fetch the results by using the callExtension method.

To learn more about how this specific page has been implemented in our sample app please follow this link.

Visit our Extensions marketplace in our Flutter documentation to learn more about the various Extensions our Flutter SDK supports that you can implement to suit your specific use-case.

Wrapping Up

We hope the sample app helped in understanding text chat features of the Flutter SDK. You have seen how to build most of the Flutter chat functionalities such as real-time messaging using the CometChat SDK.

For a complete rundown of CometChat’s text features supported by the Flutter SDK, along with additional resources to get you up and running with your Flutter chat app, check out our Flutter documentation.

Congratulations! You’re on the right path to adding feature-rich text features to your chat app! You can now start building your Flutter chat app for free by signing up to the cometchat dashboard here.

About the Author

Santosh Kumar is the Product Manager at CometChat.

Santosh Kumar

CometChat

-

Share it with everyone!

Get started for free

Build and test for as long as you need. Pick a plan when you're ready