How to turn off notification with button in flutter

Viewed 2451

I want to enable or disable the notification service with help of a button when this button is enabled, the user receives the notification, and when it's disabled he won't receive any notifications.

    import 'dart:io';
    
    import 'package:firebase_messaging/firebase_messaging.dart';
    
    class FirebaseNotifications {
      FirebaseMessaging _firebaseMessaging;
    
      void setUpFirebase() {
        _firebaseMessaging = FirebaseMessaging();
        firebaseCloudMessaging_Listeners();
    
      }
    
      void firebaseCloudMessaging_Listeners() {
        if (Platform.isIOS) iOS_Permission();
    
        _firebaseMessaging.getToken().then((token) {
          print(token);
        });
    
        _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
            print('on message $message');
          },
          onResume: (Map<String, dynamic> message) async {
            print('on resume $message');
          },
          onLaunch: (Map<String, dynamic> message) async {
            print('on launch $message');
          },
        );
      }
    
      void iOS_Permission() {
        _firebaseMessaging.requestNotificationPermissions(
            IosNotificationSettings(sound: true, badge: true, alert: true));
        _firebaseMessaging.onIosSettingsRegistered
            .listen((IosNotificationSettings settings) {
          print("Settings registered: $settings");
        });
      }
    }

Reference image

1 Answers

Aside from setting up a Cloud Function to enable/disable FCM notifications, you can also do this by (un)subscribing from topics.

Have the app subscribe to the topic when you'd like it to receive notifications. The message should also be sent to the topic for the devices to receive the notification.

FirebaseMessaging.instance.subscribeToTopic('topic');

Unsubscribing from the topic, the device won't receive the notifications sent.

FirebaseMessaging.instance.unsubscribeFromTopic('topic');
Related