Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why Firebase?
3.
Overview of Firebase Cloud Messaging
4.
Features of Firebase Messaging In Flutter
5.
Workflow of FCM
5.1.
Message Creation
5.2.
Firebase Backend
5.3.
Message Delivery Based on Different Platforms
6.
Types of Messages
6.1.
Notification Messages
6.2.
Data Messages
7.
Setting up FCM in Flutter
8.
Token Based Messaging
9.
Handling Messages in Foreground
9.1.
Implementation
9.2.
Explanation
10.
Handling Messages in Background
10.1.
Implementation
10.2.
Explanation
11.
Frequently Asked Questions
11.1.
What do you understand about FCM?
11.2.
What are notification messages?
11.3.
How can you send messages using a token in Firebase Messaging in Flutter?
11.4.
How do you handle Messages in the Foreground in FCM?
12.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Firebase Messaging in Flutter

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In the modern world, where people mostly rely on mobile chat apps for communication, sending messages on time is very important. This is where Firebase messaging in Flutter comes into the picture. IFirebase cloud Messaging or FCM is used to send messages to users without any delay.

Firebase Messaging in Flutter

In this article, we will discuss Firebase Messaging in Flutter in detail and learn how to send and handle messages.

Why Firebase?

Firebase makes things easier for developers by simplifying the complex parts of sending and receiving messages over the internet. Thus developers can focus on building the app rather than working on the tech details. In this way, Firebase Messaging in Flutter saves developers a lot of time and effort.

Firebase
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Overview of Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a service provided by Firebase that allows users to send messages and notifications between the server and mobile/web applications. It offers a reliable and efficient connection, thus making sure that the messages are delivered timely while consuming minimum power on the devices. The messaging service improves user engagement. The best part is that it can be availed at no cost. 

Features of Firebase Messaging In Flutter

The features of Firebase Messaging in Flutter are:

  • FCM can inform a client app about the availability of new emails and other data to be synced, thus keeping the app content up to date.
     
  • For instant messaging FCM allows users to send a payload of up to 4000 bytes to a client app. This adds to the flexibility of sending and processing big sets of data.
     
  • FCM also allows users to send notification messages in the form of alerts and updates to the client app.
     
  • FCM supports bidirectional communication by allowing the client app to send messages.


Next, Let us dive deeper into the topic and understand the workflow of the Firebase messaging in Flutter.

Workflow of FCM

Workflow of FCM

Firebase messaging in Flutter can be divided into four components. They are:

Message Creation

First, create a message with all the required details using the Firebase Notification Composer. You can do so using the user-friendly UI very easily. Another way to create a message is to set up your own server that supports Firebase Admin SDK or FCM server protocols.

Firebase Backend

The message request is sent to the Firebase backend, which generates a metadata message ID. The Firebase backend handles the processing and routing of messages.

Message Delivery Based on Different Platforms

The message request is sent to the targeted device through the transport layer. Different transport layers are used depending on the device. For example, Android devices use the Android Transport layer, iOS devices use the Apple Push Notification Service, and web apps use the web Push Protocol.

Finally, the device with the Firebase SDK receives the message notifications and performs the actions on the received message depending on the application's logic.

Types of Messages

There are two types of messages in FCM that can be used to build a complete messaging system for your mobile app. Let us look at each of them one by one.

Types of Messages in FCM

Notification Messages

Notification Messages are used to send notifications to users. These messages are designed to give people a user-friendly interface for displaying important information and updates. 

The FCM SDK handles notification messages. In the background or the killed state, they go to the Android Notification tray, where they can be created using the Notification Composer that is provided by the Firebase console. 

In the foreground, they are sent to the onMessage callback in the firebase_messaging plugging for Flutter. You can also send them manually using your server, postman, or other command line tools.

Data Messages

Data Messages do not have a predefined UI. These messages are used for performing actions in the Client app without giving any notification to the user. 

The code handles Such messages rather than the Firebase FCM SDK. They cannot be created using the Notification Composer. The Data Message makes a call to the onMessage or onBackgroundMessage callback if the message is either in the foreground, background, or killed state.

Setting up FCM in Flutter

To add FCM in Flutter, you follow the steps given below:

Step 1 → Create a Flutter project

Step 2 → Add the google-services.json file. This file contains the configuration details for connecting your app to Firebase services.

Step 3 → Next, update the pubspec.yaml file. Open your Flutter project and add the necessary dependency, as shown below.

dependencies:
    firebase_messaging: ^x.x.x

 

