dart工厂构造函数标识符的优势 [英] dart advantage of a factory constructor identifier

查看:62
本文介绍了dart工厂构造函数标识符的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究我的Flutter应用程序的JSON解析,并对我无法解决的工厂构造函数有疑问。我试图了解使用工厂构造函数与普通构造函数相比的优势。例如,我看到很多JSON解析示例,它们使用JSON构造函数创建了一个模型类,如下所示:

I've been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can't resolve. I'm trying to understand the advantage of using a factory constructor versus a plain constructor. For example, I see quite a few JSON parsing examples that create a model class with a JSON constructor like this:

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数据创建对象,因此将构造函数声明为工厂还是在这里使用工厂是多余的?

I've also seen an equal number of examples that DON'T declare the constructor as a factory. Both types of classname.fromJSON constructors create an object from the JSON data so is there an advantage to declaring the constructor as a factory or is using a factory here superfluous?

推荐答案

普通的构造函数总是返回当前类的新实例(构造函数抛出异常时除外)。

A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).

工厂构造函数与静态方法非常相似,不同之处在于

A factory constructor is quite similar to a static method with the differences that it


  • 只能返回当前类的实例,或者它的一个子类

  • 可以用 new 调用,但是由于 new 变为可选。

  • 没有初始化列表(没有:super()

  • can only return an instance of the current class or one of its subclasses
  • can be invoked with new but that is now less relevant since new became optional.
  • has no initializer list (no : super())

因此可以使用工厂构造函数

So a factory constructor can be used


  • 创建子类的实例(例如,根据传递的参数

  • 返回缓存的实例一个新的

  • 来准备计算所得的值,以将其作为参数转发给常规构造函数,以便最终字段可以用它们初始化。这通常用于解决普通构造函数的初始化列表中可以完成的操作的局限性(例如错误处理)。

在您的示例中,此代码

  studentId: parsedJson['id'],
  studentName : parsedJson['name'],
  studentScores : parsedJson ['score']

可以移动到a的正文中普通的构造函数,因为不需要初始化 final 字段。

could be moved to the body of a normal constructor because no final fields need to be initialized.

这篇关于dart工厂构造函数标识符的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