Flutter:FCM 未处理的异常:对空值使用空检查运算符

问题描述 投票:0回答:4

E/flutter(26872):[错误:flutter/lib/ui/ui_dart_state.cc(199)] 未处理的异常:对空值使用空检查运算符 E/颤振(26872):#0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (包:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:173:53) E/颤振(26872):#1
FirebaseMessagingPlatform.onBackgroundMessage= (包:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:108:16)

// Background Messaging Set Up
    Future<void> _firebaseMessagingBackgroundHandler(
        RemoteMessage message) async {
      print('background message');
    }

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    runApp(....)

我在 Android 系统上遇到此代码错误。除非应用程序终止,否则一切正常。

Android 上的功能:

  • 终止时的通知、onBackground 和 onForeground
  • 仅在前台时显示日期

什么在 Android 上不起作用:

  • 仅在终止和后台时才显示数据

iOS 上的功能:

  • 终止时的通知、onBackground 和 onForeground
  • 仅在前台时显示日期

什么在 iOS 上不起作用:

  • 仅在终止时才显示数据,

我不知道为什么我在 Android 系统上收到空值错误以及如何解决此问题?另外,在iOS上,当应用程序终止时,我是否真的无法收到

Data only
推送通知?

flutter push-notification firebase-cloud-messaging
4个回答
75
投票

我和你有同样的错误,在同一行。我查看了docs,它说了关于后台消息处理程序的两件事。

  1. 它不能是匿名函数。
  2. 它必须是顶级函数(例如,不是需要初始化的类方法)。

就我而言,它不是顶级函数,它是在类内部声明的。当您将处理程序移出任何类或函数,使其成为顶级函数并且不需要任何类或方法初始化时,错误就会消失。


27
投票

_firebaseMessagingBackgroundHandler 函数应该位于主函数之外。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
}


Future<void> main() async {

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  runApp(
    ...
  );
}

6
投票

就我而言,仅仅按照文档所说的去做是不够的。所以我意识到我应该在 main 函数中的所有内容之前添加

WidgetsFlutterBinding.ensureInitialized()
,如下所示:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(_handleMessage);
  runApp(const Homino());
}

0
投票
Future<void> backgroundNotification() async {
// await FirebaseMessaging.instance.setDeliveryMetricsExportToBigQuery(true);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  if (kDebugMode) {
    print("message ===> $message");
    print("message ===> ${message.sentTime}");
    print("message ===> ${message.notification?.title}");
    print("message ===> ${message.notification?.body}");
  }
  if (message.notification!.title!.isNotEmpty &&
      message.notification!.body!.isNotEmpty) {
    // Can use package:flutter_local_notifications for show notifications in app.
  }
});

}

© www.soinside.com 2019 - 2024. All rights reserved.