【发布时间】:2021-02-18 02:48:04
【问题描述】:
https://flutter.dev/docs/cookbook/networking/fetch-data
在上述页面的最后一个“完整示例”中,
class Album {
final int userId;
final int id;
final String title;
Album({this.userId, this.id, this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
是一个Album类,用于接收请求中收到的JSON字符串并在应用程序中处理, 构造函数在普通构造函数的基础上提供了工厂构造函数。
关于工厂构造函数, https://dart.dev/guides/language/language-tour#constructors
我已阅读上述页面的工厂构造函数部分。
示例中Logger类的工厂构造函数并不总是创建一个新的实例,所以 我可以理解添加工厂关键字,
这个 Complete 示例的 Album 类中是否也需要使用工厂构造函数?
在 Album 类的情况下,由于在工厂构造函数中使用了普通构造函数, 我觉得这个工厂构造函数(Album.fromJson)总是创建一个新实例。 其实
Future<Album> fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/16');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var temp=json.decode(response.body);
return Album(userId:temp['userId'],id:temp['id'],title:temp['title']);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
如您所见,即使我尝试仅使用普通构造函数,它似乎也可以正常工作。
准备和使用工厂构造函数有什么好处吗?
或者在这种情况下不使用工厂构造函数有什么问题吗?
我不确定什么时候首先使用工厂构造函数, 有明确的定义吗?
【问题讨论】:
-
我看不出
Album.fromJson需要成为factory构造函数的任何原因。它可以用redirecting constructor 来实现。该示例可能使用factory与使用json_serializable或built_value的.fromJson构造函数保持一致(或出于习惯),并且必须使用factory构造函数。