You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法配置10.0.0版本Flutter firebase messaging,寻求可行解决方案

问题核心原因

firebase_messaging 9.0及以上版本已经完全废弃了旧版的configure()方法,以及onMessage、onLaunch、onResume回调,你当前的写法是0.x/1.x版本的旧用法,和10.0.0版本不兼容,这是配置失败的核心原因。

适配10.0.0版本的正确代码
import 'package:firebase_messaging/firebase_messaging.dart';

class PushNotificationService {
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  Future initialize() async {
    // 申请通知权限(覆盖iOS、安卓13及以上版本要求)
    NotificationSettings settings = await firebaseMessaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      // 应用在前台时接收通知的回调,替代旧版onMessage
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        print('onMessage: ${message.toMap()}');
        // 若需要前台展示通知,可搭配flutter_local_notifications插件实现弹窗逻辑
      });

      // 应用在后台时点击通知打开的回调,替代旧版onResume
      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
        print('onResume/后台点击通知打开: ${message.toMap()}');
      });

      // 应用被完全终止时点击通知打开的触发逻辑,替代旧版onLaunch
      RemoteMessage? initialMessage = await firebaseMessaging.getInitialMessage();
      if (initialMessage != null) {
        print('onLaunch/应用从终止状态被通知打开: ${initialMessage.toMap()}');
      }
    }
  }

  Future<String?> getToken() async {
    String? token = await firebaseMessaging.getToken();
    if (token != null) {
      driversRef.child(currentFirebaseUser.uid).child("token").set(token);
      await firebaseMessaging.subscribeToTopic("alldrivers");
      await firebaseMessaging.subscribeToTopic("allusers");
    }
    return token;
  }
}
额外必要配置检查
  • 安卓端:确保android/app/src/main/AndroidManifest.xml中添加了默认通知渠道的meta-data配置,且google-services.json已放到android/app目录下
  • iOS端:确保Xcode中开启了Push Notifications能力,以及Background Modes中的Remote notifications选项,且GoogleService-Info.plist已通过Xcode导入到项目中

内容的提问来源于stack exchange,提问作者Ahmed Alqasim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:45:03