How to make Firebase Push Notification Increase Badge Count When Receive Notification In Flutter?

Viewed 1730
  • First of all, this is a self-answering question.
  • Second, I will try to describe in great detail the solution I have implemented for this situation.
  • The problem posed: the badge attribute cannot be dynamically incremented
  • source: https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload#badge.
  • So how do I get this badge property to automatically increment.? The solution I have answered is below, the 1st answer Also when you do this on multiple mobile devices what you need is:

IMPORTANT !!!

  • DO THIS WHEN YOU HAVE FOLLOWED THE STEPS IN THE ANSWER BELOW !!!

B1. Included badge number in each token of devices. enter image description here

B2. change this when app init and generate fcm-token

FirebaseFirestore.instance.collection('fcm-token').doc(device_name).set({'device1_pt1': token_id,'number': 0});

B3. Put this then onmessage is call.(by onlauch, onresume, onmessage)

FirebaseFirestore.instance.collection('fcm-token').doc(device_name).update({'number': 0});
1 Answers

B1. Create new Colection like new Colection B2. In API(Handle Data):

Data received: Data = {'token-device': String, 'body':'string'}

#Read badge number from firebase(create at B1):

badge = db.collection('badge').document('count').get()._data 
badge = badge['number'] badge += 1 #increate when receive new data. 
badgedx = db.collection('badge').document('count').update({'number' : badge})
Data['badge'] = str(badge) # must be string 

Data before save to firestore: Data = {'token-device': String, 'body':'string','badge':'1'}

#Save to firestore
addx = todo_ref.document() 
addx.set(Data) #save to firestore 

B3.In Firebase-Function(file index.js)

> Add badge number 

 var badgecount = newData['badge'];
    var options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
      };
    var payload = {
        notification: {
            title: 'title',
            body: 'Phiếu khảo sát khách hàng',
            sound: 'default',
            alert: 'alert',
            badge: badgecount,
        },
        data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK',
            key1: newData['content'],
        },
    };` 

B4: In FLutter: Reset badge number = 0

    _configureFirebaseListeners() {
      _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true),
    );
    _firebaseMessaging.configure(
      
      onMessage: (Map<String, dynamic> message) async {
        print('onMessage: $message');
         _setMessage(message);
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('onLaunch: $message');
         _setMessage(message);

      },
      onResume: (Map<String, dynamic> message) async {
        print('onResume: $message');
         _setMessage(message);
      },
    );
 

 }
    _setMessage(Map<String, dynamic> message)  {
      FirebaseFirestore.instance.collection('badge').doc('count').set({'number': 0});

Demo:https://drive.google.com/file/d/1UIP9BPiy-gQnk6I6rEzeporZaOwkPKTk/view?usp=sharing

Related