Here 'x.x.x' should be replaced with the latest version of the firebase_messaging package.

Step 4 → Save the changes made in the pubspec.yaml file by pressing CTRL+S.

Step 5 → Login to Firebase by typing the command "firebase login".

Step 6 → Install the FlutterFire CLI tool by running the command "dart pub global activate flutterfire_cli" in your terminal. You can refer to the official documentation for the steps.

Step 7 → Next, add the firebase_core library to your Flutter project by running the command "flutter pub add firebase_core" in your terminal. 

Step 8 → Configure Firebase services in your Flutter project using the FlutterFire CLI. Run the command "flutterfire configure" in your terminal.

Step 9 → Choose your Firebase project and select the platform (e.g., Android).

After successful configuration, the Firebase App Id will be displayed.

Step 10 → Import the package as given below in the "main.dart" file.

import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

 

Replace "firebase_options.dart" with the appropriate filename if you have a different configuration file.

Step 11 → Next, initialize Firebase in your Flutter app by adding the following code to the "main.dart" file.

await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

 

After completing these steps, you have successfully added FCM to the Flutter app.

Token Based Messaging

You can send messages to individual users using the registration token of a device.

Get the registration token by adding the following in the "main.dart" file.

Initialize an instance of FirebaseMessaging" using "FirebaseMessaging.instance".
final FirebaseMessaging messaging = FirebaseMessaging.instance;

 

  • Next, fetch the token using the "getToken()" method.
     
messaging.getToken().then((value) => debugPrint(value));

 

  • Store and use the token on your server to send notifications to specific devices. 

Handling Messages in Foreground

To Handle messages in Foreground in FCM, you can use the "onMessage" callback provided by the "firebase_messaging" package in Flutter.

Implementation

import 'package:firebase_messaging/firebase_messaging.dart';

void main() {
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    // Handling the received message in the foreground
    print('Received FG message: ${message.notification?.body}');
    // Performing actions based on the message content
  });
  
  // Rest of the code
}

Explanation

In the above code, we listen to the "onMessage" stream provided by "FirebaseMessaging. " When a message is received in the foreground, the "RemoteMessage" object is passed to the callback function. Now you can perform any actions on the received message based on its content.

Handling Messages in Background

To Handle messages in the background in Firebase Messaging in Flutter, you can use the "onBackgroundMessage" callback provided by the "firebase_messaging" package.

Implementation

import 'package:firebase_messaging/firebase_messaging.dart';

void main() async {
  // Initializing Firebase
  await Firebase.initializeApp();
 
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  
  // Rest of your code
}

// Background message handler
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  
  // Handling the received message in the background
  print('Received background message: ${message.notification?.body}');
  // Performing actions based on the message content
}

Explanation

In the above code, we have defined a "backgroundMessageHandler" function that takes a "RemoteMessage" object as a parameter. This function is called when a background message is received. You can handle the received message and perform actions within this function.

By setting the "backgroundMessageHandler" as the callback for "onBackgroundMessage," Firebase messaging will call the function when a background message is received.

Frequently Asked Questions

What do you understand about FCM?

Firebase Cloud Messaging (FCM) is a service provided by Firebase that allows users to send messages and notifications using mobile/web applications. It sets up a reliable and efficient connection, thus making sure that the messages are delivered on time. 

What are notification messages?

Notification Messages are used to send notifications to users. These messages are designed to give people a user-friendly interface for displaying important information and updates. The FCM SDK handles notification messages.

How can you send messages using a token in Firebase Messaging in Flutter?

To send messages using a token, initialize an instance of FirebaseMessaging" using "FirebaseMessaging.instance". Then use the getToken() method to retrieve the registration token. Now store and use the token as needed.

How do you handle Messages in the Foreground in FCM?

To Handle messages in Foreground in FCM, you can use the "onMessage" callback provided by the "firebase_messaging" package in Flutter. The "RemoteMessage" object is passed to the callback function when a message is received in the foreground. Now you can perform any actions on the received message.

Conclusion 

Kudos on finishing this article! We hope this blog has helped you enhance your knowledge of Firebase Messaging in Flutter. 

Keep learning! 

We suggest you read some of our other articles on Firebase and Flutter: 

  1. Flutter basics
  2. Flutter interview Questions
  3. Hosting web applications using Firebase
  4. Firebase authentication
     

Refer to our Guided Path to enhance your skills in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas!

But suppose you are just a beginner and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

Best of Luck! 

Happy Learning!

Previous article
Flutter database integration
Next article
Flutter app testing
Live masterclass