我的dart代码中是否正确使用策略模式?

问题描述 投票:0回答:1

我正在尝试在我的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上调用。接收方:null”。我不知道为什么OrderMessageContent中的deserializeContent方法没有被调用,请帮忙。

谢谢。

dart flutter
1个回答
0
投票

Data构造函数中,您在null对象上调用了一个方法,在该对象中调用了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;
}
© www.soinside.com 2019 - 2024. All rights reserved.