Tech Talks

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

Published On May 15th, 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 Flutter chat 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 a beautiful, modern chat app system design

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.

Ready to Get Started with Our Self-hosted Video, Voice & Chat Solution?
  • 100% Customizable
  • One-time License Cost
  • Hire Dedicated Team

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

build-chat-app-with-Flutter
  • Verify your account with the Confirmation link sent to your Email ID
  • Sign in to your MirrorFly Account
chat-app-for-ios-and-android
  • 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
build-messaging-app with-flutter

 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-chat-app-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
chat-application-for-android
  • 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!

Well, if you are considering 100% customizable video, voice, and chat features for your Flutter app development, you can avail of our best self-managed chat solution for a one-time license cost! To know more about this faster and more reliable option, talk to our experts today!

Till then, Happy building, and good luck!

 
Ready to Embed FREE Real-time Chat Features?

Frequently Asked Questions (FAQ)

Can we use Firebase for chat apps?

Yes, of course! Firebase can be a great choice for building chat apps as it offers certain features and tools that are essential for chat applications like real-time database, authentication, and cloud messaging. Additionally, they offer libraries and SDKs that come compatible with different platforms and support integrations with third-party services like Dialog Flow and other cloud services.
Thus, making it a great option for building a scalable and reliable chat application

Is Firebase free forever?

Yes, Firebase is free and you can make use of their no-cost pricing plan (Spark Plan) as long as you want. However, if you want more storage, network bandwidth, or hosting space for your chat app, then you must opt for their paid-tier pricing plan (Blaze Plan).

Does Firebase require coding?

No, some features like Firebase Hosting, Analytics, Test Lab can be used without writing codes. However, to use Firebase Authentication that enables users to sign in to your apps requires you to write codes to integrate it into your application.

How many GB is free on Firebase?

Users can avail up to 5GB of free storage under the Spark or pay-as-you-go pricing plan (Free Plan). And if you need more storage than this, you must upgrade to the Blaze Plan that lets you pay only for the storage you use.

Does MirrorFly use Flutter to build chat apps?

Yes, MirrorFly chat SDK supports Flutter tech stack to easily and swiftly ship in-app messaging experiences across web and mobile apps.

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 Flutter chat 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 a beautiful, modern chat app system design

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.

Ready to Get Started with Our Self-hosted Video, Voice & Chat Solution?
  • 100% Customizable
  • One-time License Cost
  • Hire Dedicated Team

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

build-chat-app-with-Flutter
  • Verify your account with the Confirmation link sent to your Email ID
  • Sign in to your MirrorFly Account
chat-app-for-ios-and-android
  • 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
build-messaging-app with-flutter

 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-chat-app-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
chat-application-for-android
  • 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!

Well, if you are considering 100% customizable video, voice, and chat features for your Flutter app development, you can avail of our best self-managed chat solution for a one-time license cost! To know more about this faster and more reliable option, talk to our experts today!

Till then, Happy building, and good luck!

 
Ready to Embed FREE Real-time Chat Features?

Frequently Asked Questions (FAQ)

Can we use Firebase for chat apps?

Yes, of course! Firebase can be a great choice for building chat apps as it offers certain features and tools that are essential for chat applications like real-time database, authentication, and cloud messaging. Additionally, they offer libraries and SDKs that come compatible with different platforms and support integrations with third-party services like Dialog Flow and other cloud services.
Thus, making it a great option for building a scalable and reliable chat application

Is Firebase free forever?

Yes, Firebase is free and you can make use of their no-cost pricing plan (Spark Plan) as long as you want. However, if you want more storage, network bandwidth, or hosting space for your chat app, then you must opt for their paid-tier pricing plan (Blaze Plan).

Does Firebase require coding?

No, some features like Firebase Hosting, Analytics, Test Lab can be used without writing codes. However, to use Firebase Authentication that enables users to sign in to your apps requires you to write codes to integrate it into your application.

