简体   繁体   English

如何在 Dart/Flutter 中扩展 class

[英]How to extend a class in Dart/Flutter

I have class A:我有 class 答:

class A{
    String title;
    String content;
    IconData iconData;
    Function onTab;
    A({this.title, this.content, this.iconData, this.onTab});
}

How can i create class B that extends class A with additional variable like following:我如何创建 class B 扩展 class A 附加变量如下:

class B extends A{
    bool read;
    B({this.read});
}

Tried with this but not working试过这个但没有工作

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

          });

You have to define the constructor on the child class.您必须在子类上定义构造函数。

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

You can inherit from or extend a class using the extends keyword.您可以使用 extends 关键字从类继承或扩展。 This allows you share properties and methods between classes that are similar, but not exactly the same.这允许您在相似但不完全相同的类之间共享属性和方法。 Also, it allows different subtypes to share a common runtime type so that static analysis doesn't fail.此外,它允许不同的子类型共享一个公共的运行时类型,这样静态分析就不会失败。 (More on this below); (更多内容见下文); The classic example is using different types of animals.典型的例子是使用不同类型的动物。

class Animal {
  Animal(this.name, this.age);
  
  int age;
  String name;

  void talk() {
    print('grrrr');
  }
}

class Cat extends Animal {
  // use the 'super' keyword to interact with 
  // the super class of Cat
  Cat(String name, int age) : super(name, age);
  
  void talk() {
    print('meow');
  }
  
}


class Dog extends Animal {
  // use the 'super' keyword to interact with 
  // the super class of Cat
  Dog(String name, int age) : super(name, age);
  
  void talk() {
    print('bark');
  }
  
}

void main() {
  var cat = Cat("Phoebe",1);
  var dog = Dog("Cowboy", 2);
  
  dog.talk();
  cat.talk();
}

Just to update for 2023, since Dart 2.17 we have Super Initializers - described in detail by Michael Thomsen here仅针对 2023 年进行更新,自 Dart 2.17 以来,我们拥有超级初始化器 - Michael Thomsen 在此处进行了详细描述

You no longer need to make the explicit call to super.您不再需要显式调用 super。

Example:例子:

class B extends A {
    bool read;
    B({super.title, super.content, super.iconData, super.onTab, this.read});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM