Flutter - 使用 json_serialized 反序列化 firebase_messagin 通知

Tho*_*ole 1 json flutter firebase-cloud-messaging

我在应用程序中的所有模型上使用Json_serialized(它通过命令行自动为我的模型提供 fromJson 和 toJson 方法)。

每个(反)序列化都可以完美运行,但不能与 firebase_messaging json 一起运行。

这就是我所做的:

onMessage: (Map<String, dynamic> msg) {
  FCMNotification fcmNotification = FCMNotification.fromJson(msg);
}
Run Code Online (Sandbox Code Playgroud)

我总是有这种错误:

类型“String”不是类型转换中类型“Map <dynamic,dynamic>”的子类型

或者

'_InternalLinkedHashMap<dynamic,dynamic>'不是类型'Map<String,dynamic>'的子类型

我在github上看到过这种问题,但是我没有找到适合我的解决方案。请帮助

Tho*_*ole 6

我已经找到了问题和解决方案。

Firebase 云消息传递通知以地图形式接收。

地图的结构如下:

{
"registration_ids": ["registrationID1, "registrationID2", ...],
"notification": {
  "title": "New message",
  "body": "new message in channel: test"
},
"data": {
  "type": "CHANNEL_MESSAGE",
  "author": {
    "id": 5,
    "firstName": "John",
    "lastName": "Doe",
    "email": "J.doe@email.com",
    "userType": "USER",
    "language": "EN"
  },
}
Run Code Online (Sandbox Code Playgroud)

}

我们可以把我们想要的东西放在“数据”中。就我而言,我有一个 Author 对象。该对象在地图中创建一个附加级别。Firebase Cloud Messaging 认为所有附加级别值都是字符串。

因此,我们可以使用传统的“fromJson(json)”方法反序列化“data”,但是如果我们想反序列化“author”,我们必须首先解码 Json,如下所示:

String jsonAuthorStr = msg["data"]["author"];
Map<String, dynamic> temp = json.decode(jsonAuthorStr);
Run Code Online (Sandbox Code Playgroud)

然后,反序列化:

Author author = Author.fromJson(temp);
Run Code Online (Sandbox Code Playgroud)