Send push notifications from a Flutter app to devices with Firebase

Send messages from device to device via FirebaseUsing Firebase Cloud Messaging and Firebase Cloud Functions we can implement a system to send and receive push notifications from a Flutter app.Photo by Sigmund on UnsplashToday we are going to focus on h…

Send messages from device to device via Firebase

Using Firebase Cloud Messaging and Firebase Cloud Functions we can implement a system to send and receive push notifications from a Flutter app.

Photo by Sigmund on Unsplash

Today we are going to focus on how to send push notifications from a Flutter app. Therefore Firebase will be used as it provides packages that can be used within a Flutter app. In this scenario, a push notification will be triggered and sent to your own device.
Firebase offers some of its services only for paying users but they charge you for your usage. If you don’t use the services, you won’t be charged anything.

Our final workflow will look like this:

  1. From our app, a message with custom text is sent to Firebase Cloud Functions.
  2. The function will forward our message to the Firebase Cloud Messaging (FCM) service.
  3. The service will deliver the message to the target device.
  4. Our app should receive a push notification within some seconds.
Workflow of the message

❌Unfortunately, at the moment there is no possibility for us, to send messages from app to device without using Firebase Cloud Functions as the FCM Flutter package does not provide a method for it. So we have to use the workflow above.

The next steps of this article are as follows:

  1. Create and set up Firebase account and project
  2. Prepare Flutter app
  3. Write code to send and receive push notifications

Firebase Setup

Before the fun part starts we need to set up the backend so that our app can send and receive push notifications. We will create a Firebase project and a Firebase app for each supported platform (iOS, Android, Web). If your Firebase environment is already configured, you can skip this part.

Create a new Firebase project

If you don’t already have one here is a short guide. Otherwise, you can skip this part.

  1. Go to console.firebase.com and log in with your Google account.
  2. Click Add project
  3. Choose a name
  4. Google Analytics can be skipped
  5. Create the project
Firebase page after successful project creation

Change plan for Firebase Cloud Functions

To use Cloud Functions you need to upgrade your project from the Spark plan (free usage) to the Blaze plan (pay per usage). This requires payment information to be entered (for example a credit card or you can also use Google Pay).

❗ This example won’t cause any recurring costs, but if you extend your Firebase usage above the free limits, you will be charged for it. Keep that in mind! Pricing details can be found here.

To change the plan, go to the Cloud Functions area, hit the Upgrade project button, and follow the instructions (see images below)

Link to the Cloud Functions area
Upgrade notification when using Cloud Functions for the first time

After the upgrade, you should see an empty dashboard. Your deployed functions will be available here, where you can check logs, health status, and usage statistics.

❗ Please be aware that a deployed cloud function occupies resources which can lead to costs. If you deploy more functions, the costs might increase. You can use a budget alert to get notified when unexpected costs arise.

App Setup

The first step is to link our app with the Firebase backend. After that, we will focus on writing code to send and receive push notifications.

Link with Firebase backend

This is a pretty easy task nowadays as there is a command-line tool that will support us with the configuration. At first, we need to add the Firebase Core dependency to our project. Run the command

flutter pub add firebase_core

from your app’s root folder. The next command installs a cli to connect our app with Firebase. Run

dart pub global activate flutterfire_cli

and wait until the install process has finished.

Finally, run the command

flutterfire configure

It will guide you through the setup process, create Firebase apps and link them with your Flutter app. Afterward, there will be a Dart file containing all relevant Firebase account information. Do not check this file into version control ❗.

Installing the Firebase packages

In your Flutter project open the pubspec.yamlfile, add the Firebase Messaging package, and the Cloud Functions package (see image below).

flutter pub add firebase_messaging
flutter pub add cloud_functions
Required Firebase packages in pubspec.yaml

Enable app capabilities for iOS

If you are targeting iOS as a platform, you need to do some more configuration work to enable push notifications. One particular requirement is that you have an active Apple developer account. It won’t work without it. The following article guides you through the complete setup process:

  • How to configure your XCode project
  • How to register keys, provisioning profiles, and identifiers in the Apple Developer portal

FCM via APNs Integration | FlutterFire

Android apps don’t require additional setup steps.

Set up cloud functions

A handy helper for everything related to Firebase are the Firebase CLI tools (installation guidelines). We will use them to initialize the cloud functions and to update them.
After the installation, run the command firebase init functions. It will guide you through the login and setup process. Be sure to select the Firebase project you created earlier. Finally, you will see a functions folder in your project directory. It contains the deployed functions and their dependencies. The setup is completed 🎉.

functions folder for Firebase Cloud Functions

Code Setup

Finally, we are getting to the most interesting part. Here we will create the cloud function that delivers our message to Firebase Cloud Messaging. And we will implement handlers for incoming notifications so that our app displays the notifications.

Setting up the cloud function

