Design Converter
Education
Last updated on Mar 19, 2024
Last updated on Mar 19, 2024
Software Development Executive - II
A Flutter and iOS developer.
Software Development Executive - II
A Flutter developer who loves crafting beautiful designs and features that people enjoy. When she is not coding, she is sketching ideas, experimenting with animations, or relaxing with a chai and good music.
Flutter offers an excellent framework for building natively compiled mobile, web, and desktop applications from a single codebase. When combined with Firebase Cloud Messaging (FCM), your application's ability to send and receive messages becomes significantly more powerful, turning it from a simple interactive tool to a real-time communication powerhouse.
Building a robust mobile application goes beyond UI/UX design and code execution. As more apps land in marketplaces daily, standing out requires that extra touch. One feature that enhances the user's interaction with an app is the ability to send and receive real-time messages. In the Flutter space, Firebase messaging has proven vital for this.
Firebase Cloud Messaging (FCM), formerly Google Cloud Messaging, is a free service that facilitates messaging between mobile apps and backend servers. A vital benefit of FCM, particularly in a Flutter project, is that it allows developers to send and receive messages in both the app's foreground and background states, boosting the app's overall functionality and enriching user experience.
In this blog, we will focus on Flutter Firebase Messaging. Specifically, we will delve into the integration process, handling background messages, and discuss the importance of Firebase Cloud Messaging on Flutter applications.
Before we dive into how to integrate Firebase Messaging into a Flutter project, let's take a moment to understand what Firebase Messaging is and its pivotal role in enhancing the functionality of Flutter applications.
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that allows you to reliably send messages at no cost. You can use FCM to notify a client app when a new email or other data is available to sync, send notifications to drive user engagement, or send marketing messages and updates to your users across platforms.
In the context of Flutter, using Firebase messaging provides a couple of distinct benefits. First, it offers a robust platform for send app-to-user notifications, enhancing the overall user experience. This includes notifications, chat, and data messages, all handled differently but equally important for your Flutter app. A unique aspect of FCM is the ability to handle notification messages with the app in the foreground, background, or even terminated.
When a Flutter Firebase messaging service runs, users receive messages efficiently and can interact with your app in real-time. Equally important is working with complex data structures in your messages, a useful feature for apps requiring significant back-and-forth user-app interaction.
Before integrating Firebase Messaging into your Flutter app, you must ensure that both Flutter and Firebase have been installed and set up correctly. Below is a step-by-step guide:
Prerequisite Software and Tools: Make sure that you have the following software and tools installed:
Flutter SDK
Dart SDK
Android Studio or any preferred IDE with a Flutter plugin
Firebase account
Creating a Firebase Project: Navigate to the Firebase console, create a new project, and give it a suitable name.
Initializing Firebase in Your Flutter App: In your Flutter project, install firebase_core, the core Flutter Firebase plugin, which is necessary to use any Firebase services in your Flutter application. You can add it as a dependency in your pubspec.yaml file, and then run the flutter pub get command.
Setting up Firebase on Android and iOS: Each platform (Android/iOS/Web) has a different setup process:
For Android, you would need to register your app with Firebase, download the google-services.json file, and place it in your Flutter project's android/app directory. Update your android/build.gradle and android/app/build.gradle files as per Firebase guidelines.
For iOS, similar steps are followed, but you download a GoogleService-Info.plist file and place it in the ios/Runner folder. You must also enable "Push Notifications" and "Background Modes" in your Xcode project. Note that to send notifications to Apple devices, you must upload your Apple Push Notification service (APNs) certificate to the Firebase console.
After following these steps, you have successfully set up your Flutter and Firebase environment and are ready to integrate Firebase Messaging into your Flutter app.
Once the Firebase environment is correctly set up, you must integrate Firebase Messaging into your Flutter application. This involves several key steps, which we'll discuss in detail below:
Adding Firebase Messaging Dependency: The first step involves adding the Firebase Messaging Plugin into your Flutter project. Add firebase_messaging to your pubspec.yaml file under dependencies, and then run the flutter pub get command.
Initializing Firebase Messaging: Import the firebase_messaging plugin in your Dart file. You'll need to create an instance of Firebase Messaging using the FirebaseMessaging class. This instance allows you to interact with Firebase Cloud Messaging. This is how you initialize Firebase:
1import 'package:firebase_messaging/firebase_messaging.dart';
1final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
Requesting User Permissions: Firebase Cloud Messaging requires user permission to send notification messages. Although some permissions are granted by default on Android, iOS requires manually requesting these permissions.
Receiving Message Notifications: Firebase Cloud Messaging can send two types of messages: notification and data. The Firebase Messaging plugin provides methods to handle incoming messages accordingly. Setting up handlers for when the app is in the foreground, background, or terminated is essential.
Responding to Message Interaction: Responding to user interactions in Flutter applications involves using the .configure method of our FirebaseMessaging instance. This is where we handle interaction events - when a user taps on a notification, for instance.
Sending Messages via Firebase Console: The Firebase console can also send notifications to your Flutter app. Once Firebase is fully configured and integrated, you can test notifications directly from the console.
With your Firebase integrated into your Flutter project, you're now ready to create a Firebase messaging service. Here's a step-by-step guide:
Import Required Libraries: Before creating the Firebase Messaging service, you must import the required libraries into your Dart file.
1import 'package:firebase_messaging/firebase_messaging.dart'; 2import 'dart:async';
Create the Class and Constructor: After importing the libraries, you then need to set up your class and constructor, where _firebaseMessaging is an instance of the FirebaseMessaging class.
1class FirebaseNotifications { 2 FirebaseMessaging _firebaseMessaging; 3 4 void setUpFirebase() { 5 _firebaseMessaging = FirebaseMessaging(); 6 firebaseCloudMessagingListeners(); 7 } 8 }
Handle Message Listener Code: Enter the code to handle Firebase message listeners for various user interactions.
1void firebaseCloudMessagingListeners() { 2 if (Platform.isIOS) iOS_Permission(); 3 4 _firebaseMessaging.getToken().then((token) { 5 print(token); 6 }); 7 8 _firebaseMessaging.configure( 9 onMessage: (Map<String, dynamic> message) async { 10 print('on message $message'); 11 }, 12 onResume: (Map<String, dynamic> message) async { 13 print('on resume $message'); 14 }, 15 onLaunch: (Map<String, dynamic> message) async { 16 print('on launch $message'); 17 }, 18 ); 19 } 20 } 21 22void iOS_Permission() { 23 _firebaseMessaging.requestNotificationPermissions( 24 IosNotificationSettings(sound: true, badge: true, alert: true) 25 ); 26 _firebaseMessaging.onIosSettingsRegistered 27 .listen((IosNotificationSettings settings) 28 { 29 print("Settings registered: $settings"); 30 }); 31}
The above code blocks set up Firebase Messaging and configure listeners for different message types depending on the app's lifecycle (Foreground, Background, Terminated). The iOS_Permission function requests appropriate iOS permissions.
1final _firebaseNotifications = FirebaseNotifications(); 2_firebaseNotifications.setUpFirebase();
This newly created Firebase Messaging service now handles sending and receiving messages, enhancing your Flutter application's communication capabilities.
Efficiently sending and receiving messages is crucial to any Flutter Firebase Messaging service. With Firebase Cloud Messaging (FCM), you can send two types of messages to clients:
Notification messages, sometimes called "display messages," are handled automatically by the FCM SDK.
Data messages, which are handled by the client app.
These messages can contain an optional payload – additional data to be sent along with the message. Messages and their payloads can be handled differently depending on the state of the receiving application:
Foreground: When your app is in the foreground, incoming FCM notifications are received by FirebaseMessaging.onMessage.
Background: If your Flutter app is in the background, clicking on the incoming notification will make the app reach the foreground and trigger FirebaseMessaging.onLaunch or FirebaseMessaging.onResume.
Let's look further into Flutter Firebase Messaging's message-handling capabilities.
Firebase's console allows you to send messages easily.
Navigate to your Firebase project in the Firebase Console.
Click on "Cloud Messaging" in the left-hand menu.
Click on "Send your first message."
Enter the text of your message.
Optionally, set a message label for tracking.
Choose “User segment” and select your app.
Finally, click on "Review" and then "Publish."
Receiving messages involves using Firebase Messaging methods to handle incoming messages: onMessage, onLaunch, and onResume. Setting up these handlers will allow your app to receive incoming FCM notifications, providing a more engaging experience to your users.
Implementing Firebase Messaging allows your app to handle incoming messages efficiently, offering a rich user experience.
Your Flutter application's ability to receive messages when it's running in the background is crucial to creating an excellent user experience. However, handling background messages in FCM requires a bit more setup than foreground messages.
To enable your Flutter app to handle background messages, you'll need to define a top-level function, not inside any class, that the Flutter engine can call when a message comes in. Remember that this handler runs separately from your app, so it doesn’t have access to your app's state.
Here’s how to set up your background message handler:
1Future<void> _messageHandler(RemoteMessage message) async { 2 await Firebase.initializeApp(); 3 print('handleBackground: ${message.messageId}'); 4} 5 6void main() { 7 FirebaseMessaging.onBackgroundMessage(_messageHandler); 8 runApp(MyApp()); 9} 10 11
In the above code snippet, _messageHandler is the named function—a top-level function that takes RemoteMessage as its argument. Then, inside your main function, you call FirebaseMessaging.onBackgroundMessage with your handler function before running your app.
This setup allows you to handle incoming FCM notifications whether your app is in the foreground or the background. However, the background message handler only manages data messages, not notifications.
By having your app handle background messages, you can ensure the user continually engages with your application— regardless of whether they're actively using it.
After integrating Firebase Cloud Messaging into your Flutter app and setting up the necessary message handling, it is essential to test your Firebase implementation.
To do this, send a test message using the Firebase console "Cloud Messaging" option. Here’s how:
Creating a Notification: Navigate to your Firebase project in the Firebase console, click on the "Cloud Messaging" tab, and then click "Send your first message."
Enter the Notification Details: In the form fields that appear, fill in the appropriate information for the test notification like Notification title, text, etc. Then scroll to the "Target" section.
Choose the Target: In the "Target" section, choose "User segment" in the drop-down menu, then select your app from the next field.
Test It Out: Click "Review," then "Publish" when ready. Your test notification should appear in your Flutter app shortly!
Firebase notifications ensure your app's real-time communication capabilities and present several opportunities to enhance user experience and engagement.
Consider these enrichments you can make with Firebase notifications:
Personalization: Use data from user behaviors and preferences to create customized notifications. This personal touch leads to a more engaging user experience.
Prompting User Action: Send push notifications to invite users to interact with your app, for instance, reminding them to complete a game level, view new content, or respond to a message.
Improving User Retention: Regular and relevant notifications keep your app in mind, increasing the likelihood of repeated app usage.
Driving Traffic: Aside from driving traffic to your app, Firebase notifications can also direct users to specific pages within the app, such as a new product detail page or a special offer.
Real-Time Updates: For apps depending on timely information, Firebase notifications ensure that your users are always up-to-date.
By effectively using Firebase Messaging in your Flutter app, you can significantly improve user engagement, retention rates, session times, and conversion rates. In addition, it grants your Flutter application a high level of interactivity, nudging it from a simple app to an immersive experience for your users.
Real-time communication contributes significantly to the richness of mobile app experiences. Firebase Cloud Messaging (FCM) lends this capability to your Flutter app with aplomb. FCM fosters deeper interactions between your app and its users by allowing you to send or receive messages quickly.
From setting up the Flutter and Firebase environment to handling messages in different app states, this guide illuminates the critical steps in integrating Firebase Messaging into a Flutter application. Most importantly, by helping you leverage Firebase Messaging's capabilities, this guide steers you toward creating a delightful, engaging user experience characterized by prompt updates and personalization.
Happy coding, and here's to creating more interactive Flutter apps with Firebase Messaging!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.