How to Add Push Notifications to a Flutter App using Firebase Cloud Messaging?

Logo
appstonelab
Blog Image

What are push notifications:

Push Notifications are a kind of pop-up messaging source that notifies the app users about the updates happening in the app. They also play an important role in boosting the user involvement in your app.

The main motive of app push notifications is to provide information to the user so that he gets back to the application. These notifications emerge at the top of the smartphone screen even if the app is closed. Their detailed message gives the subscriber the below options:

  • Click on the message, or swipe it off the screen and view it later in the app.

Firebase Cloud Messaging is a resource provided by Firebase which lets you send these alerts to your users. You can organize various configurations to send various notifications to specific audiences based on time and regime.

Implementing Push Notifications:

For implementing push notifications, we would first need to create a Flutter project. You can follow the below steps:

1. Create a Flutter Project

1.1 Create a Flutter project following the below Flutter command:

– Flutter create pushnotification

1.2 After setting up the project, execute the following command in the terminal to run the project:

– Flutter run

After a successful build, you will get the following result in the screen:

2. Integrate Firebase Configuration with Flutter

We are going to incorporate the Firebase services with our Flutter project. But before that, we need to generate a Firebase project.

 2.1 Create Firebase project

After building up & creating a simple Flutter app, move to the Firebase official website here:

2.1.1 Go to the official website and click on “Get started”.

2.1.2 After clicking on “Get started”, create a new project by tapping on the “Add project” box.

2.1.3 Click on “Add project” and follow the below step:

– Enter your project name and click on continue

– After clicking on “Continue”, the new screen would be Google Analytics for your Firebase project and then again click on “Continue”.

Google Analytics is a free and unlimited analytics solution that enables targeting, reporting, and more in Firebase Crashlytics, Cloud Messaging, In-App Messaging, Remote Config,Testing, Predictions, and Cloud Functions.

– After clicking on “Continue”, open a new screen. And select “default Account for firebase” and click on “Create project”.

After that, the project will be created successfully. Firebase will show a prompt saying “Your new project is ready”.

After the project is created successfully, now we need to configure your app to use Firebase.

2.2 Configure your app to use Firebase

In the “Add an app to get started” column, click on the Android icon to add an Android app to Firebase.

On the succeeding screen, type in your Android package name & App nickname and hit on Register App. Your package name is usually the application ID in your app-level build.gradle file. If stated, the app nickname will be used throughout the Firebase console to illustrate this app. Nicknames aren’t available to users. And click on the “Register app”.

Initialise the google-services.json file & put it in your project’s app root index. Ensure the config file is not included with extra elements, like (2). After adding this file, click on the next button.

Then, add google-service.json file. The Google services plugin for Gradle shows the google-services.json file up. Change your build.gradle files to use the plugin.

– Project-level build.gradle (<project>/build.gradle):

– App-level build.gradle (<project>/<app-module>/build.gradle):

With that we have effectively integrated Firebase configurations with our Flutter project.

3. Integrate Firebase Messaging with Flutter

So, initially, we need to add the firebase-messaging possession to the ./android/app/build.gradle file. In the file, we will have to enter the following dependencies:

Following that, we need to enter a ,measure and a classification as an intent-filter within the activity label in the ./android/app/src/main/AndroidManifest.xml file:

Now, we need to generate a Java file called Application.java in the track:
/android/app/src/main/java/<app-organisation-path>.

Then, we need to add the code from the below code extract inside it:

Now, we need to allot this Application task to the application tag of the AndroidManifest.xml file as shown in the code extract below:

This finishes our setup of the Firebase messaging plugin in the native Android code. Now, we’ll proceed to the Flutter project.

Here, we are going to apply the firebase_messaging bundle, for that, we need to enter the plugin to the dependency option of the pubspec.yaml file.

We need to add the below convention  to the dependencies option:

firebase_messaging: ^7.0.3

4. Now Implement a Simple UI Screen

The messageTitle variable will get the notification message title and notificationAlert will be allotted the action that’s been finished once the notification shows up.

So we need to set up the code to get the notification and apply the notification message to show it on the screen.

For that, we need to enter the code from the below code extract in the initiState function:

Here, we have utilised the configure procedure offered by firebase Messaging instance which in turn provides the onMessage and onResume call-backs. These call backs shares the notification message as a limitation. The message response will bear the notification item as a map item.

