Tech Talks

Building A Chat App with Flutter using Firebase Integration: A Complete Guide

Published On January 20th, 2023 Tech Talks

Flutter is a go-to framework for developers, aiming to build their chat apps natively for all platforms, within a short time. On the other-hand Firebase helps you integrate real-time functionalities into your app along with security and storage capabilities. 

Incorporating both these technologies lets you create a scalable, feature-rich and user-friendly chat app for your users. 

In this article, we’ll cover a complete overview of the steps in building a chat app in Flutter with Firebase integration. Also, you’ll learn how to create an Android app, integrate in-app chat using MirrorFly SDKs and setting up Firebase integration. 

But, first let’s get into the basics:

Why Should You Choose Flutter For Your Chat App?

Flutter is a powerful framework built by Google that can help you build high-quality apps within a short period of time. There are many reasons to why this framework may be a best choice for your app, but here are the top reasons:

Shorter Development Time: Be it any kind of app you are building, Flutter will cut your development time by half, without compromising on the quality of the build. 

Cross-platform compatibility: Since Flutter is a cross-platform framework, you can build apps for all the devices from a single codebase instead of building separate app for mobiles, web browsers and desktops. 

User-friendliness: The customization rendered by Flutter lets you create beautiful, modern chat apps. 

Hot-reload: Making changes in your codes and worried about losing the existing app state. Fear not, Flutter lets you see the changes in real-time, without affecting the app.

 
Make Industry-Specific Connections with our Secure APIs & SDKs

Why Should You Integrate Firebase Into Your Chat App?

Modern communication demands features and capabilities that perform way beyond regular chat apps. This is where Firebase integration acts as the catalyst for building robust and secure real-time infrastructures. Here are the major reasons why developers choose Firebase Integration for their apps:

Real-time functionalities: When you are building apps that need to deliver data within 1/2 a second, typically in real-time then Firebase integration might be your best bet.

Security: User authentication is a critical feature for apps that involve multiple users. When you set up a login for users with email, password, google or Facebook sign in, Firebase helps you incorporate them into your apps easily. Moreover, the data stored in the cloud is also protected with this service. 

Data Storage: A chat app typically involves conversations and media shares being stored for user access. This is another service offered by Firebase to keep user data safely in a cloud space. 

Now that we know how both these technologies will work, it is time to start using them to build your messaging application!

Part I: Steps To Build Your Chat App In Flutter

In this tutorial, we have demonstrated the step by step instructions on how to build an Android chat app that lets users send and receive messages. 

We’ll use Android Studio as the development environment and MirrorFly’s Chat SDKs to add the messaging functionality to your app. 

Minimum Requirements

  • Flutter 2.0.0 or later
  • Android 4.4 or later
  • MirrorFly Chat SDKs & License Key
  • Dart 2.12.0 or later
  • Firebase Account

Step 1: Get Your Chat SDKs And License Key

Building A Chat App with Flutter using Firebase2
  • Verify your account with the Confirmation link sent to your Email ID
  • Sign in to your MirrorFly Account
Chat App with Flutter using Firebase3
  • Download the Flutter SDK Package
  • Extract the downloaded SDK files onto your device
  • Again, go to your MirrorFly Account Dashboard 
  • Make a note of your License Key
Chat App with Flutter using Firebase2

 Step 2: Get Started With Your Chat App Project In Android Studio

In this step, you’ll create a new Android project, setting up Flutter as your development language.

  • Open the Android Studio IDE
Building A Chat App with Flutter using Firebase
  • Fill in the basic information of your project. Your Project Window will open
  • From the Downloads folder of your device, import the dependencies to your project’s App Folder. 
  • Next, add the pubspec.yaml file
  • To avoid library conflicts between the imported files, you’ll need to add the below line in the gradle.properties 
android.enableJetifier=true

 You’ll require permissions to access different components of the project. To grant them, add the below lines to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Next, in the app/build.gradle configure the License key that you acquired from your MirrorFly Account Dashboard. 

