How to receive notification even if the flutter app is terminated?

2,438 views
Skip to first unread message

Timothy Lungcayana

unread,
Apr 23, 2020, 8:59:24 AM4/23/20
to Flutter Development (flutter-dev)
I am developing a flutter app which requires a feature to receive notifications even the app is terminated. I'm currently using Firebase Cloud Messaging to push notifications along with firebase_messaging to handle incoming messages from Firebase and it works perfectly fine.

 However, I want to receive notification even if the app is terminated as well. Is there someone can help me? Is there somebody who already done this? If yes, can you provide me example on how to do this? Thanks in advance. I'd really appreciate it.

balaji ks

unread,
Apr 23, 2020, 9:06:43 AM4/23/20
to Flutter Development (flutter-dev)
Hi Timothy,
By default background and OnAppTerminated, the app will receive and show the notification from the notification tray. You don't want to add any code in that.
If you want to handle the notification on the Termination of the app, you will use this code.

onLaunch: (Map<String, dynamic> message) async {}

Thanks,
Balaji

Timothy Lungcayana

unread,
Apr 23, 2020, 9:20:54 AM4/23/20
to Flutter Development (flutter-dev)
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';

class PushNotificationService{
  final FirebaseMessaging _fcm = FirebaseMessaging();

  Future initialise(BuildContext context) async{
    
    if(Platform.isIOS){
      _fcm.requestNotificationPermissions(IosNotificationSettings());
    }

    _fcm.configure(
      onMessage: (Map<Stringdynamic> message) async{
        print('onMessage: $message');
        _serializeAndNavigate(message, context);
      },

      onLaunch: (Map<Stringdynamic> message) async{
        print('onLaunch: $message');
        _serializeAndNavigate(message, context);
      },

      onResume: (Map<Stringdynamic> message) async{
        print('onResume: $message');
        _serializeAndNavigate(message, context);
      }
    );
    

    var token = await _fcm.getToken();
    print("Instance ID: " + token);
  }

  void _serializeAndNavigate(Map<Stringdynamic> message, BuildContext context){
    var notificationdata = message['data'];
    var view = notificationdata['view'];

    if(view != null){
      Navigator.pushNamed(context, view);
    }
  }
}

As you can see, I already have onLaunch function configured on _fcm.configure() and pushed notification from Firebase Console. Still, notification is not displaying on notification tray.  
Reply all
Reply to author
Forward
0 new messages