未创建Firebase应用程序“[DEFAULT]”-当应用程序处于后台时,在flutter中调用Firebase.initializeApp()

6jjcrrmo  于 2023-02-13  发布在  Flutter
关注(0)|答案(1)|浏览(137)

我正在为基于应用程序的通知实现“Firebase云消息传递(FCM)”,并在应用程序处于后台时尝试调用_firebaseMessagingBackgroundHandler中的sendLocalNotification函数时收到以下错误。

An error occurred in your background messaging handler: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

下面是示例代码,

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging().onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  void sendLocalNotification(RemoteMessage message) {
  }
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  var myAppState = _MyAppState();
  myAppState.sendLocalNotification(message);
}
bis0qfac

bis0qfac1#

根据您提供的代码,_MyAppState类是在_firebaseMessagingBackgroundHandler方法内部创建的,因此,这意味着它没有使用/访问Firebase示例的上下文。
只需使用.createState()函数创建一个MyApp示例,然后就可以使用该状态调用sendLocalNotification()方法。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) 
 async {
     var myAppState = MyApp().createState();
     myAppState._MyAppState().sendLocalNotification(message);
}

相关问题