Push Notification is an important feature of any app, it keeps the app users engaged. In my previous blog, I demonstrated how we can integrate push notifications into our flutter apps so it is recommended to check the previous blog first. Now in this blog, we will see how we can handle the push notifications in our flutter app.
You may also check our flutter app development services
This blog is using the following firebase_messaging package:
1 2 |
dependencies: firebase_messaging: ^7.0.3 |
To handle push notifications we are going to create a separate class. This class will initialize the FirebaseMessaging object, whose functions will be used to handle push notifications.
So, we will create a class PushNotificationsManager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class PushNotificationsManager { static FirebaseMessaging _firebaseMessaging; void setUpFirebase(BuildContext context) { if(_firebaseMessaging==null) { _firebaseMessaging = FirebaseMessaging(); _firebaseCloudMessagingListeners(context); } } void _firebaseCloudMessagingListeners(BuildContext context) { if (Platform.isIOS) _iosPermission(); //For notification permission prompt for iOS only _firebaseMessaging.getToken().then((token) { print("FCM Token: " + token); //Unique FCM token }); _firebaseMessaging.subscribeToTopic(Constant.FCM_TOPIC); _firebaseMessaging.configure( onMessage: (Map<String, dynamic> message) async { print('on message $message'); }, onResume: (Map<String, dynamic> message) async { print('on resume $message'); }, onLaunch: (Map<String, dynamic> message) async { print('on launch $message'); }, ); } void _iosPermission() { _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings(sound: true, badge: true, alert: true)); _firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) { print("Settings registered: $settings"); //Settings for iOS }); } } |
Call this class from the initial widget’s initState() method so that we can initialize the FirebaseMessaging at the start.
Now, whenever the push notification is received any of the actions from the _firebaseMessaging.configure() will be triggered. So you can add your login as per the need.
In this way, we can handle the push notifications in our Flutter app.