使用 fromJson 的 Flutter 空安全

Flutter null safety with fromJson

最近迁移到 Flutter 空安全功能,我有很多 类 需要更新。

对于我的模型,我使用 fromJson 反序列化来自 json 对象的数据。这迫使我为每个非可选字段添加 late 关键字。

这是正确的方法吗?

class ServerSession {
  late String sessionId;
  late String refreshToken;
  late String accessToken;

  ServerSession({required this.sessionId, required this.refreshToken, required this.accessToken});

  ServerSession.fromJson(Map<String, dynamic> json) {
    sessionId = json['session_id'] ?? json['sessionId'];
    refreshToken = json['refresh_token'] ?? json['refreshToken'];
    accessToken = json['access_token'] ?? json['accessToken'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['sessionId'] = this.sessionId;
    data['refreshToken'] = this.refreshToken;
    data['accessToken'] = this.accessToken;
    return data;
  }
}

不,不是。您应该使用初始化列表来初始化 class 的字段。您可以在 language tour.

中阅读有关初始化程序列表的更多信息
class ServerSession {
  String sessionId;
  String refreshToken;
  String accessToken;

  ServerSession({required this.sessionId, required this.refreshToken, required this.accessToken});

  ServerSession.fromJson(Map<String, dynamic> json) :
    sessionId = json['session_id'] ?? json['sessionId'],
    refreshToken = json['refresh_token'] ?? json['refreshToken'],
    accessToken = json['access_token'] ?? json['accessToken'];

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['sessionId'] = this.sessionId;
    data['refreshToken'] = this.refreshToken;
    data['accessToken'] = this.accessToken;
    return data;
  }
}

我个人会为对象使用“普通”构造函数,并使 fromJson 成为工厂构造函数,尽管这两种方法都有效。

class ServerSession {
  String sessionId;
  String refreshToken;
  String accessToken;

  ServerSession({required this.sessionId, required this.refreshToken, required this.accessToken});

  factory ServerSession.fromJson(Map<String, dynamic> json) {
    return ServerSession(
      sessionId: json['session_id'] ?? json['sessionId'],
      refreshToken: json['refresh_token'] ?? json['refreshToken'],
      accessToken: json['access_token'] ?? json['accessToken']
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['sessionId'] = this.sessionId;
    data['refreshToken'] = this.refreshToken;
    data['accessToken'] = this.accessToken;
    return data;
  }
}