I have an app made in flutter 1.22.2, and I'm putting together a "Notification Center" view. When the notification arrives at the device, it arrives in json format, and I'm trying to make a decode, to display it in this view.

     fcm.configure(
  onMessage: (message) async {
    try {
      print("onMessage: $message");
     PushDecode.fromJson(message);
     print(PushDecode().notification.title);

    } catch (e) {
      print(e);
    }
    return message;
  },
  onLaunch: (message) async {
    print("onLaunch: $message");
  },
  onResume: (message) async {
    print("onResume: $message");
  },
);

My decode class:

// final pushDecode = pushDecodeFromJson(jsonString);
import 'dart:convert';

PushDecode pushDecodeFromJson(String str) => PushDecode.fromJson(json.decode(str));

String pushDecodeToJson(PushDecode data) => json.encode(data.toJson());

class PushDecode {
  PushDecode({
    this.data,
    this.notification,
  });

  Data data;
  PushNotification notification;

  factory PushDecode.fromJson(Map<dynamic, dynamic> json) => PushDecode(
        data: Data.fromJson(json["data"]),
        notification: PushNotification.fromJson(json["notification"]),
      );

  Map<dynamic, dynamic> toJson() => {
        "data": data.toJson(),
        "notification": notification.toJson(),
      };
}

class Data {
  Data({
    this.title,
    this.message,
  });

  String title;
  String message;

  factory Data.fromJson(Map<dynamic, dynamic> json) => Data(
        title: json["title"],
        message: json["message"],
      );
  Map<dynamic, dynamic> toJson() => {
        "title": title,
        "message": message,
      };
}

class PushNotification {
  PushNotification({
    this.body,
    this.title,
  });
  String body;
  String title;
  factory PushNotification.fromJson(Map<dynamic, dynamic> json) =>
      PushNotification(
        body: json["body"],
        title: json["title"],
      );
  Map<dynamic, dynamic> toJson() => {
        "body": body,
        "title": title,
      };
}

I have received this error when I run the code.

I/flutter (xx): onMessage: {notification: {title: Test one, body: Test one body}, data: {title: number 1, message: number too}}
I/flutter (xx): NoSuchMethodError: The getter 'title' was called on null.
I/flutter (xx): Receiver: null
I/flutter (xx): Tried calling: title

What happens is that the onMessage () try goes straight through the decode class, and the error pops up, returning null, what should I do?


Solution 1: Huthaifa Muayyad

Try using PushDecode.fromJson(jsonDecode(message.data));

You might be getting it as a string.