Issues receiving FCM notifications while app is open

Viewed 2535

I have written a test Flutter application in Android Studio to receive push notifications from Firebase. After finishing it, I installed it on a fresh Emulator through AVD and Tested out receiving a push notification while the app was terminated. That worked perfectly. While the app was open in the background. Once again succeeding. But strangely, while the app is opened, the push notification seems to be getting delivered to the device because I am getting D/FLTFireMsgReceiver( 6020): broadcast received for message after I publish the push notification but it never displays anything and I get

W/FirebaseMessaging( 6020): Unable to log event: analytics library is missing
W/FirebaseMessaging( 6020): Unable to log event: analytics library is missing

I've tried:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('A new onMessage event was published!');})

and I don't even get the print line.

What could I be doing wrong that would cause the notifications to only work when the app isn't running in the foreground?

1 Answers

add these libraries on the pubspec.yaml and use the code below

firebase_analytics: ^8.1.2 firebase_messaging: ^10.0.0

      void main() async {
      WidgetsFlutterBinding.ensureInitialized();
       await Firebase.initializeApp();
     FirebaseMessaging.onBackgroundMessage(_messageHandler);

      runApp(MyApp());
     }


  initialize() async {
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  FirebaseMessaging.onMessage.listen((RemoteMessage event) {
  print("message recieved");
  print(event.notification!.body);
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
  print('Message clicked!');
});


FirebaseMessaging.onMessage.listen((RemoteMessage event) {
  print("message recieved");
  print(event.notification!.body);
  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Notification"),
          content: Text(event.notification!.body!),
          actions: [
            TextButton(
              child: Text("Ok"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            )
          ],
        );
      });
    });
 }

  @override
  void initState() {
  super.initState();
  initialize();
  }
Related