plugins {
	...
	id 'kotlin-android'
	id 'kotlin-kapt'
}
android {
	compileOptions {
    	sourceCompatibility JavaVersion.VERSION_1_8
    	targetCompatibility JavaVersion.VERSION_1_8
	}

	kotlinOptions {
    	jvmTarget = '1.8'
	}

	packagingOptions {
    	exclude 'META-INF/AL2.0'
    	exclude 'META-INF/DEPENDENCIES'
    	exclude 'META-INF/LICENSE'
    	exclude 'META-INF/LICENSE.txt'
    	exclude 'META-INF/license.txt'
    	exclude 'META-INF/NOTICE'
    	exclude 'META-INF/NOTICE.txt'
    	exclude 'META-INF/notice.txt'
    	exclude 'META-INF/ASL2.0'
    	exclude 'META-INF/LGPL2.1'
    	exclude("META-INF/*.kotlin_module")
	}
}
In the app/build.gradle file of your Flutter project, add the following dependencies:

dependencies {

 	... // your app dependencies

 	implementation files('libs/appbase.aar')
 	implementation files('libs/flycommons.aar')
 	implementation files('libs/flynetwork.aar')
 	implementation files('libs/flydatabase.aar')
 	implementation files('libs/videocompression.aar')
 	implementation files('libs/xmpp.aar')

 }
Add the below modules to your gradle build and configure the required parameters as shown below:


dependencies {

 	... // your app dependencies

 	configurations {
     	all {
         	exclude group: 'org.json', module: 'json'
         	exclude group: 'xpp3', module: 'xpp3'
     	}
 	}

 	//For lifecycle listener
 	implementation 'android.arch.lifecycle:extensions:1.1.1'
 	annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'

 	//For GreenDao
 	implementation 'de.greenrobot:greendao:2.1.0'

 	//For gson parsing
 	implementation 'com.google.code.gson:gson:2.8.1'

 	//for smack implementation
 	implementation 'org.igniterealtime.smack:smack-android:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-tcp:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-im:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-extensions:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-sasl-provided:4.4.4'

 	implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
 	implementation 'androidx.multidex:multidex:2.0.1'
 	implementation 'com.google.android.gms:play-services-location:17.0.0'

 	//Dagger Dependencies
 	api 'com.google.dagger:dagger:2.40.5'
 	kapt 'com.google.dagger:dagger-compiler:2.40.5'
 	api 'com.google.dagger:dagger-android:2.40.5'
 	api 'com.google.dagger:dagger-android-support:2.40.5'
 	kapt 'com.google.dagger:dagger-android-processor:2.40.5'

 	//coroutines
 	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8'
 	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'

 	//apicalls
 	implementation 'com.squareup.retrofit2:retrofit:2.6.1'
 	implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
 	implementation 'com.squareup.okhttp3:okhttp:4.2.0'
 	implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'

 	//stetho interceptor
 	implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'

 	//okhttp interceptor
 	implementation 'com.squareup.okhttp3:logging-interceptor:3.14.3'

 	//shared preference encryption
 	implementation 'androidx.security:security-crypto:1.1.0-alpha03'

 	//for mobile number formatting
 	implementation 'io.michaelrocks:libphonenumber-android:8.10.1'
 }

buildTypes {
  debug {
	buildConfigField 'String', 'SDK_BASE_URL', '"https://api-preprod-sandbox.mirrorfly.com/api/v1/"'
	buildConfigField 'String', 'LICENSE', '"xxxxxxxxxxxxxxxxxxxxxxxxx"'
	buildConfigField 'String', 'WEB_CHAT_LOGIN', '"https://webchat-preprod-sandbox.mirrorfly.com/"'
	buildConfigField "String", "SUPPORT_MAIL", '"contussupport@gmail.com"'
  }
}

Step 3: Initialize The Chat SDKs

In your Android Application Class, go to the onCreate() method and add the ChatSDK builder. This step will help you get all the necessary details to get started with the SDK initialization.

Kotlin:

//For chat logging
LogMessage.enableDebugLogging(BuildConfig.DEBUG)
 
ChatSDK.Builder()
	.setDomainBaseUrl(BuildConfig.SDK_BASE_URL)
	.setLicenseKey(BuildConfig.LICENSE)
	.setIsTrialLicenceKey(true)
	.build()

