Push Notifications in Flutter with Firebase Cloud Messaging (FCM): A Comprehensive Guide

Push notifications are an essential feature in modern applications to keep users informed and engaged. In Flutter, Firebase Cloud Messaging (FCM) provides a robust and scalable solution for implementing push notifications. FCM allows you to send notifications across various platforms such as Android, iOS, and web, making it a go-to choice for Flutter developers.

This guide will walk you through the process of integrating push notifications in a Flutter application using Firebase Cloud Messaging, from setup to implementation.

Push Notifications in Flutter

What Are Push Notifications?

Push notifications are messages sent by an app to a user’s device, even when the app is not actively running. These notifications are typically used to:

With FCM, you can send push notifications to users reliably and efficiently.

Why Use Firebase Cloud Messaging (FCM) in Flutter?

Firebase Cloud Messaging offers several advantages:

  1. Cross-Platform Support: Send notifications to Android, iOS, and web.
  2. Scalability: Handle millions of users without compromising performance.
  3. Rich Features: Support for message scheduling, topics, and rich media notifications.
  4. Free Tier: FCM provides generous free-tier usage.

Steps to Integrate Push Notifications in Flutter Using FCM

Step 1: Create a Firebase Project

  1. Go to the Firebase Console.
  2. Click on Add Project and follow the prompts to create a new project.
  3. Enable Google Analytics for the project if needed.

Step 2: Add Your Flutter App to the Firebase Project

  1. Register the App:
    • For Android:
      • Go to the Project Settings in Firebase and click Add App.
      • Select Android, and provide the package name (found in android/app/src/main/AndroidManifest.xml).
    • For iOS:
      • Select iOS and provide the bundle identifier (found in ios/Runner.xcodeproj).
  2. Download the Configuration Files:
    • For Android: Download the google-services.json file and place it in the android/app directory.
    • For iOS: Download the GoogleService-Info.plist file and place it in the ios/Runner directory.
  3. Add Firebase SDK:
    • Update the android/build.gradle and android/app/build.gradle files to include the Firebase dependencies.
    • For iOS, ensure the dependencies are added in the Podfile.

Step 3: Add Firebase Messaging to Your Flutter Project

  1. Add the firebase_messaging package to your pubspec.yaml:
dependencies:  
  firebase_core: ^2.5.0  
  firebase_messaging: ^14.0.0  

2. Run flutter pub get to install the dependencies.

3. Initialize Firebase in your project by modifying the main.dart file:

import 'package:flutter/material.dart';  
import 'package:firebase_core/firebase_core.dart';  
import 'firebase_options.dart'; // This file is generated when initializing Firebase

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

class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: Scaffold(  
        appBar: AppBar(title: Text('Push Notifications')),  
        body: Center(child: Text('Welcome to Push Notifications in Flutter!')),  
      ),  
    );  
  }  
}  

Step 4: Configure FCM

  1. Request Permissions (For iOS): On iOS, you need to request user permissions to show notifications. Add the following code to your Flutter app:
import 'package:firebase_messaging/firebase_messaging.dart';  

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

  NotificationSettings settings = await messaging.requestPermission(  
    alert: true,  
    announcement: false,  
    badge: true,  
    carPlay: false,  
    criticalAlert: false,  
    provisional: false,  
    sound: true,  
  );  

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {  
    print('User granted permission');  
  } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {  
    print('User granted provisional permission');  
  } else {  
    print('User denied permission');  
  }  
}  

2. Background Message Handling: Set up a background message handler to handle incoming notifications when the app is not active:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {  
  print('Handling a background message: ${message.messageId}');  
}  

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);  

3. Foreground Notifications: Handle notifications when the app is in the foreground:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {  
  print('Message received: ${message.notification?.title}');  
});  

Step 5: Test Push Notifications

  1. Obtain the Firebase Server Key from the Firebase Console under Project Settings > Cloud Messaging.
  2. Use tools like Postman or cURL to send test notifications:Example cURL command:
 curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" \  
-d '{
  "to": "DEVICE_TOKEN",
  "notification": {
    "title": "Hello!",
    "body": "This is a test notification."
  }
}' https://fcm.googleapis.com/fcm/send  

3. Replace DEVICE_TOKEN with the token retrieved from your app using:

FirebaseMessaging.instance.getToken().then((token) => print('Device Token: $token'));  

Common Issues and Troubleshooting

  1. Notification Not Displaying on iOS:
    Ensure that Push Notifications and Background Modes are enabled in the Xcode project.
  2. Missing Permissions:
    For Android, verify that the AndroidManifest.xml contains the necessary permissions:
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

3. Token Generation Issues:
Check Firebase project settings and ensure proper configuration of google-services.json and GoogleService-Info.plist.

    Conclusion

    Firebase Cloud Messaging (FCM) makes it simple to implement push notifications in Flutter applications. With its cross-platform support, efficient delivery, and advanced features, FCM is an excellent choice for enhancing user engagement. By following this guide, you can seamlessly integrate push notifications into your Flutter project and start reaching users with real-time updates and alerts.

    Explore Other Flutter Topics…

    1. Introduction to Flutter and Dart
    2. Why choose Flutter
    3. Installing Flutter On Your Windows Mac And Linux System
    4. Your first Flutter app
    5. Flutter project structure
    6. Building blocks of Flutter
    7. Stateful vs. Stateless Widgets Explained
    8. Flutter layout system
    9. Flutter text widget
    10. Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
    11. Handling User Input with Flutter Forms
    12. Container class in Flutter
    13. Flutter Navigation
    14. Flutter – Pass Data One Screen To Another Screen
    15. Managing Device Orientation in Flutter
    16. Stateful widget lifecycle in Flutter
    17. Future of Flutter
    18. Flutter Themes
    19. Flutter Animations
    20. Flutter AppBar Customization
    21. ListView in Flutter
    22. Flutter GridView
    23. Flutter Expanded Widget
    24. Flutter BottomNavigation Bar
    25. Floating Action Button
    26. Drawer Widgets in Flutter
    27. Form Validation in Flutter
    28. Flutter TextField
    29. Adding AdMob ads to a Flutter app
    30. Building Flutter Web & Desktop Applications
    31. What is Async and Await in Flutter
    32. HTTP requests in Flutter
    33. Parsing JSON in Flutter
    34. Tinder-Style Swipe Cards in Flutter
    35. Flutter Tic Tac Toe Game Tutorial
    36. Flutter Login UI Tutorial
    37. Flutter Card Widget Tutorial
    38. Flutter music player app tutorial
    39. Flutter introduction screens
    40. Shared Preferences in Flutter
    41. SQLite Database in Flutter
    42. Firebase Authentication in Flutter
    43. Firebase Firestore in Flutter
    44. Push Notifications in Flutter
    45. Handling File Uploads in Flutter
    46. Responsive Design in Flutter
    47. Provider in Flutter
    48. Riverpod in Flutter
    49. Flutter BLoC Pattern Tutorial

    Leave a Reply

    Your email address will not be published. Required fields are marked *