Setting Up Push Notifications in a Flutter Project

Overview

Push notifications allow you to send updates and messages to your app users even when the app is not actively in use. This guide will walk you through the process of setting up push notifications for your Flutter project using Firebase Cloud Messaging (FCM).


Prerequisites

  • A Google Cloud account.
  • Firebase project setup.
  • Flutter installed and set up on your machine.
  • Your Flutter project is created and ready.

1. Set Up Firebase

  1. Create a Firebase Project

    • Go to the Firebase Console.
    • Click on Add Project and follow the setup steps. Name your project and accept the terms.
  2. Add Firebase to Your App

    • For Android:
      • In the Firebase Console, select Add Firebase to your Android app.
      • Register your app with the package name you used in your Flutter project.
      • Download the google-services.json file and place it in the android/app directory of your Flutter project.
    • For iOS:
      • In the Firebase Console, select Add Firebase to your iOS app.
      • Register your app with the iOS bundle ID.
      • Download the GoogleService-Info.plist file and add it to your Xcode project by dragging it into the ios/Runner directory in Xcode.
  3. Configure Firebase Cloud Messaging

    • Enable Cloud Messaging in the Firebase Console:
      • Go to Project Settings -> Cloud Messaging.
      • Ensure that your project has a server key and sender ID.

2. Add Firebase Dependencies

  1. For Android

    • Open android/build.gradle and add the Google services classpath to the dependencies block:
      buildscript {
      dependencies {
       // Add this line
       classpath 'com.google.gms:google-services:4.3.15'
      }
      }
    • Open android/app/build.gradle and apply the Google services plugin at the bottom of the file:
      apply plugin: 'com.google.gms.google-services'
    • Add the Firebase Messaging dependency to the dependencies block:
      dependencies {
      implementation 'com.google.firebase:firebase-messaging:23.1.0'
      }
  2. For iOS

    • Open ios/Podfile and ensure you have the following line:
      pod 'Firebase/Messaging'
    • Run pod install in the ios directory to install the Firebase SDK:
      cd ios
      pod install

3. Configure Firebase Messaging in Your Flutter App

  1. Add Dependencies

    • Open pubspec.yaml and add the firebase_core and firebase_messaging dependencies:
      dependencies:
      flutter:
       sdk: flutter
      firebase_core: ^2.12.0
      firebase_messaging: ^14.0.0
    • Run flutter pub get to install the new dependencies.
  2. Initialize Firebase

    • Open lib/main.dart and initialize Firebase:

      import 'package:firebase_core/firebase_core.dart';
      import 'package:flutter/material.dart';
      
      void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
      }
  3. Set Up Firebase Messaging

    • Create a new file lib/firebase_messaging_service.dart and configure Firebase Messaging:

      import 'package:firebase_messaging/firebase_messaging.dart';
      
      class FirebaseMessagingService {
      final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
      
      FirebaseMessagingService() {
       _firebaseMessaging.getInitialMessage().then((RemoteMessage? message) {
         if (message != null) {
           // Handle notification tap when app is launched from terminated state
         }
       });
      
       FirebaseMessaging.onMessage.listen((RemoteMessage message) {
         // Handle foreground message
       });
      
       FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
         // Handle notification tap when app is in background
       });
      }
      }
  4. Handle Notifications

    • In lib/main.dart, set up notification handling:

      import 'firebase_messaging_service.dart';
      
      class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
       FirebaseMessagingService();
       return MaterialApp(
         home: Scaffold(
           appBar: AppBar(
             title: Text('Push Notifications Example'),
           ),
           body: Center(child: Text('Hello World')),
         ),
       );
      }
      }

4. Testing Push Notifications

  1. Send a Test Notification from Firebase Console

    • Go to the Firebase Console.
    • Navigate to Cloud Messaging.
    • Click on Send your first message.
    • Fill out the notification details and send it to your app.
  2. Verify Notification Reception

    • Run your Flutter app on an emulator or physical device.
    • Ensure that the notification appears as expected.

Summary

You have successfully integrated Firebase Cloud Messaging into your Flutter project. By following these steps, you’ve set up the necessary configurations for sending and receiving push notifications on both Android and iOS platforms.

For more detailed information, refer to the Firebase Cloud Messaging documentation and the FlutterFire documentation.