Flutter集成FCM推送遇空指针错误,求解决方案
问题现象
通过Firebase Cloud Messages(FCM)发送推送通知时,接收设备能捕获通知事件,但flutter_local_notifications插件无法展示通知,抛出以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setAction(java.lang.String)' on a null object reference
此前删除AndroidManifest中的FLUTTER_NOTIFICATION_CLICK intent-filter曾临时解决问题,但现在无论有无该配置,错误均持续出现。
修复步骤
1. 统一通知渠道ID
AndroidManifest中配置的默认通知渠道ID为high_importance_channel,但showSimpleNotification方法中使用的渠道ID是ch1,两者不匹配会导致系统无法正确创建通知渠道,引发异常。修改AndroidNotificationDetails的渠道ID:
const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails( 'high_importance_channel', // 与Manifest中的默认渠道ID保持一致 '高重要性通知渠道', channelDescription: '用于展示FCM推送通知', icon: '@mipmap/ic_launcher', importance: Importance.max, priority: Priority.max, playSound: true, enableVibration: true, ticker: 'ticker', );
2. 移除冗余的click_action配置
FCM推送data字段中的click_action: 'FLUTTER_NOTIFICATION_CLICK'是旧版本用法,当前flutter_local_notifications已通过onDidReceiveNotificationResponse处理点击事件,无需该配置,删除后可避免Intent相关空指针:
final body = jsonEncode({ 'message': { 'token': token, 'notification': { 'title': title, 'body': bodyText.toString(), }, 'data': { // 移除该行:'click_action': 'FLUTTER_NOTIFICATION_CLICK', 'id': '1', 'status': 'done' } }, });
3. 调整AndroidManifest中的Intent Filter
将FLUTTER_NOTIFICATION_CLICK的intent-filter从MainActivity中移除,当前插件无需通过该Action处理点击,避免Intent冲突:
<!-- 删除以下这段配置 --> <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
4. 初始化时添加空安全判断
resolvePlatformSpecificImplementation可能返回null(非Android平台场景),修改初始化代码避免强制解包:
// 替换原有的权限请求代码 final androidImpl = _flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>(); if (androidImpl != null) { await androidImpl.requestNotificationsPermission(); }
5. 确保初始化顺序正确
在main函数中按顺序完成初始化:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await PushNotifications.init(); await PushNotifications.localNotiInit(); runApp(const MyApp()); }
验证方法
- 执行
flutter clean清理构建缓存,重新构建项目 - 通过Firebase控制台或
sendPushMessage方法发送测试通知 - 检查Logcat确认空指针异常是否消失
内容的提问来源于stack exchange,提问作者Edward Kane