Step 4: Register a User

  • Once you’ve initialized the SDK, you’ll need to register the user using the USER_IDENTIFIER and  FCM_TOCKEN
  • You can create the user either in the live or sandbox mode, as given below

Flutter:

FlyChat.registerUser(USER_IDENTIFIER, FCM_TOCKEN).then((value) {
	if (value.contains("data")) {
	// Get Username and password from the object
	}
}).catchError((error) {
	// Register user failed print throwable to find the exception details.  
});

Once you register the user, the server automatically gets connected.

Step 5: Start Sending And Receiving Messages

  1. Send a Chat Message

Add the sendTextMessage() method to start sending messages from your Flutter app.

FlyChat.sendTextMessage(TEXT, TO_JID, replyMessageId).then((value) {
     // you will get the message sent success response
 });
  1. Receive a Chat Message

Get notifications on any incoming message, using the below  onMessageReceived() method

FlyChat.onMessageReceived.listen(onMessageReceived);
void onMessageReceived(chatMessage) {
     //called when the new message is received
 }

You’ve now successfully built a chat app in Flutter that can send and receive messages. Now, let us move on to integrate Firebase into your application. 

Part II: Steps To Integrate FireBase To Your App

Follow the below steps to add Firebase services to your messaging application:

Step 1 : Create a Firebase Project

  • Create a Project using the package name of your Flutter application. Let us assume that name is com.testapp

Step 2: Configure Your App Info In The Console

To store and manage your app’s configuration information the Google Developer Console, you’ll need to perform the following steps:

  • Go to Console
  • Select your project
  • Navigate to Project settings
  • Select Cloud Messaging. You’ll find the  google-service.json file here
  • Download the file
  • Add it to the App folder of your project

Step 3: Add Firebase Dependencies 

  • Once you’ve set up the configuration, you’ll need to add the below Firebase dependencies. To do this,
  • Go to build.gradle
  • Add the below repos
buildscript {
    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
   }
   dependencies {
       classpath 'com.google.gms:google-services:4.3.13' // google-services plugin
   }
}

allprojects {
   repositories {
       // Check that you have the following line (if not, add it):
       google() // Google's Maven repository
   }
}

Next, add the plugins for Android app and Google services

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
  implementation platform('com.google.firebase:firebase-bom:30.3.1')
}

You’ve now successfully set up Firebase for your app. Let’s proceed further to integrate the Push notifications

Step 4: Firebase Integration For Push Notification

  • To set up push notifications, go to the build.gradle and add the FCM dependency as mentioned below
implementation 'com.google.firebase:firebase-messaging:23.0.6'

In your Manifest file, add the below line

<service android:name=".MyFirebaseMessagingService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Extend the FirebaseMessagingService service by creating the MyFirebaseMessagingService file in your application

Java:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {
        //Push message will be received here when push notification triggered for this device
    }

    @Override
    public void onNewToken(@NonNull String token) {
         //Whenever Device token will get updated/changed this method will be triggered
         PushNotificationManager.updateFcmToken(token, isSuccess, message) -> {
            
                         });
    }
}

Kotlin:

class MyFirebaseMessagingService : FirebaseMessagingService() {
    
    override fun onMessageReceived(message: RemoteMessage) {
        //Push message will be received here when push notification triggered for this device
    }
    
    override fun onNewToken(token: String) {
        //Whenever Device token will get updated/changed this method will be triggered
        PushNotificationManager.updateFcmToken(token, object : ChatActionListener{
            override fun onResponse(isSuccess: Boolean, message: String) {
                }
        })
    }
}
  • Use the link below to enable cloud messaging 

Firebase Cloud Messaging

To start receiving messages and calls from Chat SDK, you’ll need to authenticate cloud messaging with the server. For Authentication,

  • Go to Project Setting under Cloud Messaging
Building A Chat App with Flutter using Firebase1
  • Copy the API Key
  • Configure it in the server
  • Next, add the below permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In the cloud message console, add the device token 

Java:

 FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            //Fetching FCM registration token failed
                            return;
                        }
                        
                        //Fetching FCM registration token succeed
                        // Get new FCM registration token
                        String token = task.getResult();
                        PushNotificationManager.updateFcmToken(token, isSuccess, message) -> {
            
                         });
                    }
                });

Kotlin:

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                //Fetching FCM registration token failed
                return@OnCompleteListener
            }

            //Fetching FCM registration token succeed
            // Get new FCM registration token
            val token = task.result
            PushNotificationManager.updateFcmToken(token, object : ChatActionListener{
            override fun onResponse(isSuccess: Boolean, message: String) {
                }
            })
        })

Step 5: Firebase Integration For Crashlytics

  • In your project level build.gradle, add the Crashlytics as given below
dependencies {
    // Check for v4.3.3 or higher
    classpath 'com.google.gms:google-services:4.3.13'
    classpath "com.google.firebase:firebase-crashlytics-gradle:2.9.1"
}

allprojects {
    repositories {
       // Add repository
        google()  // Google's Maven repository
    }
}

In your app level build.gradle, add the Crashlytics as given below

apply plugin: 'com.android.application'
apply plugin:  'com.google.firebase.crashlytics'

dependencies {
 // Add dependency
  implementation 'com.google.firebase:firebase-crashlytics:18.2.12'
}

Conclusion:

We hope this article helped you understand the steps involved in building a Flutter Chat App with Firebase Integration. By following the instructions, you will be able to add real-time messaging functionalities to your Android app as well as set up user authentication, push notifications and crash reporting using Firebase. 

All things considered, you now have everything you need to build a feature-rich messaging app. Why wait? Begin your development now!

Let us know in the comments what kind of messaging app you are building with the help of this tutorial. As always, Happy building, and good luck! 

 
Ready to Embed Real-time Chat Features?

Vigneshwar

Vigneshwar is a seasoned digital marketer and blogger, extremely passionate about driving search engine visibility for websites. He thoroughly enjoys exploring emerging technologies and is currently honing his expertise in Chat APIs and their associated tech stacks.

Flutter is a go-to framework for developers, aiming to build their chat apps natively for all platforms, within a short time. On the other-hand Firebase helps you integrate real-time functionalities into your app along with security and storage capabilities. 

Incorporating both these technologies lets you create a scalable, feature-rich and user-friendly chat app for your users. 

In this article, we’ll cover a complete overview of the steps in building a chat app in Flutter with Firebase integration. Also, you’ll learn how to create an Android app, integrate in-app chat using MirrorFly SDKs and setting up Firebase integration. 

But, first let’s get into the basics:

Why Should You Choose Flutter For Your Chat App?

Flutter is a powerful framework built by Google that can help you build high-quality apps within a short period of time. There are many reasons to why this framework may be a best choice for your app, but here are the top reasons:

Shorter Development Time: Be it any kind of app you are building, Flutter will cut your development time by half, without compromising on the quality of the build. 

Cross-platform compatibility: Since Flutter is a cross-platform framework, you can build apps for all the devices from a single codebase instead of building separate app for mobiles, web browsers and desktops. 

User-friendliness: The customization rendered by Flutter lets you create beautiful, modern chat apps. 

Hot-reload: Making changes in your codes and worried about losing the existing app state. Fear not, Flutter lets you see the changes in real-time, without affecting the app.

 
Make Industry-Specific Connections with our Secure APIs & SDKs

Why Should You Integrate Firebase Into Your Chat App?

Modern communication demands features and capabilities that perform way beyond regular chat apps. This is where Firebase integration acts as the catalyst for building robust and secure real-time infrastructures. Here are the major reasons why developers choose Firebase Integration for their apps:

Real-time functionalities: When you are building apps that need to deliver data within 1/2 a second, typically in real-time then Firebase integration might be your best bet.

Security: User authentication is a critical feature for apps that involve multiple users. When you set up a login for users with email, password, google or Facebook sign in, Firebase helps you incorporate them into your apps easily. Moreover, the data stored in the cloud is also protected with this service. 