Here is the code for the Cloud Function, we will use. It takes a data argument supplied by the caller and calls the Cloud Messaging service. The result indicates the success or failure of the operation.

The dataobject is a Map that should have 3 properties:

  1. targetDevices is a list of strings containing the tokens of the target devices
  2. messageTitle is a string containing the title of the message
  3. messageBody is a string containing the body of the message

Insert this code into the index.js file in your functions folder. Then run the command firebase deploy –only functions. Your dashboard in Firebase should be updated after the operation is finished. The function is ready to be called 👏

Firebase Functions dashboard after deploying a function
Output of the deployment process

Register for incoming notifications

When the app is not running all the notifications are handled by the operating system. You get your typical sound and the app icon in the notification bar just as you are used to. To handle incoming notifications while our app is running we need to register a handler function. If there is no handler the message is just swallowed and you don’t even know that you received one.

After our handler is registered and a notification is received while the app is running, the title and body will be printed to the console.

A background handler has the restriction that it must be a top-level function. It will be invoked when a notification is received and the app is in the background.

Send a push notification

To send a push notification we need to get the device token of the target device (in this case our own device). We then send the message to the Firebase Cloud Functions service which delivers it to the Firebase Cloud Messaging service and it handles everything else. If for example, the target device is offline the message is transmitted as soon as the device is online again. All the little details we don’t need to worry about 🎉

Device token is printed to the console on app launch

The code tries to find a Firebase function with the name notifySubscribers. When found, it invokes the function with an argument that contains the target devices, the message title, and the text, the user entered in the UI. A print message in the console tells us if the call was successful.

Customize a push notification

You can add additional data to a push notification and have your app handle it in different ways. The RemoteMessage object has a data property where you can add your custom data to the request. Your app can read these values and react accordingly. The image below shows a modified version of our cloud function using the data property.

Send a test notification from Firebase

Firebase allows to send customize push notifications from its UI. That way you can test for example how a notification looks like when your app is not running. Follow these steps to send a notification.

  • On the Firebase page go to Cloud Messaging.
Menu overview on the Firebase page
  • Click on Send your first message.
Send your first message with Cloud Messaging
  • Enter at least a title and a description and click Send test message.
Send a test message with Cloud Messaging
  • Add your device token and click on Test.
Finally sending the message to the target device

Your device should receive a push notification. The handling depends on whether the app is in the foreground, in the background, or not running at all.

  • When the app is not running at all, you’ll get a hint in your notification tray of the mobile OS.
Received push notification from Firebase when app is in background
  • When the app is running in the background, you’ll get a hint in your notification tray of the mobile OS and the background handler function will kick it, if it is set (see possible output below).
Output when receiving a notification while app is in background
  • When the app is running in the foreground, the foreground handler function will handle the message if set (see possible output below).
Output when receiving a notification while app is in foreground

Conclusion

This is the shortest way possible to enable a Flutter app to receive AND send push notifications to other devices. The configuration of the backend might be a bit overwhelming at first, but it’s really not that hard. With this knowledge, you can interact more easily with your app users in an anonymous way.

Source code

You can find the source code on GitHub. The repo contains the working app without the Firebase configuration. You need to create the account, link your app with it and deploy the cloud function. Then you can reproduce all the results of this article.

Related articles

If you like the article, I would be glad to get a clap 👏 (did you know that you can clap several times? 😎) and also, if you haven’t followed me yet, I’d appreciate that as well. Feel free to have a look at my other Flutter articles.


Send push notifications from a Flutter app to devices with Firebase was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


Print Share Comment Cite Upload Translate
APA
xeladu | Sciencx (2024-03-29T10:17:28+00:00) » Send push notifications from a Flutter app to devices with Firebase. Retrieved from https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/.
MLA
" » Send push notifications from a Flutter app to devices with Firebase." xeladu | Sciencx - Monday February 7, 2022, https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/
HARVARD
xeladu | Sciencx Monday February 7, 2022 » Send push notifications from a Flutter app to devices with Firebase., viewed 2024-03-29T10:17:28+00:00,<https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/>
VANCOUVER
xeladu | Sciencx - » Send push notifications from a Flutter app to devices with Firebase. [Internet]. [Accessed 2024-03-29T10:17:28+00:00]. Available from: https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/
CHICAGO
" » Send push notifications from a Flutter app to devices with Firebase." xeladu | Sciencx - Accessed 2024-03-29T10:17:28+00:00. https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/
IEEE
" » Send push notifications from a Flutter app to devices with Firebase." xeladu | Sciencx [Online]. Available: https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/. [Accessed: 2024-03-29T10:17:28+00:00]
rf:citation
» Send push notifications from a Flutter app to devices with Firebase | xeladu | Sciencx | https://www.scien.cx/2022/02/07/send-push-notifications-from-a-flutter-app-to-devices-with-firebase/ | 2024-03-29T10:17:28+00:00
https://github.com/addpipe/simple-recorderjs-demo