'Flutter FirebaseMessaging onMessage not working

I am trying to push a notification to an IOS flutter app. My flutter main loop looks like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  print(await FirebaseMessaging.instance.getToken());

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true, // Required to display a heads up notification
    badge: true,
    sound: true,
  );

  runApp(MyApp());
}

And the initState() of MyApp() looks like this:

@override
  void initState() { 
    super.initState();

    FirebaseMessaging messaging = FirebaseMessaging.instance;

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
  }

I can't get any of the FirebaseMessaging streams to work. The onMessage/onMessageOpenedApp/onBackgroundMessage() won' work but if the App is closed I can push notifications. But still none of the above streams will have any content.

I push notifications via this python code:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

cred = credentials.Certificate("auth.json")
app = firebase_admin.initialize_app(cred)

topic = 'test'

apns_config = messaging.APNSConfig(
    payload=messaging.APNSPayload(
        messaging.Aps(
            mutable_content=False,
            sound=messaging.CriticalSound('default')
        )
    )
)

notification = messaging.Notification(
    title="FCM Message",
    body="This is a Firebase Cloud Messaging Topic Message!"
)

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    notification=notification,
    #topic=topic,
    token="token_of_device",
    apns=apns_config
)


response = messaging.send(message, app=app)

print('Successfully sent message:', response)

Is there a way to fix this problem? Thanks in advance.



Solution 1:[1]

To test notifications on IOS you must have:

Mac (to run from XCode), IPhone (will not work on emulator, because it is the politics of apple: "get all the money from user"), apple dev account (100$/year), set up certificates, ask user for permissions and then test on real Iphone device

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nazarii Boichyshyn