Data Storage: A chat app typically involves conversations and media shares being stored for user access. This is another service offered by Firebase to keep user data safely in a cloud space. 

Now that we know how both these technologies will work, it is time to start using them to build your messaging application!

Part I: Steps To Build Your Chat App In Flutter

In this tutorial, we have demonstrated the step by step instructions on how to build an Android chat app that lets users send and receive messages. 

We’ll use Android Studio as the development environment and MirrorFly’s Chat SDKs to add the messaging functionality to your app. 

Minimum Requirements

  • Flutter 2.0.0 or later
  • Android 4.4 or later
  • MirrorFly Chat SDKs & License Key
  • Dart 2.12.0 or later
  • Firebase Account

Step 1: Get Your Chat SDKs And License Key

Building A Chat App with Flutter using Firebase2
  • Verify your account with the Confirmation link sent to your Email ID
  • Sign in to your MirrorFly Account
Chat App with Flutter using Firebase3
  • Download the Flutter SDK Package
  • Extract the downloaded SDK files onto your device
  • Again, go to your MirrorFly Account Dashboard 
  • Make a note of your License Key
Chat App with Flutter using Firebase2

 Step 2: Get Started With Your Chat App Project In Android Studio

In this step, you’ll create a new Android project, setting up Flutter as your development language.

  • Open the Android Studio IDE
Building A Chat App with Flutter using Firebase
  • Fill in the basic information of your project. Your Project Window will open
  • From the Downloads folder of your device, import the dependencies to your project’s App Folder. 
  • Next, add the pubspec.yaml file
  • To avoid library conflicts between the imported files, you’ll need to add the below line in the gradle.properties 
android.enableJetifier=true

 You’ll require permissions to access different components of the project. To grant them, add the below lines to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Next, in the app/build.gradle configure the License key that you acquired from your MirrorFly Account Dashboard. 

plugins {
	...
	id 'kotlin-android'
	id 'kotlin-kapt'
}
android {
	compileOptions {
    	sourceCompatibility JavaVersion.VERSION_1_8
    	targetCompatibility JavaVersion.VERSION_1_8
	}

	kotlinOptions {
    	jvmTarget = '1.8'
	}

	packagingOptions {
    	exclude 'META-INF/AL2.0'
    	exclude 'META-INF/DEPENDENCIES'
    	exclude 'META-INF/LICENSE'
    	exclude 'META-INF/LICENSE.txt'
    	exclude 'META-INF/license.txt'
    	exclude 'META-INF/NOTICE'
    	exclude 'META-INF/NOTICE.txt'
    	exclude 'META-INF/notice.txt'
    	exclude 'META-INF/ASL2.0'
    	exclude 'META-INF/LGPL2.1'
    	exclude("META-INF/*.kotlin_module")
	}
}
In the app/build.gradle file of your Flutter project, add the following dependencies:

dependencies {

 	... // your app dependencies

 	implementation files('libs/appbase.aar')
 	implementation files('libs/flycommons.aar')
 	implementation files('libs/flynetwork.aar')
 	implementation files('libs/flydatabase.aar')
 	implementation files('libs/videocompression.aar')
 	implementation files('libs/xmpp.aar')

 }
Add the below modules to your gradle build and configure the required parameters as shown below:


