Dart中的类构造函数语法之间的区别
问题内容:
我正在创建一个类,如下所示:
class Movie {
final String title, posterPath, overview;
Movie(this.title, this.posterPath, this.overview);
Movie.fromJson(Map json) {
title = json["title"];
posterPath = json["poster_path"];
overview = json['overview';
}
}
我收到一条警告,说“必须初始化最终变量’overview’,’posterPath’和‘1’。每个变量周围也有警告说’title’不能用作设置器,因为它是最终的。
当我使用这种语法编写构造函数时,警告消失了:
Movie.fromJson(Map json)
: title = json["title"],
posterPath = json["poster_path"],
overview = json['overview'];
这到底是怎么回事?
问题答案:
在任何人获得对新对象的引用之前,必须完全初始化Dart对象。由于构造函数的主体可以访问this
,因此需要 在 进入构造函数的主体 之前
初始化该对象。
为此,生成的Dart构造函数具有一个初始化程序列表,看起来类似于C ++,您可以在其中初始化字段(包括final字段),但是您尚不能访问对象本身。语法:
Movie.fromJson(Map json)
: title = json["title"],
posterPath = json["poster_path"],
overview = json['overview'];
使用了初始化列表(分配后的列表:
)来初始化最后的实例变量title
,posterPath
和overview
。
第一个构造函数使用“初始化形式” this.title
将参数直接放入字段中。
构造函数
Movie(this.title, this.posterPath, this.overview);
实际上是以下方面的简写:
Movie(String title, String posterPath, String overview)
: this.title = title, this.posterPath = posterPath, this.overview = overview;
您的构造函数可以将所有这些与主体结合起来:
Movie(this.title, this.posterPath, String overview)
: this.overview = overview ?? "Default Overview!" {
if (title == null) throw ArgumentError.notNull("title");
}
(const构造函数不能具有主体,但可以具有对允许的表达式有一些限制的初始化列表,以确保可以在编译时对其进行求值)。