【发布时间】:2019-02-17 08:07:38
【问题描述】:
我一直在调查我的 Flutter 应用程序的 JSON 解析,并且有一个关于我无法解决的工厂构造函数的问题。我试图了解使用工厂构造函数与普通构造函数的优势。例如,我看到很多 JSON 解析示例,它们使用如下 JSON 构造函数创建模型类:
class Student{
String studentId;
String studentName;
int studentScores;
Student({
this.studentId,
this.studentName,
this.studentScores
});
factory Student.fromJson(Map<String, dynamic> parsedJson){
return Student(
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
);
}
}
我还看到了相同数量的不将构造函数声明为工厂的示例。两种类型的 classname.fromJSON 构造函数都从 JSON 数据创建一个对象,因此将构造函数声明为工厂或在这里使用工厂是多余的吗?
【问题讨论】:
-
工厂构造函数不是真正的构造函数。它们是隐藏在假构造函数后面的函数。它们用于替换您在其他语言中使用的静态方法
-
这帮助我理解了它:stackoverflow.com/a/56107639