Guest Article

Creating a chat application on Flutter using Applozic

Create a fully-fledged Flutter application that leverages Applozic's powerful chat API!
Google+ Pinterest LinkedIn Tumblr

This guest post on the Applozic blog was written by Mr. Rohith Gilla. Rohith is a software engineer based in India who specializes in building exceptional mobile applications, websites, and everything in between. His current favourite tech stack is Flutter for Mobile and Next for Web. You can find him on his website or Twitter.

Rohith Gilla

Applozic is an amazing platform to create high-quality chat applications that boost your mobile application development.

This service makes the development of chat applications a hassle-free experience by not compromising on the quality and features of the application.

Creating a project

Create a new Flutter project

You could use any Flutter starter kit to generate the scaffold of the project, but for simplicity purposes let’s use the standard Flutter create.

At the time of writing this tutorial, these are the latest Flutter and tooling versions:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 2.3.0-24.1.pre, on macOS 11.4 20F71 darwin-x64, locale en-IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2021.1.3)
[✓] VS Code (version 1.57.1)
[✓] Connected device (3 available)

Let’s create our bare-bones project by running the following command:

flutter create applozic_example

Installing required dependencies

We would be needing applozic_flutter: ^0.0.4 and flutter_login: ^2.1.0 for the tutorial. To develop your chat application for Flutter and various other frameworks, register for a free trial of Applozic’s chat API.

We use applozic_flutter for the core functionality of the application and flutter_login to scaffold the UI of the login screen quickly.

Please note that the applozic_flutter library hasn’t been migrated to null safety yet, so we cannot build with sound null safety.

name: applozic_example
description: A new Flutter project.

publish_to: "none"

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  applozic_flutter: ^0.0.4
  flutter_login: ^2.1.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true

Please do check this link for platform-specific configuration too, since this may change as the version changes.

Applozic side

Now you could head over to Applozic Console and create a new application.

Once you have created a new application you will have the Application ID you will be needing that.

Integration

Now once we set up everything, we now have the Application ID of the app.

Let’s save our Application ID in a new file, let’s say config.dart

const String appID = 'Your App ID';

We will need the appID during the authentication part.

Authentication

Applozic provides us with two useful utility functions to check if the user is logged in and another to check logged-in user id.

Root

ApplozicFlutter.isLoggedIn() is the function to check the login status of the user. This function returns Future<bool> so we could wrap this function with the help of FutureBuilder.

We then create two new screen one for HomePage and another for the LoginPage. Now, based on the user being present we direct them to the respective pages.

FutureBuilder(
        future: ApplozicFlutter.isLoggedIn(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data) {
              return const HomePage();
            } else {
              return const LoginPage();
            }
          } else {
            return const CircularProgressIndicator();
          }
        },
      );

The code of the main.dart file will look something similar to this:

//@dart = 2.9
import 'package:applozic_example/auth/login.dart';
import 'package:applozic_example/home/home.dart';
import 'package:applozic_flutter/applozic_flutter.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Applozic Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: ApplozicFlutter.isLoggedIn(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data) {
              return const HomePage();
            } else {
              return const LoginPage();
            }
          } else {
            return const CircularProgressIndicator();
          }
        },
      ),
    );
  }
}

Login Page

To simply our process and save a lot of time we will be using flutter_login to implement the Login UI of the application.

But before seeing how the UI is built, let’s see how the user is logged in using Applozic.

They provide a simpler way to carry out authentication, we could use the login method to do both signup and log in at the same time. It is very handy.

 final Map<String, dynamic> user = {
    'applicationId': appID, //Mandatory
    'userId': loginData.name, //Mandatory
    'displayName': loginData.name,
    'password': loginData.password, // Mandatory
    'authenticationTypeId': 1 //Mandatory
  };
  final result = await ApplozicFlutter.login(user);

Now if you check the JSON object that we are passing to the function, it has three mandatory fields

  • authenticationTypeId – this is set to 1
  • userId – you could generate this using a UUID library, for simplicity we will be using email as the userId
  • applicationId – this is the part where you use the Application ID that we have generated in the Applozic console.

The Login UI which we discussed above is used in the following way:

import 'package:applozic_example/config.dart';
import 'package:applozic_example/home/home.dart';
import 'package:applozic_flutter/applozic_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FlutterLogin(
      hideSignUpButton: true,
      hideForgotPasswordButton: true,
      onSubmitAnimationCompleted: () {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (_) => const HomePage()));
      },
      onSignup: (LoginData loginData) {},
      onLogin: (LoginData loginData) async {
        final Map<String, dynamic> user = {
          'applicationId': appID, //Mandatory
          'userId': loginData.name, //Mandatory
          'displayName': loginData.name,
          'password': loginData.password,
          'authenticationTypeId': 1 //Mandatory
        };
        final result = await ApplozicFlutter.login(user);
      },
      onRecoverPassword: (String email) {},
    );
  }
}

Core functionality

Overview

Applozic provides you with a pre-built chat UI where you could

  • Share Documents
  • Share Images
  • Share Videos
  • Share Location
  • Share Contacts
  • Reply to messages
  • Get Unread counts
  • Create groups

And many more in the library out of the box with no additional configuration required.

User screen

If you want to launch a chat with a certain user you could grab their user ID and pass it:

SizedBox(
  width: MediaQuery.of(context).size.width * 0.8,
  child: ElevatedButton(
    onPressed: () {
      ApplozicFlutter.launchChatWithUser(userId);
    },
    child: const Text(
      'Open User Chat Screen',
    ),
  ),
),

The user chat screen would look something like this, the screenshot also shows how sharing of images work, pretty sweet right?

Realtime Messaging GIF

In Realtime Messaging, you could see typing indicators out of the box which is honestly really amazing! You can also see the user status below the user email ID:

User Chat screen

Chat Screen open:

SizedBox(
  width: MediaQuery.of(context).size.width * 0.8,
  child: ElevatedButton(
    onPressed: () {
      ApplozicFlutter.launchChatScreen();
    },
    child: const Text(
      'Open Chat Screen',
    ),
  ),
),

You will have the compose button on the right side and back on the left, you could see all your chats, groups in one place sorted with recent activity.

The core functions like delete and block are taken care of by default so we need not worry about it.

View of a chat group


Sharing
You can share images, videos, contacts, location documents, and more

Unread Counter

Applozic provides a function out-of-box to calculate both the number of unread messages, the number of unread chats, and also the number of unread user messages.

GitHub Repository

The code for the demo application used in the tutorial can be found here.

Rohithgilla12/applozic_example

Thanks for reading the article! Feel free to leave your comments and doubts in the comment section below 🙂

Author

Do you want to share your thoughts with the Global App Development Community? Write for Applozic! Check out how here: https://www.applozic.com/guest-writer/