How many GB is free on Firebase?

Users can avail up to 5GB of free storage under the Spark or pay-as-you-go pricing plan (Free Plan). And if you need more storage than this, you must upgrade to the Blaze Plan that lets you pay only for the storage you use.

Does MirrorFly use Flutter to build chat apps?

Yes, MirrorFly chat SDK supports Flutter tech stack to easily and swiftly ship in-app messaging experiences across web and mobile apps.

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.

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

  1. Walter says:

    Hello MirrorFly, a really great article that’s put up neatly for beginners. Hats off! I’m looking forward to learning more about your product and how it can benefit me, as I’m developing a real-time chat app and needs authentication features to be implemented.

    1. Vigneshwar says:

      Hello Walt, thank you for your kind words about my article. I’m thrilled to hear that you are interested in our product and how it can help you build a real-time chat app. Here’s a brief intro about us. MirrorFly is a powerful Free chat API provider that is highly preferred by developers for its easy-to-use messaging features and simple integration capabilities. Along with these, it also offers both cloud and self-hosted solutions to build feature-rich chat apps. If you would like to learn more about us, you can schedule a demo with our expert team who would be happy to guide you on your requirements.

      And regarding the need to add authentication for your chat app, the ideal option would be to go ahead with firebase integration using MirrorFly’s in-app chat SDK.

  2. Saina says:

    Hello team, I’m looking to build a healthcare chat app using Flutter for adding voice and video capabilities and I want to know whether you support this framework. Also, I want to know whether you have UI kits for my app. How may I reach you?

    1. Vigneshwar says:

      Hello Saina, thank you for reaching out to us, and great to hear that you are planning to build a healthcare chat app. Yes, we do support the Flutter framework for building chat apps with both voice and video capabilities. And regarding UI kits, we have a pre-built UI kit for iOS, Android, and web apps that can help you jumpstart your healthcare chat app project.

      You can get in touch with us by talking to our experts or by sending an email to our support team.

  3. Charles says:

    Hi, I have built a chat app using Flutter but looking for certain features. And when I searched other websites, I found the pricing to be high. May I know at what pricing you offer your services and I need integration support too?

    1. Vigneshwar says:

      Hello Charles, it is really wonderful news that you have a chat app ready in hand. I’m thrilled to tell you that MirrorFly’s Free chat API offers high-end messaging features to users for recurring monthly packages or one-time license cost. You may also take a look at our pricing page to get more clarity on the pricing options available.
      Regarding the SDK integration support, our self-hosted solutionself-hosted solution lets you hire a dedicated development team to help you with the integration right from the start till your app goes live. If you would like to proceed further, please talk to our experts.

  4. Benjamin says:

    Hello, I’m Benjamin and this is a very good tutorial. Can you tell me how to notify the user status online or offline? Thanks!!

    1. Vigneshwar says:

      Hello Benjamin, thank you for your kind response towards my article. You can notify users about their offline/online status by enabling online presence indicators in your chat platform using our Free chat API.Or simply, you may talk to our experts regarding this.

  5. Kennedy says:

    Thank you very much for the blog post! I hope you write more stories on flutter!

    1. Vigneshwar says:

      Sure Kennedy! Thanks for your response to my article and please keep coming back for more insights on developer-related articles.

  6. Ayaz says:

    This is a great article to learn how to build a chat application using Flutter and firebase. This article has everything from Firebase integration to Flutter along with Authentication, Sign-in, Cloud firebase, and storage services. This is a must-learn tutorial for beginners in Flutter development because it teaches much more about Firebase services and how to access them in Flutter to build a Chat application. This type of integration is adopted in some of the most amazing Flutter chat app templates that are in the market.

    1. Vigneshwar says:

      Thanks for such a wonderful response to my article! Very true Ayaz, these days Flutter is highly used to build chat apps along with Firebase services. My best wishes to you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Request Demo