Updated Push Notifications — Flutter
Flutter firebase team has updated the push notifications and got me to spend 2 days to implement the new way for push notifications. 😄
So what’s changed?
Previously we would create an instance of FirebaseMessaging and call configure method on it for displaying our notifications.
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();_firebaseMessaging.configure(
onMessage: (message) async{
setState(() {
messageTitle = message["notification"]["title"];
notificationAlert = "New Notification Alert";
});
},
onResume: (message) async{
setState(() {
messageTitle = message["data"]["title"];
notificationAlert = "Application opened from Notification";
});
},
);
onMessage allowed us to receive the notifications while we are running the app (App is in Foreground). The onResume function triggers when we receive the notification alert in the device notification bar and opens the app through the push notification itself. In this case, the app can be running in the background or not running at all.
Sadly there’s no .configure method anymore.
Updates
Here’s what I found while implementing push notifications for both app being in foreground or background.
Initial Steps
- Setup your project with firebase.
- Add Firebase Messaging package in your pubspec.yaml file. i.e., firebase_messaging:
- Scroll down to cloud messaging in your firebase console.
- Create a token, which I reckon you know how to do.
- Why this token in necessary? Because the push notifications will only work only when the app is started at least once on your phone and generate device specific token.
- Run the following code and copy the token from your debug console.
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';class PushNotifications extends StatefulWidget {
@override
_PushNotificationsState createState() => _PushNotificationsState();
}class _PushNotificationsState extends State<PushNotifications> {
FirebaseMessaging messaging = FirebaseMessaging.instance;@override
void initState() {
super.initState();
messaging.getToken().then((value) => print("token: $value"));
}@override
Widget build(BuildContext context) {
return Container();
}
}
All set for now.
Background Notifications
Background push notifications work by default. Make sure your app is in background. Go to your firebase console in cloud messaging
Enter a dummy Notification Title and Notification Text.
Click on Send text message.
Add your token.
Select your token and test your dummy notification.
This notification will only launch your application without performing any action (the only thing that you came down here for).
So, how do we do that?
What action do you want to perform?
Let’s create a pop up dialogue box to display, which contains the notification data, and display that pop up after clicking the notification while in background.
Create a dialogue Box
_showCupertinoDialog(context, String title, String body) {showDialog(context: context,builder: (_) => new AlertDialog(title: Center(child: new Text(title)),content: Column(mainAxisSize: MainAxisSize.min,children: [Text(body,textAlign: TextAlign.center,style: TextStyle(fontSize: 30.0, color: Colors.grey),),SizedBox(height: 15,),Row(mainAxisAlignment: MainAxisAlignment.spaceAround,children: [SizedBox(width: 120,child: ElevatedButton(style: ButtonStyle(backgroundColor:MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {if (states.contains(MaterialState.pressed))return Colors.black;return Colors.green; // Use the component's default.},),),onPressed: () {_stopFile();Navigator.pop(context);},child: Text('Accept'),),),SizedBox(width: 5,),SizedBox(width: 120,child: ElevatedButton(style: ButtonStyle(backgroundColor:MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {if (states.contains(MaterialState.pressed))return Colors.black;return Colors.red; // Use the component's default.},),),onPressed: () {_stopFile();Navigator.pop(context);
},
child: Text('Reject'),),),],)],),));
}
To return this dialogue box after clicking on notification, we need to use the “onMessageOpenedApp” method which is now provided with firebase messaging.
Create an asynchronous function named backgroundNotifications()
In this function we will use an instance of FirebaseMessaging to controll the action that we want to perform when we click on the notification.
void backgroundNotifications() async {try {FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {RemoteNotification notification = message.notification;if (notification != null) {_showCupertinoDialog(context, notification.title, notification.body);}});} catch (e) {}}
Now if we send our self a nice notification we will be seeing a dialogue box, when the app is opened from notification panel.
But don’t forget to call this function in your initState() method.
@override
void initState() {
super.initState();
backgroundNotifications();
}
Here’s the output:
Foreground Notifications
Foreground notifications are used when your app is in a running state.
To display notifications in foreground we will be using the ‘onMessage’ function, with firebase messaging.
For handling the actions to happen when the app is in foreground, its almost the same as the background.
Create a foregroundNotifications function call it in initState().
void foregroundNotifications() async {try {FirebaseMessaging.onMessage.listen((RemoteMessage message) {RemoteNotification notification = message.notification;if (notification != null) {_showCupertinoDialog(context, notification.title, notification.body);}});} catch (e) {}}