Paramclasses Academy - Blog

Tutorials Details

←
Post 30 of 40
→

How to Add Push Notifications to Flutter Apps

How to Add Push Notifications to Flutter Apps

November 3, 2026

❖ Welcome to Param Classes!

Have you ever received a notification from WhatsApp, Instagram, a shopping application or a banking app? These messages are called push notifications. They allow mobile applications to send important updates directly to users, even when the application is not currently open.

For example, an e-commerce application can notify users about order updates. A school management application can send announcements to parents. A news application can send alerts about breaking news.

Flutter supports push notifications through Firebase Cloud Messaging (FCM). In this tutorial, you will learn how to configure Firebase, connect it to a Flutter application, request notification permission, receive notifications and display notification messages.

Let's build a basic push notification system step by step.

✦ 1. What Are Push Notifications?

Push notifications are messages sent from a server to a mobile device through a notification service.

A typical notification system works like this:

  1. A user installs your Flutter application.

  2. The application connects to Firebase Cloud Messaging.

  3. Firebase generates an FCM registration token for the device.

  4. Your application sends this token to your backend server.

  5. Your backend sends a notification request through Firebase.

  6. Firebase delivers the notification to the user's device.

Example: A school sends an announcement to its students. The backend sends a notification request to Firebase, and Firebase delivers the message to the registered devices.

✦ 2. Understanding Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a service that allows developers to send messages and notifications to Android, iOS and web applications.

Some important features include:

  • Send notifications to individual devices.

  • Send notifications to multiple devices.

  • Send notifications to subscribed topics.

  • Deliver order and payment updates.

  • Send promotional announcements.

  • Receive data messages for custom application logic.

Official documentation:

https://firebase.google.com/docs/cloud-messaging

✦ 3. Create a Flutter Project

First, create a new Flutter project.

Open the terminal and run:

flutter create flutter_notification_app

Move into the project:

cd flutter_notification_app

Open it in Android Studio or VS Code.

✦ 4. Create a Firebase Project

Now connect your Flutter application to Firebase.

Follow these steps:

  1. Open https://console.firebase.google.com/

  2. Sign in with your Google account.

  3. Click Create a project.

  4. Enter a project name, such as FlutterNotificationApp.

  5. Complete the project creation process.

  6. Open the newly created Firebase project.

  7. Add an Android application.

You will need your Android application ID. You can find it in the Android app's Gradle configuration.

For example:

com.example.flutter_notification_app

Enter the correct application ID while registering your Android app in Firebase.

Important: The Android application ID must match the application ID configured in your Flutter project's Android build settings.

✦ 5. Configure Firebase in Flutter

The recommended approach is to use the Firebase CLI and FlutterFire CLI.

First, install the Firebase CLI by following the official instructions:

https://firebase.google.com/docs/cli

Log in:

firebase login

Install FlutterFire CLI:

dart pub global activate flutterfire_cli

Configure Firebase from your Flutter project directory:

flutterfire configure

Select your Firebase project and Android platform.

This command generates a Firebase configuration file, commonly named:

lib/firebase_options.dart

Now add the required packages:

flutter pub add firebase_core
flutter pub add firebase_messaging

Then run:

flutter pub get

✦ 6. Initialize Firebase in main.dart

Open lib/main.dart and initialize Firebase before running your application.

Use this code:

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

import 'firebase_options.dart';

@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(
  RemoteMessage message,
) async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  debugPrint('Background message: ${message.messageId}');
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FirebaseMessaging.onBackgroundMessage(
    firebaseMessagingBackgroundHandler,
  );

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Notifications',
      home: const NotificationHome(),
    );
  }
}

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

  @override
  State<NotificationHome> createState() =>
      _NotificationHomeState();
}

class _NotificationHomeState extends State<NotificationHome> {
  String token = 'Loading token...';
  String notificationMessage = 'No notification received yet';

  @override
  void initState() {
    super.initState();
    setupNotifications();
  }

  Future<void> setupNotifications() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    NotificationSettings settings =
        await messaging.requestPermission();

    debugPrint(
      'Permission status: ${settings.authorizationStatus}',
    );

    String? fcmToken = await messaging.getToken();

    if (!mounted) return;

    setState(() {
      token = fcmToken ?? 'Token unavailable';
    });

    // Receive messages while app is open.
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      final title = message.notification?.title ?? 'Notification';
      final body = message.notification?.body ?? '';

      if (!mounted) return;

