在Flutter中处理Firebase Data推送通知

时间:2019-11-24 05:56:14

标签: flutter dart

我想从Firebase向Flutter应用发送数据类型推送通知。根据文档,我们需要处理这些类型的通知,以便在通知中心中显示它们。但是没有文件说明我们如何做到这一点。

在Flutter中处理数据类型推送通知是否可行?有没有人尝试过onbackgroundMessage函数的实现?

1 个答案:

答案 0 :(得分:1)

使用official firebase_messaging library来使用推送通知,您也可以在那里找到不错的文档。 您可以像这样接收数据或通知有效载荷,

  

定义一个TOP-LEVEL或STATIC函数来处理后台消息

 Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
   if (message.containsKey('data')) {
     // Handle data message
     final dynamic data = message['data'];
   }

   if (message.containsKey('notification')) {
     // Handle notification message
     final dynamic notification = message['notification'];
   }

   // Or do other work.
 }
  

在调用configure时设置onBackgroundMessage处理程序

 _firebaseMessaging.configure(
       onMessage: (Map<String, dynamic> message) async {
         print("onMessage: $message");
         _showItemDialog(message);
       },
       onBackgroundMessage: myBackgroundMessageHandler,
       onLaunch: (Map<String, dynamic> message) async {
         print("onLaunch: $message");
         _navigateToItemDetail(message);
       },
       onResume: (Map<String, dynamic> message) async {
         print("onResume: $message");
         _navigateToItemDetail(message);
       },
     );

要显示本地通知,请使用flutter_local_notifications此库,

var androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'your channel id', 'your channel name', 'your channel description',
    importance: Importance.Max, priority: Priority.High, ticker: 'ticker');

var iOSPlatformChannelSpecifics = IOSNotificationDetails();

var platformChannelSpecifics = NotificationDetails(
    androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);

await flutterLocalNotificationsPlugin.show(
    0, 'plain title', 'plain body', platformChannelSpecifics,
    payload: 'item x');