gpt4 book ai didi

使用 fromJson flutter null 安全性

转载 作者:行者123 更新时间:2023-12-04 12:33:10 25 4
gpt4 key购买 nike

最近迁移到 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;
}
}

最佳答案

不,不是。您应该使用初始化列表来初始化类的字段。您可以在 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;
}
}

关于使用 fromJson flutter null 安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67065621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com