Setting Up Notifications Using Firebase in Flutter

Firebase Cloud Messaging (FCM) is a robust solution to integrate push notifications into your Flutter app. This article will walk you through the process of setting up FCM from start to finish.


1. Setting Up Firebase and FlutterFire CLI

Step 1: Add Firebase to Your Flutter Project

  1. Ensure Flutter is installed and updated:

     flutter doctor
    
  2. Create a Firebase project:

  3. Link Firebase to Flutter:

    • Install FlutterFire CLI:

        dart pub global activate flutterfire_cli
      
    • Configure your project:

        flutterfire configure
      

Step 2: Add Firebase SDK

Add Firebase packages to your pubspec.yaml file:

dependencies:
  firebase_core: ^2.16.0
  firebase_messaging: ^14.5.0

Run:

flutter pub get

2. Configuring Firebase Messaging

Step 1: Configure Firebase for Android

  1. In Firebase Console:

    • Add your app's package ID (e.g., com.example.app).

    • Download the google-services.json file and place it in the android/app directory.

  2. Update the android/build.gradle file:

     dependencies {
         classpath 'com.google.gms:google-services:4.3.15'
     }
    
  3. Update the android/app/build.gradle file:

     apply plugin: 'com.google.gms.google-services'
    

Step 2: Configure Firebase for iOS

  1. In Firebase Console:

    • Download the GoogleService-Info.plist file and place it in the ios/Runner directory.
  2. Edit ios/Runner/Info.plist and add:

     <key>FirebaseAppDelegateProxyEnabled</key>
     <false/>
    
  3. Run:

     cd ios
     pod install
    

3. Integrating Firebase Messaging in Flutter

Step 1: Initialize Firebase

Update your main.dart file:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Messaging',
      home: const HomeScreen(),
    );
  }
}

Step 2: Retrieve the FCM Token

Add logic to your home_screen.dart file:

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    _initFirebaseMessaging();
  }

  void _initFirebaseMessaging() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    // Retrieve FCM Token
    String? token = await messaging.getToken();
    print("FCM Token: $token");

    // Listen for messages
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print("Notification received: ${message.notification?.title}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('FCM Example')),
      body: const Center(child: Text('Welcome to Firebase Messaging!')),
    );
  }
}

4. Sending Notifications via Firebase Console

  1. Open Firebase Console > Messaging.

  2. Create a new notification:

    • Enter the title and body content.

    • Select the target audience.

    • Send the notification and verify it in your app.


5. Configuring App Store Connect for iOS

Step 1: Register an APNs Key in Apple Developer

  1. Visit Apple Developer.

  2. In Certificates, Identifiers & Profiles, select Keys.

  3. Create a new APNs Key:

    • Name the key.

    • Download the .p8 file and store it securely.

  4. Note the Key ID and Team ID for Firebase configuration.

Step 2: Update APNs Key in Firebase Console

  1. Go to Firebase Console > Project Settings > Cloud Messaging.

  2. Under iOS app configuration, upload the .p8 file:

    • Enter the Key ID and Team ID.

    • Save the changes.

Step 3: Configure App Store Connect

  1. Visit App Store Connect.

  2. In Certificates, Identifiers & Profiles:

    • Ensure the App ID has Push Notifications enabled.

    • Create and associate the appropriate provisioning profile with your app.

  3. Download the profile and integrate it into your Xcode project.


Conclusion

Setting up notifications using Firebase in Flutter enhances user engagement and interaction. With detailed steps covering Firebase setup, app configuration, and App Store Connect, this guide aims to help you successfully implement FCM in your Flutter application.