Flutter firebase messaging background

To handle Firebase Cloud Messaging (FCM) in the background in a Flutter app, you need to follow these steps:

  1. Add the necessary dependencies to your Flutter project by adding the following lines to your pubspec.yaml file:

    dependencies:
      firebase_core: ^1.6.0
      firebase_messaging: ^10.0.0
      flutter_local_notifications: ^12.0.0
                
  2. Configure Firebase Messaging by adding the necessary code in your Flutter project’s main.dart file.

    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_messaging/firebase_messaging.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
    
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    
      runApp(MyApp());
    }
    
    Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      // Handle FCM message in the background
      // You can perform any necessary tasks here such as showing notifications, executing background tasks, etc.
      print("Handling a background message: ${message.messageId}");
    }
                
  3. Request the necessary permissions and handle the FCM messages in your app’s Dart code.

    import 'package:firebase_messaging/firebase_messaging.dart';
    
    class FirebaseMessagingService {
      FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
    
      Future setupFirebaseMessaging() async {
        // Request permission to receive notifications
        NotificationSettings settings = await _firebaseMessaging.requestPermission(
          alert: true,
          badge: true,
          sound: true,
        );
    
        if (settings.authorizationStatus == AuthorizationStatus.authorized) {
          // User granted permission
          String? token = await _firebaseMessaging.getToken();
          print("FirebaseMessaging token: $token");
    
          FirebaseMessaging.onMessage.listen((RemoteMessage message) {
            // Handle foreground FCM messages here
            print("Handling a foreground message: ${message.messageId}");
            // You can choose to show a notification or perform any necessary tasks
          });
        }
      }
    }
                
  4. Handle the FCM messages in the background using platform-specific code (Android and iOS).

    For Android:

    import 'package:flutter_local_notifications/flutter_local_notifications.dart';
    
    class MyFirebaseMessagingService extends FirebaseMessagingService {
      static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
      
      @override
      void onCreate() {
        super.onCreate();
    
        const AndroidInitializationSettings initializationSettingsAndroid =
            AndroidInitializationSettings('app_icon');
    
        final InitializationSettings initializationSettings =
            InitializationSettings(android: initializationSettingsAndroid);
    
        flutterLocalNotificationsPlugin.initialize(initializationSettings);
      }
    
      @override
      Future onMessageReceived(RemoteMessage message) async {
        super.onMessageReceived(message);
    
        // Handle background FCM messages here
        print('Handling a background message: ${message.messageId}');
        // You can choose to show a notification or perform any necessary tasks using flutterLocalNotificationsPlugin
      }
    } 
                

    For iOS:

    import 'package:firebase_messaging/firebase_messaging.dart';
    
    class MyFirebaseMessagingDelegate extends NSObject
        with UNUserNotificationCenterDelegate, MessagingDelegate {
    
      static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
    
      Future setupFirebaseMessaging() async {
        FirebaseMessaging.instance.setDelegate(MyFirebaseMessagingDelegate());
        const IOSInitializationSettings initializationSettingsIOS =
            IOSInitializationSettings();
    
        final InitializationSettings initializationSettings =
            InitializationSettings(iOS: initializationSettingsIOS);
    
        flutterLocalNotificationsPlugin.initialize(initializationSettings);
      }
    
      @override
      void didReceiveRemoteNotification(
        Map userInfo,
        int? badge,
      ) {
        // Handle background FCM messages here
        print('Handling a background message');
    
        // You can choose to show a notification or perform any necessary tasks using flutterLocalNotificationsPlugin
      }
    }
                

With the above setup, your Flutter app will be able to handle FCM messages in the background. You can customize the handling of messages based on your requirements, such as showing notifications, executing background tasks, etc.

Leave a comment