Notifications in Flutter 🔔

Notifications are not an easy task especially when it comes to cross-platform Application Development using flutter. Currently, there are some packages like flutter-local-notification and recently launched awesome_notifications but scheduling notification is still a challenge as these packages use a local database which is not useful in the case of multi-device usage by a single user or by any chance of reinstalling the application. To avoid this problem instead of using local notification use a centralised system especially when scheduling a notification.

NOTIFICATION USING CLOUD FUNCTIONS

Firebase functions are the best solution for your notification problem but instead of using HTTP triggered or real-time database triggered use scheduled functions. Schedule functions get triggered automatically either daily or at any specified time or date.

To schedule a notification following things you need to know:

Implementation

Start by requesting permission and store FCMtoken in your database by calling a function from your dart main file. Make sure you call this function every time so that FCM gets stored in the database whenever it changes or the user login into a new device.

The next step is to store all notification data in your database. As per your requirement store necessary details in your database. If you are using an application where you need to modify the notification data based on some later changed details then make sure you assign an ID( Work Specified ) to the notification so that you locate the notification data and update its details when required.

FirebaseDatabase firebaseDatabase = FirebaseDatabase.instance;
firebaseDatabase
.reference()
.child('ScheduledNotifications')
.child(scheduleTime.month.toString())
.push()
.set({
'notificationID' : notificationId,
'titleString' : titleString,
'bodyString' : bodyString,
'time' : scheduleTime.toString(),
'uid' : FirebaseAuth.instance.currentUser.uid,
});

Now we only need to work on our backend function which will read all the data from our database and will send it on the date mentioned in the details ( or 3/7 days before the due date )

Follow these steps to initialize the firebase function.

In index.js, declare your function as given below (write a schedule notification).

exports.notificationServices =functions.pubsub.schedule(‘0 12 * * *’).onRun(async function(context){ // your funtions}

Read scheduled notification data from your database,

Getting data from the real-time database

After you read all the necessary data from your database and if the condition satisfied to send the notification then first you need to define a payload that is to be sent to the specified device and then push this payload data to the target device.

Payload and send data

Just keep in mind for the payload that:

Do go through this payload doc for more details

A Cross-Platform app developer Flutter SDK | Firebase backend Services |Arduino Programmer