dependencies {

 	... // your app dependencies

 	configurations {
     	all {
         	exclude group: 'org.json', module: 'json'
         	exclude group: 'xpp3', module: 'xpp3'
     	}
 	}

 	//For lifecycle listener
 	implementation 'android.arch.lifecycle:extensions:1.1.1'
 	annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'

 	//For GreenDao
 	implementation 'de.greenrobot:greendao:2.1.0'

 	//For gson parsing
 	implementation 'com.google.code.gson:gson:2.8.1'

 	//for smack implementation
 	implementation 'org.igniterealtime.smack:smack-android:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-tcp:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-im:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-extensions:4.4.4'
 	implementation 'org.igniterealtime.smack:smack-sasl-provided:4.4.4'

 	implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
 	implementation 'androidx.multidex:multidex:2.0.1'
 	implementation 'com.google.android.gms:play-services-location:17.0.0'

 	//Dagger Dependencies
 	api 'com.google.dagger:dagger:2.40.5'
 	kapt 'com.google.dagger:dagger-compiler:2.40.5'
 	api 'com.google.dagger:dagger-android:2.40.5'
 	api 'com.google.dagger:dagger-android-support:2.40.5'
 	kapt 'com.google.dagger:dagger-android-processor:2.40.5'

 	//coroutines
 	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8'
 	implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'

 	//apicalls
 	implementation 'com.squareup.retrofit2:retrofit:2.6.1'
 	implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
 	implementation 'com.squareup.okhttp3:okhttp:4.2.0'
 	implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'

 	//stetho interceptor
 	implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'

 	//okhttp interceptor
 	implementation 'com.squareup.okhttp3:logging-interceptor:3.14.3'

 	//shared preference encryption
 	implementation 'androidx.security:security-crypto:1.1.0-alpha03'

 	//for mobile number formatting
 	implementation 'io.michaelrocks:libphonenumber-android:8.10.1'
 }

buildTypes {
  debug {
	buildConfigField 'String', 'SDK_BASE_URL', '"https://api-preprod-sandbox.mirrorfly.com/api/v1/"'
	buildConfigField 'String', 'LICENSE', '"xxxxxxxxxxxxxxxxxxxxxxxxx"'
	buildConfigField 'String', 'WEB_CHAT_LOGIN', '"https://webchat-preprod-sandbox.mirrorfly.com/"'
	buildConfigField "String", "SUPPORT_MAIL", '"contussupport@gmail.com"'
  }
}

Step 3: Initialize The Chat SDKs

In your Android Application Class, go to the onCreate() method and add the ChatSDK builder. This step will help you get all the necessary details to get started with the SDK initialization.

Kotlin:

//For chat logging
LogMessage.enableDebugLogging(BuildConfig.DEBUG)
 
ChatSDK.Builder()
	.setDomainBaseUrl(BuildConfig.SDK_BASE_URL)
	.setLicenseKey(BuildConfig.LICENSE)
	.setIsTrialLicenceKey(true)
	.build()

Step 4: Register a User

  • Once you’ve initialized the SDK, you’ll need to register the user using the USER_IDENTIFIER and  FCM_TOCKEN
  • You can create the user either in the live or sandbox mode, as given below

Flutter:

FlyChat.registerUser(USER_IDENTIFIER, FCM_TOCKEN).then((value) {
	if (value.contains("data")) {
	// Get Username and password from the object
	}
}).catchError((error) {
	// Register user failed print throwable to find the exception details.  
});

Once you register the user, the server automatically gets connected.

Step 5: Start Sending And Receiving Messages

  1. Send a Chat Message

Add the sendTextMessage() method to start sending messages from your Flutter app.

FlyChat.sendTextMessage(TEXT, TO_JID, replyMessageId).then((value) {
     // you will get the message sent success response
 });
  1. Receive a Chat Message

Get notifications on any incoming message, using the below  onMessageReceived() method

FlyChat.onMessageReceived.listen(onMessageReceived);
void onMessageReceived(chatMessage) {
     //called when the new message is received
 }

You’ve now successfully built a chat app in Flutter that can send and receive messages. Now, let us move on to integrate Firebase into your application. 

Part II: Steps To Integrate FireBase To Your App

Follow the below steps to add Firebase services to your messaging application:

Step 1 : Create a Firebase Project

  • Create a Project using the package name of your Flutter application. Let us assume that name is com.testapp

Step 2: Configure Your App Info In The Console

To store and manage your app’s configuration information the Google Developer Console, you’ll need to perform the following steps:

  • Go to Console
  • Select your project
  • Navigate to Project settings
  • Select Cloud Messaging. You’ll find the  google-service.json file here
  • Download the file
  • Add it to the App folder of your project

Step 3: Add Firebase Dependencies 

  • Once you’ve set up the configuration, you’ll need to add the below Firebase dependencies. To do this,
  • Go to build.gradle
  • Add the below repos
buildscript {
    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
   }
   dependencies {
       classpath 'com.google.gms:google-services:4.3.13' // google-services plugin
   }
}

