如何在 Dart/Flutter 中扩展类

anh*_*hnt 12 dart flutter

我有A类:

class A{
    String title;
    String content;
    IconData iconData;
    Function onTab;
    A({this.title, this.content, this.iconData, this.onTab});
}
Run Code Online (Sandbox Code Playgroud)

我如何创建类 B 来扩展类 A 与附加变量如下:

class B extends A{
    bool read;
    B({this.read});
}
Run Code Online (Sandbox Code Playgroud)

试过这个但没有用

let o = new B(
          title: "New notification",
          iconData: Icons.notifications,
          content: "Lorem ipsum doro si maet 100",
          read: false,
          onTab: (context) => {

          });
Run Code Online (Sandbox Code Playgroud)

Vin*_*sil 30

您必须在子类上定义构造函数。

class B extends A {
  bool read;
  B({title, content, iconData, onTab, this.read}) : super(title: title, content: content, iconData: iconData, onTab: onTab);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

只是为了更新 2023 年,从 Dart 2.17 开始,我们有了超级初始化器 - Michael Thomsen 在这里详细描述了

您不再需要显式调用 super。

例子:

class B extends A {
    bool read;
    B({super.title, super.content, super.iconData, super.onTab, this.read});
}
Run Code Online (Sandbox Code Playgroud)