使用哪个构造函数?为什么?超级有什么用?
Which Constructor to use? and Why? What is super used for?
代码示例 #1(我对这些代码的解释是否正确)
class Weather extends Equatable {
final String cityName;
final double temperature;
Weather({
@required this.cityName,
@required this.temperature,
});
@override
List<Object> get props => [cityName, temperature];
}
代码示例 #2
(这里的代码抛出添加 'overrride' 的错误)
class Weather extends Equatable {
final String cityName;
final double temperature;
Weather({
@required this.cityName,
@required this.temperature,
}) : super([cityName, temperature]);
}
提前感谢您的帮助。
解决方案 #2 不是 equatable
的使用方法。
要使用 equatable
只有解决方案 #1 是有效的。
What is super
used for?
关键字super
用于调用基础class构造函数。当你有一个基础 class 时,你 有 来调用那个构造函数。默认情况下,如果您不显式执行此操作,将调用不带参数的构造函数。必须显式调用构造函数的最明显实例是当基础 class 没有无参数的可访问构造函数时。
Which Constructor to use? and Why?
您使用您的构造函数。如果 需要 ,则显式调用 super
构造函数。如果不需要,默认调用即可。
What's wrong here?
这不是你的问题,但我想这就是你来这里的原因。在您的第二个示例中,您正在调用基 class 的构造函数,该构造函数根本不存在或您无法访问。我不知道你从哪里得到可能有效的想法。也许是过时的文档或教程?妄想?通常,使用确实定义了这样的构造函数的基 class,它就可以工作。你的基础 class 没有,所以它不起作用。
代码示例 #1(我对这些代码的解释是否正确)
class Weather extends Equatable {
final String cityName;
final double temperature;
Weather({
@required this.cityName,
@required this.temperature,
});
@override
List<Object> get props => [cityName, temperature];
}
代码示例 #2 (这里的代码抛出添加 'overrride' 的错误)
class Weather extends Equatable {
final String cityName;
final double temperature;
Weather({
@required this.cityName,
@required this.temperature,
}) : super([cityName, temperature]);
}
解决方案 #2 不是 equatable
的使用方法。
要使用 equatable
只有解决方案 #1 是有效的。
What is
super
used for?
关键字super
用于调用基础class构造函数。当你有一个基础 class 时,你 有 来调用那个构造函数。默认情况下,如果您不显式执行此操作,将调用不带参数的构造函数。必须显式调用构造函数的最明显实例是当基础 class 没有无参数的可访问构造函数时。
Which Constructor to use? and Why?
您使用您的构造函数。如果 需要 ,则显式调用 super
构造函数。如果不需要,默认调用即可。
What's wrong here?
这不是你的问题,但我想这就是你来这里的原因。在您的第二个示例中,您正在调用基 class 的构造函数,该构造函数根本不存在或您无法访问。我不知道你从哪里得到可能有效的想法。也许是过时的文档或教程?妄想?通常,使用确实定义了这样的构造函数的基 class,它就可以工作。你的基础 class 没有,所以它不起作用。