allprojects {
   repositories {
       // Check that you have the following line (if not, add it):
       google() // Google's Maven repository
   }
}

Next, add the plugins for Android app and Google services

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
  implementation platform('com.google.firebase:firebase-bom:30.3.1')
}

You’ve now successfully set up Firebase for your app. Let’s proceed further to integrate the Push notifications

Step 4: Firebase Integration For Push Notification

  • To set up push notifications, go to the build.gradle and add the FCM dependency as mentioned below
implementation 'com.google.firebase:firebase-messaging:23.0.6'

In your Manifest file, add the below line

<service android:name=".MyFirebaseMessagingService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Extend the FirebaseMessagingService service by creating the MyFirebaseMessagingService file in your application

Java:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {
        //Push message will be received here when push notification triggered for this device
    }

    @Override
    public void onNewToken(@NonNull String token) {
         //Whenever Device token will get updated/changed this method will be triggered
         PushNotificationManager.updateFcmToken(token, isSuccess, message) -> {
            
                         });
    }
}

Kotlin:

class MyFirebaseMessagingService : FirebaseMessagingService() {
    
    override fun onMessageReceived(message: RemoteMessage) {
        //Push message will be received here when push notification triggered for this device
    }
    
    override fun onNewToken(token: String) {
        //Whenever Device token will get updated/changed this method will be triggered
        PushNotificationManager.updateFcmToken(token, object : ChatActionListener{
            override fun onResponse(isSuccess: Boolean, message: String) {
                }
        })
    }
}
  • Use the link below to enable cloud messaging 

Firebase Cloud Messaging

To start receiving messages and calls from Chat SDK, you’ll need to authenticate cloud messaging with the server. For Authentication,

  • Go to Project Setting under Cloud Messaging
Building A Chat App with Flutter using Firebase1
  • Copy the API Key
  • Configure it in the server
  • Next, add the below permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In the cloud message console, add the device token 

Java:

 FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            //Fetching FCM registration token failed
                            return;
                        }
                        
                        //Fetching FCM registration token succeed
                        // Get new FCM registration token
                        String token = task.getResult();
                        PushNotificationManager.updateFcmToken(token, isSuccess, message) -> {
            
                         });
                    }
                });

Kotlin:

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                //Fetching FCM registration token failed
                return@OnCompleteListener
            }

            //Fetching FCM registration token succeed
            // Get new FCM registration token
            val token = task.result
            PushNotificationManager.updateFcmToken(token, object : ChatActionListener{
            override fun onResponse(isSuccess: Boolean, message: String) {
                }
            })
        })

Step 5: Firebase Integration For Crashlytics

  • In your project level build.gradle, add the Crashlytics as given below
dependencies {
    // Check for v4.3.3 or higher
    classpath 'com.google.gms:google-services:4.3.13'
    classpath "com.google.firebase:firebase-crashlytics-gradle:2.9.1"
}

allprojects {
    repositories {
       // Add repository
        google()  // Google's Maven repository
    }
}

In your app level build.gradle, add the Crashlytics as given below

apply plugin: 'com.android.application'
apply plugin:  'com.google.firebase.crashlytics'

dependencies {
 // Add dependency
  implementation 'com.google.firebase:firebase-crashlytics:18.2.12'
}

Conclusion:

We hope this article helped you understand the steps involved in building a Flutter Chat App with Firebase Integration. By following the instructions, you will be able to add real-time messaging functionalities to your Android app as well as set up user authentication, push notifications and crash reporting using Firebase. 

All things considered, you now have everything you need to build a feature-rich messaging app. Why wait? Begin your development now!

Let us know in the comments what kind of messaging app you are building with the help of this tutorial. As always, Happy building, and good luck! 

 
Ready to Embed Real-time Chat Features?

Vigneshwar

Vigneshwar is a seasoned digital marketer and blogger, extremely passionate about driving search engine visibility for websites. He thoroughly enjoys exploring emerging technologies and is currently honing his expertise in Chat APIs and their associated tech stacks.

Leave a Reply

Your email address will not be published.