Sending Notifications to Flutter App
In this semester, our team tried to develop an mobile APP using Flutter. One user story is that when user are not using the APP, he/she should be notified when new friend request or new message coming
Since we are using firebase as our backend service, cloud functions can be used to monitor the database, and send notifications when triggered
This document provides a simple example:
- The function triggers on writes to the Realtime Database path where followers are stored.
- The function composes a message to send via FCM.
- FCM sends the notification message to the user's device.
Cloud Functions
Setting Triggers
Interactions between users is stored at
/users/{userId}/interactions/{interactionID}
in Cloud
Firestore. Firebase SDK provide 4 triggers
onCreate
,onUpdate
,onDelete
,onWrite
In our case, we want to send a notification when user generate an interaction. So the function running on Node.js 8 should specify the document path and event type:
1 | const functions = require('firebase-functions'); |
Parse Data
Based on the data we need, we can set the FCM messages Notification messages will be displayed to end-user devices, data messages can be handled by client app and token is device registration token generated by FCM SDK in client app
For given platform, token can be got as follows
- iOS (Swift) —
retrieveFCMTokenForSenderID:completion:
- Android —
getToken()
Users can have multiple devices, however, for convenience, just assume that token is stored as a string under the user profile
The content of interaction is a JSON like data passed by snapshot
1 | { metaData: {}, |
Once getting token and notification data, we can set the message
1 | const functions = require('firebase-functions'); |
Sending Message via Firebase Cloud Messaging
This is very straight forward, sending the message to target device, then receiving response or error code
1 | const functions = require('firebase-functions'); |
The cloud work is completed, next step is to make your device receive notifications
Firebase Messaging
Firebase
Messaging is a flutter plugin for FCM, to use this, just update a
dependency in the pubspec.yaml
file
The README file introduced how to integrate Firebase with your Android and IOS project, as we are using Cloud Storage and Firebase Auth. these part is already done yet. Then import the plugin and instantiate it in the Dart code
1 | import 'package:firebase_messaging/firebase_messaging.dart'; |
BTW, The device token can be accessed by doing so
1 | _firebaseMessaging.getToken().then((token) { |