Flutter - How to remove iOS notification badge after opening app

Viewed 1627

When I send a notification from Firebase Cloud Messaging, the notification badge shows up on the app icon, but there is no code to remove it.

The count of notifications do not matter so I don't have to have any notification counter or whatever, so all I need to do is clear the notification badge when the app is opened.

How can I accomplish this without rewriting my entire code for notifications (I barely got it working)?

This is the code:

_fcm.getToken().then((token) {
  print("The token is: " + token);
  setState(() {
    tokenSave = token;
  });
});

_fcm.requestPermission(
  sound: true,
  badge: true,
  alert: true,
  provisional: false,
);

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  RemoteNotification notification = message.notification;
  AndroidNotification android = message.notification?.android;
  if (notification != null && android != null) {
    flutterLocalNotificationsPlugin.show(
      notification.hashCode,
      notification.title,
      notification.body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          channel.description,
          color: Colors.blue,
          playSound: true,
          icon: null,
        ),
      ),
    );
  }
});

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  print("onMessageOpenedApp event");
  RemoteNotification notification = message.notification;
  AndroidNotification android = message.notification?.android;
  if (notification != null && android != null) {
    showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            title: Text(notification.title),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [Text(notification.body)],
              ),
            ),
          );
        });
  }
});

}

2 Answers

I've had the same problem before. My workaround was using the App badger package

With that package you can do the following in your main.dart or any other entrypoint of your application:

FlutterAppBadger.removeBadge();

or

FlutterAppBadger.updateBadgeCount(0);

Add the following function to your AppDelegate.swift, under the application() function:

override func applicationDidBecomeActive(_ application: UIApplication) {
  application.applicationIconBadgeNumber = 0;
}
Related