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

Flutter中Firebase In-App Notification无报错但无法接收求助

Flutter Android设备FCM推送API返回正常但无法接收通知的解决方案

核心缺失依赖与配置

你的项目未集成FCM消息接收的核心依赖,首先在pubspec.yaml中添加:

dependencies:
  firebase_core: ^2.24.2
  firebase_messaging: ^14.7.11

执行flutter pub get完成依赖安装。

申请Android 13+通知权限

Android 13及以上版本需明确请求通知权限,在初始化代码中添加权限申请逻辑:

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  
  // 请求通知权限
  if (await Permission.notification.isDenied) {
    await Permission.notification.request();
  }
  
  runApp(const MyApp());
}

注:需在pubspec.yaml额外添加permission_handler: ^11.0.1依赖。

订阅目标主题

你推送的通知目标是/topics/myTopic,但设备未订阅该主题,在页面初始化时添加订阅逻辑:

@override
void initState() {
  super.initState();
  // 订阅主题
  FirebaseMessaging.instance.subscribeToTopic('myTopic');
}

处理前台通知展示

APP在前台运行时,FCM默认不会自动弹出通知,需手动监听并处理:

@override
void initState() {
  super.initState();
  FirebaseMessaging.instance.subscribeToTopic('myTopic');
  
  // 监听前台消息
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    RemoteNotification? notification = message.notification;
    if (notification != null) {
      // 用弹窗展示通知内容,或集成flutter_local_notifications展示系统级通知
      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          title: Text(notification.title!),
          content: Text(notification.body!),
        ),
      );
    }
  });
}

检查AndroidManifest配置

确保android/app/src/main/AndroidManifest.xml包含以下配置:

  1. 添加FCM消息服务:
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
  1. 配置通知点击跳转的Activity:
<activity
    android:name=".MainActivity"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="FLUTTER_NOTIFICATION_CLICK" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

验证设备注册状态

添加日志确认设备Token与主题订阅状态:

@override
void initState() {
  super.initState();
  // 获取设备FCM Token
  FirebaseMessaging.instance.getToken().then((token) {
    print('FCM Token: $token');
  });
  
  // 确认主题订阅结果
  FirebaseMessaging.instance.subscribeToTopic('myTopic').then((_) {
    print('已成功订阅myTopic主题');
  });
}

额外排查点

  • 确认FCM服务器密钥(Authorization中的key)未过期、无拼写错误
  • 检查google-services.json已正确放置在android/app目录,Firebase控制台应用配置与本地一致
  • 使用真实物理设备测试(部分Android模拟器存在FCM接收异常)

内容的提问来源于stack exchange,提问作者Pluto WEB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:20:25