在Flutter中使用onMessage.listen时,前台的Firebase Cloud Messaging通知没有收到

移动开发 2026-07-11

我正在用Flutter构建一个应用,使用Firebase Cloud Messaging (FCM) 和 flutter_local_notifications。通知在 后台已终止 状态下工作正常,但 FirebaseMessaging.onMessage.listen 在应用处于 前台 时从未触发。

设置:

class Notificationsstatus{
// terminated
  Future<void> setupnotification(BuildContext context) async{
    //دى function بشتغل على الحالتين ارسال الاشعار سواء كان التطبيق مغلق او التطبيق فى الخلفيه
     FirebaseMessaging.instance.requestPermission();// اطلب الاذن الاول
     FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin=FlutterLocalNotificationsPlugin();// هنا احنا بنستدعى المكتبه العامه الخاصه بى الاشعارات 

    await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel);//الخاصه بلندرويد السطر ده عشان استدعى المكتبه الخاصه بى  قنوات الاشعار 
    //Inilizations الاول
      const AndroidInitializationSettings androidsettings=AndroidInitializationSettings("warning");
    const InitializationSettings initsettings=InitializationSettings(android: androidsettings);
    print("=========================================================================🔄 BEFORE INITIALIZE");
    await flutterLocalNotificationsPlugin.initialize(initsettings);
    print("=========================================================================✅ initialize DONE");
    //listen انى حاله الى عملها الuser فى التطبيق
    RemoteMessage? intialmessage=await FirebaseMessaging.instance.getInitialMessage();

    if(intialmessage!=null){
     _handledmessage(context,intialmessage);
    }
    // background
    FirebaseMessaging.onMessageOpenedApp.listen((message)=>_handledmessage(context,message));// دى حاله لو التطبيق فى حاله الخلفيه Background

    // استدعاء المكتبه العامه للاشعارات 



    // دى حاله الforeground


   try {
      FirebaseMessaging.onMessage.listen((RemoteMessage message){
      print("==================================================📩 MESSAGE RECEIVED: ${message.notification?.title}");
      print("==================================================📩 MESSAGE DATA: ${message.data}");



      RemoteNotification? notification=message.notification;

      AndroidNotification? android=notification?.android;

      if(notification!=null && android !=null){
         print("=================================================================✅ SHOWING NOTIFICATION");
        flutterLocalNotificationsPlugin.show(
          notification.hashCode, 
          notification.title, 
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
             channel.id, 
              channel.name,
              priority: Priority.high
              // icon: //
              ),
          )
          );
      }else{
    print("===========================================❌ notification or android is NULL");
    print("===========================================notification: $notification");
    print("============================================android: $android");
      }
    });
     print("✅ onMessage listener REGISTERED");
   } catch (e) {
     print("❌ ERROR: $e");
   }


  }

我尝试了:

在Firebase控制台中添加了SHA-1和 SHA-256 下载了新的google-services.json 确保在onMessage.listen之前完成初始化 使用特定的FCM令牌进行测试 添加了带有 @pragma('vm:entry-point') 的后台处理程序

结果:

后台和已终止通知可以正常工作 ✅ 在前台时onMessage.listen从不触发 ❌ 控制台没有错误

我有一个Cloud Function,当Firestore的文档被删除时应该发送一条FCM通知。该函数已部署,Firestore的路径看起来也正确,但函数从未触发。 Flutter删除代码:

Future<void> deleteitem(String id) async {
  String? token = await FirebaseMessaging.instance.getToken();

  // Save FCM token in parent document
  await FirebaseFirestore.instance
      .collection("Salesitems")
      .doc("Ck5MG5FJ3WA6TxtpiX7p")
      .set({"fcmToken": token}, SetOptions(merge: true));

  // Delete the document
  await FirebaseFirestore.instance
      .collection("Salesitems")
      .doc("Ck5MG5FJ3WA6TxtpiX7p")
      .collection("Product")
      .doc("3nv478KbjPaVFTPhL4fu")
      .collection("code")
      .doc(id)
      .delete();
}



Cloud Function:
typescriptexport const sendDeleteNotification = onDocumentDeleted(
  "Salesitems/{dep}/Product/{prodId}/code/{id}",
  async (event) => {
    const token = // get token from Salesitems/{dep}
    await admin.messaging().send({
      token,
      notification: { title: "Deleted", body: "Item deleted" },
      data: { type: "Salesitem" },
    });
  }
);

问题:

文档已成功删除 ✅ FCM令牌已保存在Firestore ✅ Cloud Function从未触发 ❌ 在Google Cloud Console中没有日志输出 ❌

我还缺少什么?

解决方案

你试过吗?

    try {
      /// Update the iOS foreground notification presentation options to allow
      /// heads up notifications.
      await FirebaseMessaging.instance
          .setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );
    } catch (e) {
      debugPrint('Error setting Firebase foreground notification options: $e');
    }
  }
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章