Engagement Evolution: Implementing Push Notifications in Flutter

Back to Blogs

Introduction

In the fast-paced world of mobile app development, user engagement is paramount. One of the most effective tools for keeping users informed and engaged is through notifications. Flutter offers support for both local and push notifications.

We'll explore everything you need to know about implementing and managing notifications in your Flutter app.  We'll start by understanding the key differences between local and push notifications.

Push Notification

Push notifications including the server-side infrastructure needed to send notifications and the client-side code required to receive and handle them in your Flutter app. we'll guide you through the process of setting up Firebase Cloud Messaging (FCM), Google's free messaging platform, which provides an easy way to send push notifications to Android and iOS devices.

Setup Firebase

Step 1. Open Firebase base console https://console.firebase.google.com/,
             Select Project if not project not available then create a new project.

Step 2. Install and run the FlutterFire CLI.
             From any directory, run this command:
             $ dart pub global activate flutterfire_cli

             Then, at the root of your Flutter project directory, run this command:
             $ flutterfire configure – “project-id”
             This will automatically register your pre-platform apps with firebase and adds a lib/firebase_options.dart configure file to your flutter project

Step 3. To initialize Firebase, call Firebase.initializeApp from the firebase_core package with the configuration from your new firebase_options.dart file:

await Firebase.initializeApp(

    options: DefaultFirebaseOptions.currentPlatform,

);

IOS Step

Before your application can start to receive messages, you must enable push notifications and background modes in your Xcode project.

  1. Open your Xcode project workspace (ios/Runner.xcworkspace).
  2. Enable push notifications.
  3. Enable the Background fetch and the Remote notifications background execution modes.
  4. Upload Your APNs authentication key.

Before you use FCM, upload your APNs certificate to Firebase. If you don’t have a APNs certificate, create one in Apple Developer Member center.

  • Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
  • Select the Upload Certificate button for your development certificate, your production certificate, or both. At least one is required.
  • For each certificate, select the. p12 file, and provide the password, if any. Make sure the bundle ID for this certificate matches the bundle ID of your app. Select Save.

 

Implementation

Install FCM Plugin

From the root of your Flutter project, run the following command to install the plugin:

$ flutter pub add firebase_messaging


Get Notification permission

void getpermission(){

Permission.notification.request();
}

 

Access the registration token

To retrieve the current registration token for an app instance, call getToken(). If notification permission has not been granted, this method will ask the user for notification permissions.

final fcmToken = await FirebaseMessaging.instance.getToken();

Send a Test notification

Step 1. Install and run the app on the target device. On Apple devices, you'll need to accept the request for permission to receive remote notifications.

Step 2. Make sure the app is in the background on the device.

Step 3. In the Firebase console, open the Messaging page.

Step 4. If this is your first message, select Create your first campaign.

Select Firebase Notification messages and select Create.

Step 5. Otherwise, on the Campaigns tab, select New campaign and then Notifications.

Step 6. Enter the message text. All other fields are optional.

Step 7. Select Send test message from the right pane.

Step 8. In the field labeled Add an FCM registration token, enter the registration token you obtained in a previous section of this guide.

Step 9. Select Test.

After you select Test, the targeted client device (with the app in the background) should receive the notification.

You can also send the notification using POSTMAN

With the post-request

Url :- https://fcm.googleapis.com/fcm/send


Payload  = {
     “to”:”device token”,
       “notification”:{
             “title”:”test notification”,
             “body”:”Test Notificaion”
   },
“data”:{
  “type”:”notification” 
}
}

headers: {

  'Authorization': 'Bearer ' + accessToken

}

To get the accesstoken,

  1. Open the Firebase Project that you configure you flutter project.
  2. Navigate to project setting.
  3. Select cloud messaging
  4. Under Cloud Messaging API you will get your accesstoken.

 

Handling Notifications Interaction in Your Flutter App

When user tap a notification, then default behavior on both Android & IOS is to open the application. If the application is terminated, it will be started, and if it is in the background, it will be brought to the foreground.

Depending on the content of a notification, you may want to handle the user's interaction when the application opens. For example, if a new chat message is sent using a notification and the user selects it, you may want to open the specific conversation when the application opens.

The firebase-messaging package provider 2 ways to handle

1. getInitialMessage(): if the application is in terminated state then it will open the app and navigates to the screen containing in the notification.

2. onMessageOpenedApp: if the application is in background state then it will be brought to foreground and navigate to the screen containing in the notification.

  void _handleMessage(RemoteMessage message) {

    if (message.data['type'] == 'chat') {

      Navigator.pushNamed(context, '/chat',

        arguments: ChatArguments(message),

      );

    }

  }


  Future setupInteractedMessage() async {

    // Get any messages which caused the application to open from

    // a terminated state.

    RemoteMessage? initialMessage =

        await FirebaseMessaging.instance.getInitialMessage();

    // If the message also contains a data property with a "type" of "chat",

    // navigate to a chat screen

    if (initialMessage != null) {

      _handleMessage(initialMessage);

    }

    // Also handle any interaction when the app is in the background via a

    // Stream listener

    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);

  }


Call the setupInteractedMessage() function on the initial screen of the app.

 

- Tejas Chinni.

Other Articles