FirebaseMessaging.onBackgroundMessage 不起作用

qui*_* 7 firebase flutter firebase-cloud-messaging

FirebaseMessaging.onBackgroundMessage不起作用。我遵循了官方文档。我使用的版本:firebase_messaging: ^14.2.1

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

void main() async {
  await Firebase.initializeApp()
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}
Run Code Online (Sandbox Code Playgroud)

这是我通过云函数发送 fcn 的方式:

admin.messaging().sendMulticast({
        tokens: [user.fcmToken!],
        apns: {
          payload: {
            aps: {
              "mutable-content": 1,
              "content-available": 1,
            },
          },
        },
        notification: {
          body: body,
          title: title,
        },
        data: {
          hello: "world?!",
        },
      });
Run Code Online (Sandbox Code Playgroud)

我可以看到推送通知在我的设备上弹出,但FirebaseMessaging.onBackgroundMessage没有被调用。有什么想法可能是问题出在哪里吗?

小智 -1

我想你忘了添加WidgetsFlutterBinding.ensureInitialized()

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // Try to add this
  await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}
Run Code Online (Sandbox Code Playgroud)