【问题标题】:Dart - error doing deserialization of FCM Json notificationDart - 对 FCM Json 通知进行反序列化时出错
【发布时间】:2021-06-23 14:41:36
【问题描述】:

我有一个用 Flutter 1.22.2 制作的应用,我正在整理一个“通知中心”视图。当通知到达设备时,它以 json 格式到达,我正在尝试进行解码,以将其显示在此视图中。

     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");
  },
);

我的解码类:

// 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/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

怎么回事,onMessage()尝试直接通过decode类,弹出错误,返回null,怎么办?

【问题讨论】:

    标签: json firebase flutter dart firebase-cloud-messaging


    【解决方案1】:

    尝试使用PushDecode.fromJson(jsonDecode(message.data));

    你可能会得到它作为一个字符串。

    【讨论】:

    • 我无法得到这个.datamessage 是一个 Map &lt;String, dynamic&gt; 变量
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 2015-01-11
    • 2011-12-17
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多