Dart类与Mixin报错求助:无参无名构造函数不存在问题
错误原因分析及解决方法
错误根源
你在PilotedCraft的构造函数里用super.astronauts来初始化Mixin的成员,这是行不通的:
- Mixin没有构造函数:
Piloted是Mixin,它不能定义构造函数,自然也没法通过super来传递参数初始化它的成员。 - 父类构造函数不支持第三个参数:父类
Spacecraft的构造函数只接受name和launchDate两个参数,根本没有第三个参数的定义,所以Dart会报错说找不到匹配的父类构造函数。
修复方案
修正后的完整代码
class Spacecraft { String name; DateTime? launchDate; int? get launchYear => launchDate?.year; Spacecraft(this.name, this.launchDate); Spacecraft.unlaunched(String name) : this(name, null); void describe() { print('Spacecraft: $name'); var launchDate = this.launchDate; if (launchDate != null) { int years = DateTime.now().difference(launchDate).inDays ~/ 365; print('Launched: $launchYear ($years years ago)'); } else { print('Unlaunched'); } } } mixin Piloted { int astronauts = 1; void describeCrew() { print('Number of astronauts: $astronauts'); } } class PilotedCraft extends Spacecraft with Piloted { // 先调用父类构造函数初始化name和launchDate,再直接初始化Mixin的astronauts PilotedCraft(String name, DateTime? launchDate, this.astronauts) : super(name, launchDate); @override void describe() { super.describe(); describeCrew(); // 直接调用混入的方法,无需super } } void main() { var spacecraft = PilotedCraft('ISS', DateTime(2010, 11, 20), 6); spacecraft.describe(); }
关键修改说明
- 把构造函数里的
super.astronauts删掉,改成在参数列表里用this.astronauts直接初始化Mixin的成员,初始化列表里只保留父类的构造函数调用super(name, launchDate)。 describe方法里调用describeCrew()时,不需要加super.,因为当前类已经混入了Piloted,可以直接访问该方法(加super.也能运行,但直接调用更清晰)。
你也可以用初始化列表的方式初始化astronauts,写法如下,效果完全一致:
PilotedCraft(String name, DateTime? launchDate, int astronauts) : super(name, launchDate), this.astronauts = astronauts;
内容的提问来源于stack exchange,提问作者user3523406
相关产品推荐
相关产品推荐

