DEV Community

Cover image for Implementing Firebase Background Notifications in Flutter 👌
Abhinav Kumar
Abhinav Kumar

Posted on

Implementing Firebase Background Notifications in Flutter 👌

Enabling Background Notifications in Your Flutter App with Firebase Cloud Messaging (FCM)

This guide walks you through implementing background notifications in your Flutter application using Firebase Cloud Messaging (FCM). FCM is a powerful service that allows you to send targeted and engaging notifications to your app users, even when the app is in the background or closed.

Prerequisites:

Step-by-Step Guide:

  • Firebase Project Setup and Login:

    • In the Firebase console, create a new project or select an existing one.
    • Navigate to Project settings -> Your apps..
  • Activate FlutterFire CLI:

    • Install the FlutterFire CLI globally using the command: bash dart pub global activate flutterfire_cli
  • Configure FlutterFire:

    • In your project's root directory, run: bash flutterfire configure
    • Select your Firebase project and choose the app(s) you want to enable notifications for.
  • Add Required Packages:

    • In your pubspec.yaml file, add the following dependencies: yaml dependencies: firebase_core: firebase_messaging:
    • Run flutter pub get to install the packages.
  • Create Firebase Utilities Class (firebase_utils.dart):

   import 'package:firebase_messaging/firebase_messaging.dart';
   import 'package:logger/logger.dart'; // Consider using a logging library for debugging

   class FirebaseUtil {
     final _firebaseMessaging = FirebaseMessaging.instance;
     final Logger logger = Logger(); // Optional: For logging

     Future<void> handleBackgroundMessage(RemoteMessage message) async {
       logger.d(message.notification?.title ?? "No title available");
       logger.d(message.notification?.body ?? "No body available");
       logger.d(message.data);
       // Process the notification data here (e.g., display a local notification)
     }

     Future<void> initNotification() async {
       // Request notification permissions
       await _firebaseMessaging.requestPermission();

       // Get the FCM token for identification
       final fCMToken = await _firebaseMessaging.getToken();
       logger.d(fCMToken);

       // Listen for background messages
       FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
     }
   }
Enter fullscreen mode Exit fullscreen mode
  • Initialize Notifications in main.dart:
   import 'package:firebase_core/firebase_core.dart';
   import 'package:flutter/material.dart';
   import 'package:flutter_notification_test/firebase_options.dart'; // Replace with your project's path
   import 'package:flutter_notification_test/firebase_utils.dart';

   void main() async {
     WidgetsFlutterBinding.ensureInitialized();
     await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

     // Initialize notification handling
     await FirebaseUtil().initNotification();

     runApp(const MyApp());
   }

   class MyApp extends StatelessWidget {
     const MyApp({super.key});

     @override
     Widget build(BuildContext context) {
       return const MaterialApp(
         home: Scaffold(
           body: Center(
             child: Text("Background Notification Test"),
           ),
         ),
       );
     }
   }
Enter fullscreen mode Exit fullscreen mode

Testing Notifications in Firebase Console:

  1. Go to the Engage > Messaging section in your Firebase project.
  2. Click Send test message.
  3. Enter a title, body, and optionally, data for your notification.
  4. Paste the FCM token you obtained earlier (from FirebaseUtil.initNotification) into the Device token field. This token uniquely identifies your app instance.
  5. Click Test.

Test Notification

Explanation:

  • The code creates a FirebaseUtil class to handle notification initialization and background message processing.
  • handleBackgroundMessage is called when a notification is received in the background. You can customize this function to display a local notification or perform other actions.
  • initNotification requests notification permissions, retrieves the FCM

Top comments (0)