Apps

Building a WhatsApp clone from scratch using Flutter

Use Applozic’s chat API to create a fully functional real-time chat app
Google+ Pinterest LinkedIn Tumblr

According to Statista, around 2.77 billion mobile phone users accessed over-the-top messaging to communicate in 2020, and this figure is poised to reach three billion users in 2022. Of these, WhatsApp was the most popular mobile messenger app worldwide with over 2 billion users, mainly due to its first-mover advantage and user-friendly interface.

However, due to concerns over the recent updates to WhatsApp’s privacy policies, many users and businesses are on the lookout for alternatives. Check out our previous blog post to learn more about the security implications of WhatsApp’s policy updates.

Thanks to Applzozic’s intuitive chat SDKs and platform APIs, it‘s pretty easy to build your own chat alternative to WhatsApp! Before we delve into the code, let’s discuss the framework that we’ll use to implement our chat messenger app.

Why Flutter?

Launched by Google in 2018, Flutter is a free and open-source SDK for developing high-performing mobile, web, and desktop applications from a single codebase. 

An exciting feature of Flutter is its layered structure that enables developers to build highly customizable and attractive apps with much lower time and effort, without compromising on performance. Moreover, experimenting new features and debugging errors is much faster in Flutter due to its hot reload feature that reflects instant changes in the codebase within milliseconds

Even though Flutter is a relatively new cross-platform app development framework compared to established contemporaries like React Native, many companies have started to migrate to Flutter due to its higher performance and flexible UI.

Do note that we’ll only be delving into the code implementation of the app’s chat functionality using Applozic Flutter SDK in this article – here’s a simple tutorial on creating a UI for the app using Flutter.

Creating a new application and setting up dependencies

flutter.dev has a comprehensive starter tutorial on creating your first application using Flutter. Once you are ready to integrate using the Applozic SDK, follow these steps:

I. Installation

  1. Add the following dependency in your pubspec.yaml file:
dependencies:
  # other dependencies
applozic_flutter: ^0.0.4

2. Install the package as shown below:

flutter pub get

3. Import the applozic_flutter in your .dart file to use the methods from Applozic:

import 'package:applozic_flutter/applozic_flutter.dart';

II. Authentication

Login

Create an Applozic user object, and pass it to the login() function as shown below:

dynamic user = {
      'applicationId': "<APPLICATION_ID>",   //Mandatory
      'userId': userId.text,                 //Mandatory
      'displayName': displayName.text,
      'password': password.text,
      'authenticationTypeId': 1              //Mandatory
  };

ApplozicFlutter.login(user).then((response) {
      print("Login success : " + response)
    }).catchError((error, stack) =>
      print("Error while logging in : " + error.toString()));

Please keep in mind that once the user is logged in, a new login is permitted only after the user logs out. Use this code to check if the user is already logged in:

ApplozicFlutter.isLoggedIn().then((isLoggedIn) {
        if (isLoggedIn) {
          //The user is logged in
         } esle {
          //The user is not logged in
         }
     });

Update logged in user details

You can update the logged in user details as given below:

  dynamic user = {
                    'displayName': '<New name>'
                    'imageLink': '<New Image URL>'
                  }

  ApplozicFlutter.updateUserDetail(user)
                        .then(
                            (value) => print("User details updated : " + value))
                        .catchError((e, s) => print(
                            "Unable to update user details : " + e.toString()));

Get logged in userID

You can get the userID of the logged in user as given below:

  ApplozicFlutter.getLoggedInUserId().then((userId) {
      print("Logged in userId : " + userId);
    }).catchError((error, stack) {
      print("User get error : " + error);
   });

III. Push Notifications

  • Go to /android/build.gradle
  • Add the following under buildscript → dependenciesclasspath 'com.google.gms:google-services:4.0.1'
  • Add the following at the bottom of the file: apply plugin:'com.google.gms.google-services'
  • After adding, it will look something like this:
buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }

    dependencies {
      classpath 'com.android.tools.build:gradle:3.3.0'
      classpath 'com.google.gms:google-services:4.0.1'
    }
}

apply plugin: 'com.google.gms.google-services'
  • From login success callback, call ApplozicFlutter.registerPushNotification();
  • For push notifications, you must have a Firebase account: Sign-up to https://console.firebase.google.com/ and create your application and generate push notification services file.
  • Download google-services.json from your Firebase Console and paste it to /android folder
  • Go to the Applozic console, update the FCM Server Key from the Firebase account to your Applozic account push notification section here.

IV. Conversation

Launch main chat screen

Launch the main chat screen as below:

  ApplozicFlutter.launchChatScreen();

Launch Chat with a specific User

Launch the conversation with a user by passing the userID as below:

  ApplozicFlutter.launchChatWithUser("&lt;USER_ID&gt;");

Send message

To send a message to a contact or a group, you must first create a message object:

dynamic message = {
      'to': "userID", // to send message to a contact pass the userID of the receiver 
      'message': "message text", // message to send
    };

Note: A message object can have more parameters. Refer to this link: https://docs.applozic.com/docs/android-chat-message-api#build-your-ui-from-scratch—message-api

Then pass the message object to this function:

ApplozicFlutter.sendMessage(message)
    .then((value) =&gt; print("Message sent."))
    .catchError((e, s) =&gt; print("Error while sending message: " + e.toString()));

Logout

To log out from Applozic, execute the following code:

 ApplozicFlutter.logout()
                .then((value) =&gt;
                  print("Logout successfull")
                .catchError((error, stack) =&gt;
                  print("Logout failed : " + error.toString()));

Conclusion

In this tutorial, we have implemented basic features of a chat messenger application such as one-to-one messaging and push notifications using Applozic’s powerful  Flutter SDK. To add more features like Group Messaging, Audio and Video Call, Rich Messaging, and many more, visit Applozic’s documentation website.

Please leave your feedback and doubts in the comments below!

Akash is a Developer Evangelist and an amateur programmer who loves to demystify technology, one article at a time.