The onMessage task triggers when the notification is received while we are running the app. The onResume function activates when we obtain the notification alert in the device notification bar and opens the app through the push notification itself. In this instance, the app can be playing in the background or not running at all.

Now we just need to configure a message in Firebase Cloud Messaging and share it to the device.

5. Create a Message from the Firebase Cloud Messaging Console

First, we need to revert to the Cloud Messaging console in the Firebase website as displayed in the picture below:

Here, we can view the ‘Send your first message’ alternative in the window, as we have not aligned any messages earlier. We need to tap on it which will take us to the below window:

Here, we can show the headline, text, photo, and name of the alert. The headline we position here will be given as the title in the message object on the callbacks we positioned earlier in the Flutter project.

After fixing the specific columns, we can tap on ‘Next’ which will take us to the below window:

Here, we need to share our target app and click on ‘Next’.

For Scheduling we can keep the default preference:

Next, the Conversion window will display which we can put as default as well, and then tap on the ‘Next’ icon.

Next, a window where we need to share the custom data will show up in which we can position the title and click_action. This click action event is activated whenever we click on the alert that shows up in the notification bar of the device.

Now, we are all set to send the first notification message to the device as we tap on the ‘Review’ button and send the notification. When we click on “Review button”,  it shows an alert dialog box which looks like the image below and then click on “Publish”.

When we click on the publish button we finally send push notification in our Flutter app.

The app is playing in the background. When we send the message, we get a push notification in the notification bar of the device. Then, as we draw down the notification bar, we can view the notification message title and text. And, by tapping on the notification message, we can initiate the application and show the custom data on the screen. This makes sure that our onResume call back was activated.

And we’re done! We have well added a push notification feature in our Flutter application using Firebase Cloud Messaging.

Conclusion:

Push notifications plays an important role in any mobile app. Basically, push notification is a messaging medium that alerts the app users about what’s going on in the app. In this blog, we have discussed how to implement push notifications in our Flutter project using Firebase.

Related Post

View all
Blog Image

New AdonisJS Tools: FlyDrive, Transmit, Health Checks & More!

AdonisJS update introduces FlyDrive, Transmit, health checks & more, simplifying file storage, real-time events, debugging, and background tasks for faster Node.js development.

Blog Image

The behaviorism of design: 15 fundamentals every UI/UX designer should be aware of

1. Hick’s Law: Hick’s law is the most prevailing fundamental, along with the gestalt laws. It’s also very elementary to understand and practice. 2. Priming: Priming is a basic fundamental of psychology with a huge impact on user interface design: acknowledgment of something makes a user more likely to think and express in related ways at later steps in the interaction. 3. Cognitive Load The total analytic load, or portion of mental processing power required to use your site, impacts how effortlessly users discover content and finalize the tasks. 4. Progressive Disclosure Progressive disclosure postpones the improved or hardly used […]

Blog Image

Custom extensions in Dart

In this blog, I would like to share the amazing concept of Dart Extensions and how to make custom extensions for quality and optimised code. The specialty of this blog is that it will show you how to create extensions from your JSON models and it is very useful for state management. What are Extensions? Extension is used to enhance the feature of an existing class or a library. Using the extensions, one cannot change the existing properties of the class but can definitely change the view of class or model. Extensions are identical to the “prototype” of Javascript but […]

Blog Image

How To Flash Custom Rom on an Android Device

What Is a Custom Rom? (Android Read Only Memory) A file consisting the feasible requirements (a system image) of an Android OS and allied apps. The “stock ROM” comes inbuilt on the phone or tablet, whereas a “custom ROM” comes from an outsider.The custom ROM is either a distinctively improved OS, such as Cyanogen, or a stock version made accessible for older devices or for new devices before the vendor launch date. Why should you Use a Custom ROM? Flashing the ROM: Flashing a ROM means installing the system image into the device’s internal flash memory. Flash memory retains the […]

Blog Image

Top server security analysis tools

There are many server analysis tools available today and we will see some tools/websites which scan server/hostname for various security testing which I usually use. Sometimes we ignore small security points, but those points motivate hackers to hack sites. There are some concepts which secure the user (End user) data security. We can make our server/domain secure by HTTP/HTTPS, SSL/TLS, SMTP/PoP3, SSH, FTP, etc.. various tests on the site below which will list your vulnerabilities. 1. Observatory.mozilla.org This is one of the best sites to test server vulnerability. I always use this to scan first to check various security. It […]