      setState(() {
        notificationMessage = '$title: $body';
      });
    });

    // Handle notification tap when app is in background.
    FirebaseMessaging.onMessageOpenedApp.listen(
      (RemoteMessage message) {
        final title =
            message.notification?.title ?? 'Notification opened';

        if (!mounted) return;

        setState(() {
          notificationMessage = 'Opened: $title';
        });
      },
    );

    // Handle notification tap that launched the app.
    RemoteMessage? initialMessage =
        await messaging.getInitialMessage();

    if (initialMessage != null && mounted) {
      setState(() {
        notificationMessage =
            'Opened: ${initialMessage.notification?.title ?? 'Notification'}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Push Notifications'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),

      body: Padding(
        padding: const EdgeInsets.all(20),

        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Firebase FCM Token:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 18,
              ),
            ),

            const SizedBox(height: 10),

            SelectableText(token),

            const SizedBox(height: 30),

            const Text(
              'Notification Message:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 18,
              ),
            ),

            const SizedBox(height: 10),

            Text(notificationMessage),
          ],
        ),
      ),
    );
  }
}

This example initializes Firebase, requests notification permission, obtains the device's FCM token and listens for incoming messages.

It also handles notification taps when the app is in the background or opened through a notification.

✦ 7. Understand the FCM Token

An FCM token identifies a particular app installation for Firebase Cloud Messaging.

Example:

eXampleFCMToken123456789

Your application can retrieve the token using:

String? token =
    await FirebaseMessaging.instance.getToken();

debugPrint(token);

In a real application, send this token to your backend API and associate it with the logged-in user.

Remember that tokens can change. Your application should listen for token updates:

FirebaseMessaging.instance.onTokenRefresh.listen(
  (newToken) {
    debugPrint('Updated FCM Token: $newToken');

    // Send the updated token to your backend API.
  },
);

Never assume that a device token will remain unchanged forever.

✦ 8. Send a Test Notification from Firebase

After configuring your application:

  1. Run your Flutter app on an Android device.

  2. Accept notification permission when requested.

  3. Open Firebase Console.

  4. Select your project.

  5. Open Messaging or Firebase Cloud Messaging.

  6. Create a notification campaign.

  7. Enter a notification title and message.

  8. Select your registered Android application as the target.

  9. Send the test notification using the available test-device/token option, if provided.

Use a second device or background the app when testing notification delivery.

Important: Foreground notification messages are received by FirebaseMessaging.onMessage. The basic example above updates the app screen but does not automatically show a system notification while the app is open. For a visible foreground notification, you can integrate a local notification package such as flutter_local_notifications.

✦ 9. Send Push Notifications from a Backend

In a real application, notifications are usually sent by a trusted backend server.

For example, when a school publishes a new announcement, its PHP backend can send an FCM message to the relevant devices.

The recommended approach is to use Firebase Admin SDK or the Firebase Cloud Messaging HTTP v1 API.

Your backend should:

  1. Authenticate securely with Google service credentials.

  2. Obtain an authorized access token.

  3. Prepare an FCM message containing the device token and notification details.

  4. Send the request to the FCM HTTP v1 endpoint.

  5. Handle the response and any invalid or expired tokens.

Official documentation:

https://firebase.google.com/docs/cloud-messaging/send/v1-api

Security Warning: Never put Firebase service account credentials, private keys or server authentication secrets inside your Flutter application. Keep them on your trusted backend server.

✦ 10. Common Push Notification Errors

1. Firebase Not Initialized

Make sure Firebase is initialized before calling Firebase Messaging methods.

2. Notification Permission Denied

The user may have denied notification permission. Check the permission status and explain how to enable notifications in device settings.

3. FCM Token Not Generated

Check your Firebase configuration, internet connection and Firebase project setup.

4. Notification Not Received

Check the device token, notification permission, Firebase project and message delivery response.

5. Background Notification Not Working

Make sure the background handler is registered before runApp() and follows Firebase's background execution requirements.

✦ 11. Best Practices for Push Notifications

  • Ask users for notification permission at an appropriate time.

  • Send useful and relevant notifications.

  • Avoid sending too many notifications.

  • Keep notification titles and messages short.

  • Store FCM tokens securely on your backend.

  • Update tokens when they change.

  • Remove invalid tokens when Firebase reports them.

  • Never expose server credentials in application code.

  • Test notifications on real Android devices.

  • Provide notification preferences inside your application.

✦ 12. What You Learned

In this tutorial, you learned:

  • What push notifications are.

  • How Firebase Cloud Messaging works.

  • How to create a Firebase project.

  • How to configure Firebase in Flutter.

  • How to initialize Firebase.

  • How to request notification permission.

  • How to generate an FCM token.

  • How to receive foreground and background messages.

  • How to handle notification taps.

  • How to send notifications through a trusted backend.

❖ Conclusion

Push notifications help mobile applications communicate with users and provide important updates. With Firebase Cloud Messaging, Flutter developers can build notification features for school applications, shopping applications, booking systems and many other projects.

At Param Classes, we focus on practical programming lessons that help beginners understand real-world application development. Try integrating push notifications into your own Flutter project and experiment with different notification messages.

Learn Today, Grow Tomorrow – Param Classes.

←
Post 30 of 40
→