Thomas Nicole
Thomas Nicole

Reputation: 785

Flutter - Deserialize firebase_messagin notification using json_serializable

I am using Json_serializable on all my models in my app (it gives a fromJson and a toJson method automaticly to my models with a command line).

Every (de)serializations are working perfectly but not with the firebase_messaging json.

Here is what I do :

onMessage: (Map<String, dynamic> msg) {
  FCMNotification fcmNotification = FCMNotification.fromJson(msg);
}

And I always have this kind of error :

Type 'String' is not a subtype of type 'Map < dynamic, dynamic>' in type cast

Or

'_InternalLinkedHashMap< dynamic, dynamic>' is not a subtype of type 'Map< String, dynamic>'

I have seen this kind of issue in github here, but I didn't find any solution for me. Help please

Upvotes: 1

Views: 2419

Answers (1)

Thomas Nicole
Thomas Nicole

Reputation: 785

I have found the problem and the solution.

Firebase Cloud Messaging notifications are received as a Map.

The structure of the map is like :

{
"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": "[email protected]",
    "userType": "USER",
    "language": "EN"
  },
}

}

We can put what we want in "data". In my case, I have an Author objet. This object make an additional level in the map. Firebase Cloud Messaging considers that all additionnal levels values are String.

So, we can deserialize 'data' with traditionnal 'fromJson(json)' method, but if we want to deserialize 'author', we have to decode Json first, like that :

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

Then, deserialize :

Author author = Author.fromJson(temp);

Upvotes: 6

Related Questions