Flutter Firebase messaging - push notification is not showing when app is open

I'm new to flutter and I'm just trying to receive firebase push notifications to my flutter app. Push notifications are receiving when the app is closed and in the background. But when the app is open, push notification is receiving, but it's not showing the alert notification (I want to show the push notification title and body as an alert in my app if it's opened). Here's my code for it.

_fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: ListTile(
              title: Text(message['notification']['title']),
              subtitle: Text(message['notification']['body']),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Ok'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
        print("onMessage: $message");
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );

Can someone please help me with this?

1 answer

  • answered 2020-09-14 05:53 Ronak Punase

    FCM provides you with three callbacks. OnResume, OnLaunch and OnMessage.

    When the app is in foreground, the onMessage is triggered, and it gives you the opportunity to carry out any custom action.

    In order to show a notification while the app is in foreground, you can make use of Flutter Local Notifications package.

    You might not be able to see an alert dialog due to the lack of context inside onMessage callback. Try wrapping the _fcm.configure inside

    SchedulerBinding.instance.addPostFrameCallback((_){ [_fcm.configure block] });