Flutter Push Notification Integrations

Mohamed Essam
4 min readFeb 22, 2021

(Firebase With Local Notification Integration)

Installation

First of all, we need to create a new project or we can use the existing project we have to declare of dependencies inside pubspec.yaml

flutter create flutterfcm
cd flutterfcm

Then open your pubspec.yaml file, then add

dependencies:
flutter:
sdk: flutter firebase_messaging: ^7.0.3

Once, we have done with dependencies, we must edit our package name in order to work with firebase push notification

Working with the Android Project File

  • Working with android/app/src/build.gradle file
  • Navigate to your android/app/src/build.gradle
  • Update your package name from defaultConfig -> applicationId
  • After updating the package name, we need to add google-service inside your apply plugin: 'com.google.gms.google-services'
  • Working with android/build.gradle file
  • Open android/app/build.gradle & add classpath for google-service classpath 'com.google.gms:google-services:4.2.0'
  • Working with AndroidManifest.xml
  • 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 these lines inside <activity>

  • Copy & Paste your google-service.json file
  • Download google-service.json file from firebase (mentioned on 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

Working with Flutter Push Notification

Now, we have completed all of our configurations, we now can write code to receive 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 arrived.
  • 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": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "ccbTAyu9GTM: APA91bFb58HWa3d73BjS9oBk6pWkR1XpYiJiFXwBf-OGgu3QItVyPR-sZ1_WRhE2WaGW_IRMHw_0yIXeEJFq-3WdnhxE1GkGRvlev56faOAQKfEjGe_D8H_9FvNGyPHUrb"}'
curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=AAAARx2WWw4: APA91bFRCwWXKNSTSTdYznuIflRijbS03V8qzj8RvDN7vv22Xw8Km3dCIfEYliBXhb9b8yF_5mlnBS7jHJkKfyxfmERaTttzI9lZyIxED3Psi_d14v_XELvZO5yBUTB2U-W"

Now Its Time To integrate with local Notification

Add below dependency in your pubspec.yaml file

flutter_local_notifications: ^3.0.2

Flutter Local Notifications Changes In Android Platform

For local notifications in android, We need to add following permissions in android manifest file.

<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED”/>
<uses-permission android:name=”android.permission.VIBRATE” />

We also need to add receivers in android manifest file. Add below lines under application tag in AndroidManifest.xml.

<receiver android:name= “com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver”>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED”></action>
</intent-filter>
</receiver>
<receiver android:name=”com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver” />

Request Permissions For Flutter Local Notifications In iOS Platform

We need to ask notification permission for iOS users to integrate local notifications.

void requestPermissions() {
flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation
<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}

Initialize Flutter Local Notifications

First we initialize notification settings for android and iOS platform separately. For android platform, We must specify notification icon name otherwise notification will not be shown in android platform. Notification icon must be places under android res/drawable folder.

For iOS platform, You can set sound, badge and alert permissions as below. You can also specify function to onSelectNotification parameter to display new screen on click of notification. You can also pass information to new screen.

@override
void initState() {
super.initState();
var androidSettings = AndroidInitializationSettings(‘app_icon’);
var iOSSettings = IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
);
var initSetttings = InitializationSettings(androidSettings, iOSSettings);
flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onClickNotification);
}Future onClickNotification(String payload) {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return DestinationScreen(
payload: payload,
);
}));
}

--

--