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

Flutter集成FCM时RemoteNotification类型不匹配及弹窗报错求助

Flutter FCM集成中RemoteNotification空安全错误解决方法

问题分析

  • 第一个错误:message.notification是RemoteNotification?可空类型,直接赋值给非空的RemoteNotification变量,导致类型不匹配。
  • 第二个错误:给RemoteNotification加上?标记后,notification.title和notification.body本身也是String?可空类型,但Text组件要求接收非空字符串,因此报错。

修正后的代码

void initState() {
    super.initState();
    // 本地通知监听
    FirebaseMessaging.onMessage.listen((RemoteMessage message){
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if(notification != null && android != null){
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          // 处理title空值,默认空字符串
          notification.title ?? '',
          // 处理body空值,默认空字符串
          notification.body ?? '',
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channel.description,
              color: Colors.blue,
              playSound: true,
              icon: 'assets/bluelogo.png',
            ),
          )
        );
      }
    });
    // 弹窗通知监听
    FirebaseMessaging.onMessage.listen((RemoteMessage message){
     print('A new onMessageOpenedApp event was published!');
     // 修正:给可空类型变量添加?标记
     RemoteNotification? notification = message.notification;
     AndroidNotification? android = message.notification?.android;
     if (notification != null && android != null) {
       showDialog(context: context, builder: (_) {
         return AlertDialog(
           // 处理title空值,默认显示"通知"
           title: Text(notification.title ?? '通知'),
           content: SingleChildScrollView(
             child: Column(
               crossAxisAlignment: CrossAxisAlignment.start,
               children: [
                 // 处理body空值,默认空字符串
                 Text(notification.body ?? '')
               ],
             ),
           ),
         );
       });
     }
    });
  }

关键修改点

  • 给第二个监听里的RemoteNotification和AndroidNotification变量添加?标记,解决可空类型赋值错误。
  • 使用??运算符给notification.title和notification.body设置默认值,确保传给Text组件的是非空字符串。如果能确保FCM消息一定包含title和body,也可以用!断言(如notification.title!),但不推荐——若消息缺失字段会触发空指针异常。

内容的提问来源于stack exchange,提问作者Shanel Jung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:35:18