Quick Summary
With the efficiently evolving tech development marketplace, keeping in touch with the users is a significant part of ensuring optimal results for your business application development. Push notifications are of the essence to engage users, encourage retention, and improve the overall experience of your business application for your end-users. Flutter Push Notifications with Firebase Cloud Messaging offers a smooth way to integrate cloud notifications within your business applications. In this blog post, we initially understand Push Notifications and their benefits. Also, we will discuss the steps to implement Push Notifications with Firebase Cloud Messaging for your next development project.
Push Notifications are brief messages or alerts mobile applications send to users’ devices. These notifications pop up on the user’s lock screen, notification center, or status bar, letting users know about your business application’s latest updates, messages, events, or reminders. These are of the essence for keeping your users engaged and informed, even if they are not currently using mobile applications. The Push notifications keep their users interested in the app and improve the overall experience, giving them timely and valuable information on their devices.
Push notifications are a crucial part of our day-to-day activities. When used correctly, they bring many benefits.
Flutter makes building mobile applications easier by combining many useful features and having a strong community to help. When you use Flutter along with Firebase Cloud Messaging (FCM), adding cloud notifications to your application becomes a breeze.
Before diving into the setup process, make sure you have the following prerequisites in place for implementing Flutter Push Notifications with Firebase Cloud Messaging:
Hire Flutter developer from us to easily build robust and performant cross-platform applications.
Now, when you have logged in to the Firebase console, create a new project by clicking on the ‘Add Project’ button.
After creating the project, you will be redirected to the project dashboard. For a detailed setup guide on registering Android / iOS apps to Firebase, please refer to our previous blog, Firebase Setup Guide.
Once Firebase has been set up and you have successfully registered your Android and/or iOS apps with Firebase, let’s start with our cloud messaging setup to help us control Push notifications.
FlutterFire is the set of Flutter plugins that enable Flutter apps to use Firebase services. To integrate Firebase Cloud Messaging with your Flutter app:
Add the firebase_messaging plugin by running the following command in your terminal:
Now, we must configure our iOS and Android for Flutter push notifications with Firebase.
Let us start with iOS push notifications with Firebase, which you can achieve using the steps given below:
Enabling App Capabilities
Registering Our iOS App To The Apple Developer Account
Uploading APN Certificate to Firebase
We must follow the steps below to ensure the setup for Android push notifications Firebase.
The next step is to handle the incoming notifications, for which you have to follow the process given below:
Now, we have to handle the notifications on the application side, as we have completed the setup to receive them. We will create a notification_service that will handle all the notification-related code.
Let’s start by creating notifications_service.dart
class NotificationService { ///single instance of FCM static final _messaging = FirebaseMessaging.instance; ///To store the FCM token static String? _token; }
We have created a static instance of the FirebaseMessaging object and also for the FCM token that we will be receiving from Firebase.
FCM Token is a unique identifier for the device that sends notifications to that device.
So, for that purpose, we need to store the FCM token.
Let’s add a function that will ask the user for notification permission. After the Android 13 update, it is possible to ask the notification permission in runtime.
///ask permission from the user to display notifications static void _requestPermission() async { final settings = await _messaging.requestPermission( alert: true, announcement: false, badge: true, carPlay: false, criticalAlert: false, provisional: false, sound: true, ); if (settings.authorizationStatus == AuthorizationStatus.authorized) { /// User has granted the notification permission } else if (settings.authorizationStatus == AuthorizationStatus.provisional) { /// User has only granted the provisional permission } else { /// User has discarded the permission popup or denied the notification permission } }
Now, let’s fetch the FCM token.
///setup the FCM token to receive notifications static void _getFCMToken() async { _token = await _messaging.getToken(); ///onTokenRefresh stream allows us to listen to the token value whenever it changes _messaging.onTokenRefresh.listen((newValue) { _token = newValue; }); }
Note: If you encounter the following error given below:
uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:firebase_messaging]
Follow the instructions after the error and provide the higher minSkVersion in the app-level build.gradle file(android/app/build.gradle), which in our case is 19
Notifications that are received when the app is open and is being used are referred to as foreground notifications.
We must use the Flutter local notifications plugin to handle and display the foreground notifications. If you want to display a notification in the foreground, you can use the data sent along with it and set the logic accordingly.
Add the Flutter local notifications plugin.
Let’s create a notification plugin instance and notification channels that will be used to display notifications.
///notification plugin initialisation static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); ///notification channel to handle android notifications static const AndroidNotificationChannel _androidNotificationChannel = AndroidNotificationChannel( 'high_importance_channel', 'High Importance Notifications', description: 'This channel is used for important notifications.', importance: Importance.max, ); ///notification channel to handle iOS notifications static const DarwinNotificationDetails _iOSNotificationChannel = DarwinNotificationDetails( presentAlert: true, presentBadge: true, presentSound: true, );
Now, let’s create a function to configure the Flutter local notifications plugin. This function will initialize the local notifications plugin with Android and iOS settings.
static void _configureLocalNotificationPlugin() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('ic_launcher'); const DarwinInitializationSettings initializationSettingsIOS = DarwinInitializationSettings( requestSoundPermission: false, requestBadgePermission: false, requestAlertPermission: false, ); await _flutterLocalNotificationsPlugin.initialize( const InitializationSettings( android: initializationSettingsAndroid, iOS: initializationSettingsIOS, ), onDidReceiveNotificationResponse: (response) {}, ); /** Update the iOS foreground notification presentation options to allow heads up notifications. */ await _messaging.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ); }
Further, we must create the Android notification channels with the properties defined in the _androidNotificationChannel variable declared in the function scope.
static void _createAndroidNotificationChannel() async { /** we have created the android notification channel which we had specified in the AndroidManifest.xml file earlier */ await _flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(_androidNotificationChannel); }
Now that we have completed all the setups required to receive the notification, we will create a function that will handle the display of the foreground notification and its click.
static void _showForegroundNotification(RemoteMessage message) async { RemoteNotification? notification = message.notification; if (notification != null) { _flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( _androidNotificationChannel.id, _androidNotificationChannel.name, channelDescription: _androidNotificationChannel.description, icon: 'launch_background', ), iOS: _iOSNotificationChannel, ), ); } }
Most of the notification part is completed. We need to add a foreground notification listener during the notification service initialization, which we will do later when we complete the background notification setup.
Notifications received when the application is in the recent applications tray or dead state are referred to as background notifications.
We do not have much control over displaying notifications as they are automatically added to the system’s notifications queue. However, we can modify the default behavior by omitting the notification variable in the remote message object that is received from the firebase.
We want to display the notification received for now, so we will set the background handling accordingly.
First, we need to add a background message handler in our main.dart following three simple criteria:
@pragma('vm:entry-point') Future_firebaseMessagingBackgroundHandler(RemoteMessage message) async { /** If we are going to use further Firebase services we need to * initialize the Firebase setup */ await firebaseInitialisation(); } void main() async { WidgetsFlutterBinding.ensureInitialized(); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); await firebaseInitialisation(); runApp(const FirebaseMessagingDemo()); }
After registering the background message handler, we must define a function in the notification service class that will be called when the notification is clicked.
static void _handleBackgroundNotificationOnTap(RemoteMessage message) async { RemoteNotification? notification = message.notification; if (notification != null) { debugPrint('Notification clicked: ${notification.title}'); // You can put your logic here to handle the notification on click } }
We have completed all the steps to receive and display notifications. Now, we have to initialize our notifications service to start handling notifications.
Let’s create an init function in the notification service class.
static Futureinit() async { _requestPermission(); _getFCMToken(); _configureLocalNotificationPlugin(); _createAndroidNotificationChannel(); /// Foreground notification handler FirebaseMessaging.onMessage.listen(_showForegroundNotification); /// Background notification handler FirebaseMessaging.onMessageOpenedApp .listen(_handleBackgroundNotificationOnTap); }
This init function has the initializing calls necessary to display and interact with our notifications.
Now, we will call this init function in our main.dart file to initialize the notification service.
void main() async { WidgetsFlutterBinding.ensureInitialized(); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); await _firebaseInitialisation(); await NotificationService.init(); runApp(const FirebaseMessagingDemo()); }
We have successfully completed the setup for the push notifications we will receive from Firebase cloud messaging (FCM). Let’s test this setup and send some notifications from the Firebase console.
To test the cloud notifications, we will send the notification from the Firebase console to the app. Let’s create our first campaign for Firebase notification messages and test them on our device.
Go Firebase console ➡️ Messaging ➡️ Create your first campaign.
Select the Firebase notification message and click on Create.
After that, Enter the notification title and text and click Next.
Select the preferred target to continue and click on Next.
In schedule, select now and click on Next. Skip the optional Conversion events and Additional options and click on Review.
Now, publish the notification campaign.
After the campaign is published, the notification should appear on the device. To explore the full potential of Firebase Cloud Messaging, try sending out multiple notifications enabling different data content within the campaign.
For more detailed info, refer to this GitHub repository for complete code.
Following these steps, you can easily set up cloud notifications in your Flutter applications using Flutter Cloud Messaging. Push notifications are a powerful tool for engaging users, delivering timely updates, and enhancing the overall user experience. As a business owner, if you are confused about making the right call to introduce Flutter Push Notifications with Firebase Cloud Messaging, you can contact a leading Flutter app development company like Bacancy and get started today with your development process while you focus on your core business.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.