将来自 FCM 通知的数据添加到 Flutter 列表?

Add data from FCM notification to a Flutter List?

我正在尝试将来自 Firebase 云消息传递通知的数据添加到列表中。

final List<FCMContent> fcmcrafts = [];

该列表是根据从外部 PHP 页面下载的 JSON 数据创建的。

if (response.body.contains('audioid')) {
    List fcmcrafts = json.decode(response.body);
    return fcmcrafts.map((fcmcraft) => FCMContent.fromJson(fcmcraft)).toList();
}

这是我为 FCMContent 准备的 class;

class FCMContent {

  final String audioid, name, title;

  FCMContent({
    this.audioid,
    this.name,
    this.title,
  });

  factory FCMContent.fromJson(Map<String, dynamic> jsonData) =>FCMContent(
      audioid: jsonData['audioid'],
      name: jsonData['name'],
      title: jsonData['title']
  );

  Map<String, dynamic> toJson() => {
    "audioid":audioid,
    "name":name,
    "title":title
  };
}

如何将 FCM 通知添加到列表中?如果它是一个字符串,下面是我将如何添加它。

 @override
 void onNotify(RemoteMessage notification) {
  _firebaseMessagingBackgroundHandler(notification);
 setState(() {
  _notification = notification;
  fcmcrafts.insert(0, _notification?.notification?.title ?? "");
  });
}

但是如何添加作为 JSON 代码到达的 FCM 通知?

你不能做这样的事情吗

fcmcrafts.insert(0, FCMContent.fromJson(_notification),);

您只需将 RemoteMessage 转换为 FCMContent,也许您可​​以创建自定义构造函数 FCMContent.fromRemoteMessage() 并映射字段。