Flutter Push Notification using Firebase Cloud Messaging (FCM)

Praharsh Bhatt
Multiverse Software
4 min readFeb 9, 2020
Flutter Push Notification using Firebase Cloud Messaging (FCM)

This tutorial, we’re going to learn how to integrate push notification in your flutter apps.

For this, we’ll be using the firebase_messaging plugin.

Github Code: https://github.com/praharshbhatt/flutter-firebase-cloud-messaging

Installation

First of all, we need to create a new project or we can use the existing project. Open the pubspec.yaml and add the following dependency:

dependencies:
flutter:

sdk: flutter

firebase_messaging: ^6.0.9

Working on the Android side of things

Update Project level Gradle

Navigate to your android/app/src/build.gradle

Update your package name from defaultConfig to your applicationId

After updating the package name, we need to add google-service inside your apply plugin: 'com.google.gms.google-services'

Update App level Gradle

Open android/app/build.gradle & add classpath for google-service classpath 'com.google.gms:google-services:4.2.0'

Update App manifest

Open android/app/src/main/AndroidManifest.xml

<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

add the above lines inside <activity>

google-service.json

Now, download google-service.json file from firebase (mentioned in the next step) & paste android/app/ folder

Working with Firebase

  • Login to your firebase account & create a new project or choose an existing project
  • Navigate to Project Overview > Project Settings
  • Add your support Email then
  • scroll down then click Add Android App
  • Fill your package name, nickname and SHA-1 Key (Refer: https://developers.google.com/android/guides/client-auth)
  • Click Next & download google-service.json
  • Copy google-service.json & paste android/app/ as mentioned on previous steps

Awesome! We’ve completed the Android side of things!

Working on the iOS side of things

To integrate your plugin into the iOS part of your app, follow these steps:

  1. Generate the certificates required by Apple for receiving push notifications following this guide in the Firebase docs. You can skip the section titled “Create the Provisioning Profile”.
  2. Using the Firebase Console add an iOS app to your project: Follow the assistant, download the generated GoogleService-Info.plist file, open ios/Runner.xcworkspace with Xcode, and within Xcode place the file inside ios/Runner. Don't follow the steps named "Add Firebase SDK" and "Add initialization code" in the Firebase assistant.
  3. In Xcode, select Runner in the Project Navigator. In the Capabilities Tab turn on Push Notifications and Background Modes, and enable Background fetch and Remote notifications under Background Modes.
  4. Follow the steps in the “Upload your APNs certificate” section of the Firebase docs.
  5. Add the following lines to the (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method in the AppDelegate.m/AppDelegate.swift of your iOS project.

Objective-C:

if (@available(iOS 10.0, *)) {
[UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;
}

Swift:

if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

Awesome! We’ve now covered iOS too!

Let’s go ahead and cover the Flutter part now.

Working on the Flutter side of things

Now, we can write the code to receive a notification. Copy below code and paste it on your main.dart. I have explained code below.

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}

class _MyAppState extends State<MyApp> {
String _message = '';

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

_register() {
_firebaseMessaging.getToken().then((token) => print(token));
}

@override
void initState() {
// TODO: implement initState
super.initState();
getMessage();
}

void getMessage(){
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
setState(() => _message = message["notification"]["title"]);
}, onResume: (Map<String, dynamic> message) async {
print('on resume $message');
setState(() => _message = message["notification"]["title"]);
}, onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
setState(() => _message = message["notification"]["title"]);
});
}

@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Message: $_message"),
OutlineButton(
child: Text("Register My Device"),
onPressed: () {
_register();
},
),
// Text("Message: $message")
]),
),
),
);
}

Code Explanation

  • We created a stateful widget, because, we’re displaying messages dynamically whenever new messages arrive.
  • We have created an instance called _firebaseMessaging using FirebaseMessaging()
  • using _firebaseMessaging.getToken() we’re registering our app with firebase & Received token
  • _firebaseMessaging.configure() allows as to create some action based on the received message, such as onMessage, onResume, onLaunch
  • We simply use setState to display the current message on the screen

Sending Push Notification

If you want to send a push notification, we can use the firebase console to send a message. We also can use the terminal to testing purpose (CURL must be enabled)

  • To get server key, please navigate to firebase Project Overview -> Project Settings -> Cloud Messaging & copy server key
  • You can copy device token from your terminal
  • DATA=’{“notification”: {“body”: “this is a body”, “title”: “this is a title”}, “priority”: “high”, “data”: {“clickaction”: “FLUTTERNOTIFICATIONCLICK”, “id”: “1”, “status”: “done”}, “to”: “<CLIENT FCM TOKEN>”}’ curl https://fcm.googleapis.com/fcm/send -H “Content-Type:application/json” -X POST -d “$DATA” -H “Authorization: key=<SERVER KEY>”

Note: Please insert your own server key and FCM Token

--

--

Praharsh Bhatt
Multiverse Software

I'm not an entrepreneur, nor a CEO. I'm a nerdy programmer who likes to have opinions on Twitter.