Blog Image

Flutter Snippets

What is a snippet in flutter? Flutter snippets is a collection of commonly used flutter classes and methods. It increases your code speed of development by eliminating most of the boilerplate code associated with creating a widget. Currently, Awesome Flutter snippets provide different kinds of shortcuts for widgets. For example, StreamBuilder and SingleChildScrollView can be created by typing the shortcut streamBldr and singleChildSV respectively. Please find below few of the snippets with the respective shortcuts: Shortcut Expanded Description statelessW Stateless Widget Generates a Stateless widget statefulW Stateful Widget Generates a Stateful widget build Build Method Explains the part of the […]

Blog Image

Deep linking

Deep linking technology has obtained substantial awareness over the past few years by permitting the marketers to upgrade their involvement with mobile app users. Deep links offer a comprehensible way for app publishers to rectify, convey, and transfer the users to a particular content within apps. Eventually, they can assist the app publishers boost the installs, user involvement, and conversions — the fundamental to any app’s accomplishment. Deep links are mobile links that manage much like hyperlinks, but instead of pointing out the users to a web page, deep links send them to a certain screen within a mobile application. […]

Blog Image

5 Tips for Managing Diversity in the Workplace

Workforce across the world is becoming increasingly diverse, and this has a huge impact on the management. We tried creating a guide with practical and actionable tips for managing diverse teams that are inclusive and positive. What is diversity in the workplace? Diversity in the workplace refers to an organization that intentionally employs a workforce comprised of individuals of range of characteristics, such as gender, religion, race, age, ethnicity, sexual orientation, education, and other attributes. Workplace diversity is a regular subject of discussion among employers, hiring managers, and recruitment skilled officials but diversity and inclusion in the workplace isn’t just […]

Blog Image

Getting started with Tailwind CSS

What is tailwind CSS? TailwindCSS is a utility-first CSS framework. This implies that they are primarily focused on utilities. They provide utility classes like flex, pt-4, bg-orange-100, and rotate-90 that can be combined for building modern user-friendly UI components. Their purpose isn’t necessarily to define your component’s appearance. Using the different classes they provide, you decide what to do. Why Tailwind CSS? An experienced CSS framework user or a total beginner might ask this question. Tailwind allows for full customization, allows the use of utility classes, and is a very low-level and basic CSS framework for anyone interested in using […]

Blog Image

Simple & Constructive methods to improve your Visual/UI Design

1. Get acquainted with design patterns Get accustomed with the UI/UX design patterns and what specific issues they solve. Generally speaking, design patterns are known as common reference points, guides, templates that designers might utilize to resolve a particular issue when designing a website or mobile app, so you do not have to revamp the wheel every single time trying to solve the problem. I’ve assembled a list of some of the best places to obtain the design specimen on the web: pttrns.com A great compilation of mobile design specimens uisources.com — mobile design samples & interactions uigarage.net — regular […]

Blog Image

What is SEO(Search Engine Optimization)?

Search engine optimization (SEO) consists of improving a website’s ranking in search engines and thereby boosting its traffic from search engines. The objective of SEO is to target unpaid traffic (also known as “organic” or “natural” results) rather than direct traffic or paid traffic. The crucial difference between SEO and paid advertising is that SEO involves “organic” ranking, which implies you don’t pay to be there in space. Search machine optimization means taking a chunk of online content and optimizing it, so search machines like Google show it towards the highest of the runners when someone searches for a commodity. […]

Blog Image

Sanctum-Library

Sanctum is an easy package to issue API tokens to the users without the complication of OAuth. Sanctum provides authentication services based on Laravel built-in cookie base sessions. For small applications, I prefer using Sanctum because it’s simple and easy. What is Laravel Sanctum? Laravel Sanctum gives a lightweight authentication system for simple token based APIs and mobile applications, and single page applications (SPA). In Sanctum, we have two different ways mainly as mentioned below: 1) The API Token Authentication.2) Single page application authentication. This Authentication process is similar to API token Authentication process. Now we shall understand the difference […]

Hero Image

Ready to BuildYour Next Big Project?

Partner with our expert team for clear guidance, reliable solutions and faster, high quality delivery from idea to launch.

Book Free Consultation