Unlock the Power of Push Notifications in Your Flutter App

What Are Push Notifications?

Push notifications are clickable pop-up messages that appear on users’ devices, even when they’re not actively using your app. These notifications can inform users of status updates, message requests, reminders, alerts, and more.

Setting Up Firebase

To get started with Firebase Cloud Messaging (FCM), you need to create a new Firebase project. Follow these steps:

  1. Log in to your Google account and navigate to the Firebase console.
  2. Enter a project name and click Continue.
  3. Disable Google Analytics (you won’t need it for this project).
  4. Click Create project.

Integrating Firebase with Your Flutter App

Now that your Firebase project is ready, it’s time to integrate it with your mobile app. Since Flutter is a cross-platform framework, you’ll need to perform the initial Firebase setup for both Android and iOS platforms separately.

Android Setup

Follow these steps:

  1. Click the Android icon on the project overview page.
  2. Enter the Android package name and optionally, a nickname for your app.
  3. Enter the SHA-1 hash (you can generate it using the command keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android).
  4. Register your app and download the google-services.json file.
  5. Follow the instructions to add the code snippets to your project.

iOS Setup

Follow these steps:

  1. Click the Add app button on the project overview page and select iOS.
  2. Enter the iOS bundle ID and your app nickname.
  3. Register your app and download the GoogleService-Info.plist file.
  4. Open the ios folder of your project directory in Xcode and add the file.
  5. Follow the instructions to complete the setup.

Installing Flutter Plugins

You’ll need the following Flutter plugins for this project:

  • firebase_core
  • firebase_messaging
  • overlay_support

Add these packages to your pubspec.yaml file and install them.

Building a Flutter UI

Create a simple UI for your app with an AppBar and a Column to display the notification content:


import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Push Notifications Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Push Notifications Demo'),
        ),
        body: Column(
          children: [
            // Notification content will be displayed here
          ],
        ),
      ),
    );
  }
}

Adding Push Notification Functionality

Define a variable for FirebaseMessaging and create a method called registerNotification() to initialize the Firebase app, request notification access, and configure messaging to receive and display push notifications:


import 'package:firebase_messaging/firebase_messaging.dart';

Future _registerNotification() async {
  await Firebase.initializeApp();
  FirebaseMessaging.instance.requestPermission();
  FirebaseMessaging.onMessage.listen((message) {
    // Handle incoming notifications
  });
  FirebaseMessaging.onLaunch.listen((message) {
    // Handle notification tap while app is terminated
  });
  FirebaseMessaging.onResume.listen((message) {
    // Handle notification tap while app is in background
  });
}

Reacting to a Push Notification

Use the overlay_support plugin to show the notification on the UI. Wrap the MaterialApp widget with the OverlaySupport widget and use the showSimpleNotification() method to display the notification:


import 'package:overlay_support/overlay_support.dart';

Future _showNotification(RemoteMessage message) async {
  await showSimpleNotification(
    title: message.notification.title,
    subtitle: message.notification.body,
    background: Colors.blue,
  );
}

Handling Background Notifications

Define a top-level function called _firebaseMessagingBackgroundHandler() and pass it to the onBackgroundMessage() inside the registerNotification() method. This will handle background notifications and update the UI accordingly:


Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // Handle background notifications
}

Future _registerNotification() async {
  //...
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}

Sending Push Notifications

You can send notifications from the Firebase Cloud Messaging console directly. Enter a notification title, text, and name, and specify the target as either your Android or iOS app, or both.

By following these steps, you’ll have a solid understanding of how to integrate push notification functionality with a Flutter app using Firebase Cloud Messaging.

Leave a Reply