我试图在我的dart代码中应用策略模式,但是我不知道为什么子类中被覆盖的方法没有被调用。
下面是将发送到移动设备的示例推送通知消息,“内容”节点中的数据可能会有所不同,具体取决于“类型”值。为了正确反序列化消息,我创建了以下类,
{
"priority": "high",
"to": "123342"
"notification": {
"body": "this is a body",
"title": "this is a title"
},
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"status": "done",
"type": "Order",
"content" : {
"order_id" : "[order_id]"
}
},
}
class Message<T extends BaseDataContent> {
String to;
String priority;
Notification notification;
Data<T> data;
Message({this.to, this.priority, this.notification, this.data});
Message.fromJson(Map<String, dynamic> json) {
to = json['to'];
priority = json['priority'];
notification = json['notification'] != null
? new Notification.fromJson(json['notification'])
: null;
data = json['data'] != null
? new Data.fromJson(json['data'])
: null;
}
}
class Notification {
String title;
String body;
Notification({this.title, this.body});
Notification.fromJson(Map<String, dynamic> json) {
title = json['title'];
body = json['body'];
}
}
class Data<T extends BaseDataContent> {
String click_action;
String status;
String type;
T content;
Data({this.click_action, this.status, this.type, this.content});
Data.fromJson(Map<String, dynamic> json) {
click_action = json['click_action'];
status = json['status'];
type = json['type'];
content = json['content'] != null?
this.content.deserializeContent(json['content'])
: null;
}
}
abstract class BaseDataContent{
BaseDataContent deserializeContent(Map<String, dynamic> jsonString);
}
class OrderMessageContent extends BaseDataContent {
int orderId;
OrderMessageContent({this.orderId}) : super();
@override
OrderMessageContent deserializeContent(Map<String, dynamic> jsonString){
///Deserialize Content json.
}
}
为了测试我的代码,我编写了一些演示代码,如下所示:
String json = '{"priority": "high", "to": "343434", "data":{"click_action":"343434","content":{"order_id" : "1234"}}}';
var jsonResponse = jsonDecode(json);
var result = Message<OrderMessageContent>.fromJson(jsonResponse);
代码到达第
行时失败this.content.deserializeContent(json['content'])
错误消息是“ NoSuchMethodError:方法deserializeContent在null上调用。Receiver:null”。我不知道为什么OrderMessageContent中的deserializeContent方法没有被调用,请帮忙。
谢谢。
答案 0 :(得分:0)
在Data
构造函数中,您在一个空对象上调用了一个方法,您在其中调用了deserializeContent
。您应该将该方法设为静态,或者首先初始化content
。
Data.fromJson(Map<String, dynamic> json) {
click_action = json['click_action'];
status = json['status'];
type = json['type'];
content = json['content'] != null?
this.content.deserializeContent(json['content'])
: null;
}