【发布时间】:2019-10-02 21:02:24
【问题描述】:
我试图弄清楚如何在不指定父类的所有可选参数的情况下创建类的子类,但仍然可以从子子类的构造函数中访问它们。当使用无数属性对 Flutter Widget 进行子类化时,这一点尤其重要。
例如 DoorWidget 是具有许多可选参数的父类。
ChildDoorWidget 继承了 DoorWidget 添加额外的逻辑,但仍然想要所有可选的父参数,而不必在子类的 super() 方法中指定每个参数。
有没有办法做到这一点?
这是一个例子。
// Maine widget
class DoorWidget {
String color = 'red';
int width;
int height;
int p1;
int p2;
int p3;
Function onKicked = () => print('Kicked');
DoorWidget(this.color, {this.onKicked, this.width, this.height, this.p1, this.p2, this.p3});
}
class ChildDoorWidget extends DoorWidget {
@override
String color = 'green';
ChildDoorWidget(String color, {Function onKicked, int width, int height})
// Do I need to specify every parent optional parameter in the super class?
// Is there a way to avoid this.
: color = color,
super(color, onKicked: onKicked, width: width);
}
main() {
DoorWidget d = DoorWidget('green', width: 10, onKicked: () => print('DoorWidget Kicked') );
print('Text Class');
print(d.color);
print(d.width);
d.onKicked();
ChildDoorWidget c = ChildDoorWidget('blue',
width: 12, onKicked: () => print('ChildDoorWidget tapped called'));
// Ideally I would like to do this:
// ChildDoorWidget m = ChildDoorWidget('blue', width: 12, onKicked: () => print('tapped called'), p1: 1, p2: 2, and any other optional params);
print('\nMyText Class');
print(c.color);
print(c.width);
c.onKicked();
}
【问题讨论】:
-
没有办法做到这一点,但不应该像这样覆盖小部件。您要覆盖哪些小部件?
标签: class dart flutter subclassing