Flutter:如何从 firebase 通知负载获取 Json 数据

Gok*_*oku 6 dart flutter firebase-cloud-messaging

当我收到来自 firebase 的通知时,我需要显示自定义对话框。但我不知道如何从通知负载中获取我的数据

我试过下面的代码,但它是机器人为我工作

  Future<void> _handleNotification(
    Map<dynamic, dynamic> message, bool dialog) async {
    final dynamic data = message['data'] ?? message;
    final dynamic notification = message['notification']['body'] ?? message;

    final String itemId = data['body'];

    debugPrint("DATA ->> $data");
    debugPrint("notification ->> $notification");
    message.forEach((k, v) => debugPrint("${k} - ${v}"));
  }
Run Code Online (Sandbox Code Playgroud)

这是我在控制台中的有效载荷

flutter: 通知消息 {gcm.message_id: 1578573493122232, id: 30, google.cae: 1, type: test, aps: {alert: {title: notication title, body: Message of Push notification}, sound: 1}}

任何机构都可以帮助从通知负载中获取数据吗?

Gok*_*oku 8

最后我可以自己解决这个问题

如果您想从通知负载中获取数据,那么您需要"data"在消息的 -field内发送您的数据。

示例代码从"data"消息的 -field读取数据。

Future<void> _handleNotification(
    Map<dynamic, dynamic> message, bool dialog) async {
    var data = message['data'] ?? message;
    String notificationTitle = data['YOUR_KEY']; // here you need to replace YOUR_KEY with the actual key that you are sending in notification  **`"data"`** -field of the message. 
    String notificationMessage = data['YOUR_KEY'];// here you need to replace YOUR_KEY with the actual key that you are sending in notification  **`"data"`** -field of the message. 

    // now show the Dialog
    Utils().showMessageDialog(context, notificationTitle,notificationMessage);
  }
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请阅读 Notification messages with additional data