In flutter how to clear notification in bar?
Solution 1
It thinks there is no way to do this in documentation.
But you can try this. You can just go to your MainActivity.java in your Android folder, and do something like this.
import android.app.NotificationManager;
import android.content.Context;
Import these packages.
@Override
protected void onResume() {
super.onResume();
// Removing All Notifications
closeAllNotifications();
}
private void closeAllNotifications() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
Add an onResume
function below onCreate
on MainActivity.java.
Hope this solves your issue.
Solution 2
Shri Hari solution did the trick. Kotlin:
import android.app.NotificationManager
import android.content.Context
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun onResume() {
super.onResume()
closeAllNotifications();
}
private fun closeAllNotifications() {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll()
}
}
And For IOS I use UNUserNotificationCenter:
import UIKit
import Flutter
import UserNotifications
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
application.applicationIconBadgeNumber = 0 // For Clear Badge Counts
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Solution 3
In case you don't want to modify your swift or java code you can use flutter_local_notifications
which offers a method cancelAll()
.
class SomeWidget extends State<SomeState> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed) {
await flutterLocalNotificationsPlugin
.cancelAll();
}
}
}
puzzled
Updated on December 04, 2022Comments
-
puzzled over 1 year
I am learning Google cloud messaging and firebase messaging is working fine, but when a user do not click at the notification to open the app and instead goes directly to app by manually opening it and bringing to foreground, the notification stays. I want those notification message related to my app go away when the app comes to foreground. How can I achieve this ?
-
Jasmin Sojitra about 3 yearsHow to do this in flutter 2.0? Can you please help me?
-
K.Amanov almost 3 years@JasminSojitra I guess it works on Flutter 2.*
-
Ali Solanki almost 3 yearsThis worked for me in Flutter 2.0 as well