Flutter Firebase通知在Android模拟器无法正常显示问题
排查与修复步骤
终端显示已收到消息广播但无通知弹出,说明消息已抵达设备,但本地通知展示逻辑或系统配置存在问题,以下是具体排查和修复方案:
1. 补全Android 8.0+通知渠道配置
Android 8.0(API 26)及以上版本必须创建通知渠道才能展示通知,确保代码中初始化了对应渠道:
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin(); void _initNotificationChannel() async { const AndroidNotificationChannel channel = AndroidNotificationChannel( 'push_notification_channel', // 自定义渠道ID '推送通知', // 渠道名称 description: '接收Firebase推送消息的通知渠道', importance: Importance.max, ); await _notificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); }
在初始化Firebase Messaging前调用该方法。
2. 修正Firebase消息监听逻辑
分别处理前台、后台/终止状态的消息:
- 前台消息:通过
onMessage监听并手动触发本地通知
FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { _notificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( 'push_notification_channel', // 与初始化的渠道ID一致 '推送通知', channelDescription: '接收Firebase推送消息的通知渠道', icon: '@mipmap/ic_launcher', // 替换为你的应用图标 ), ), ); } });
- 后台/终止状态:在
AndroidManifest.xml中声明默认通知通道,让Firebase自动触发通知:
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="push_notification_channel" />
3. 检查模拟器通知权限
打开模拟器设置 → 应用 → 你的应用 → 通知,确保:
- 总通知权限已开启
- 对应通知渠道未被禁用
4. 验证build.gradle依赖配置
项目级(android/build.gradle)
确认Google服务插件版本兼容:
buildscript { dependencies { classpath 'com.google.gms:google-services:4.3.15' // 使用最新稳定版 } }
应用级(android/app/build.gradle)
确保Firebase Messaging依赖版本与Flutter插件匹配:
dependencies { implementation 'com.google.firebase:firebase-messaging:23.2.1' }
同时检查minSdkVersion不低于21(Firebase Messaging最低要求)。
5. 同步pubspec.yaml插件版本
确保相关插件版本兼容:
dependencies: flutter: sdk: flutter firebase_core: ^2.15.0 firebase_messaging: ^14.6.5 flutter_local_notifications: ^16.1.0
执行flutter pub get更新依赖。
6. 测试消息格式与系统时间
- Firebase控制台发送测试消息时,确保勾选了通知选项(仅
data字段的消息不会自动触发通知) - 检查模拟器系统时间是否与网络时间同步,时间偏差可能导致通知延迟或不展示
内容的提问来源于stack exchange,提问作者user17281101
相关产品推荐
相关产品推荐

