【问题标题】:How to extend a class in Dart/Flutter如何在 Dart/Flutter 中扩展一个类
【发布时间】:2019-07-04 01:28:39
【问题描述】:

我有A班:

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

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

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

试过了,但没用

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

          });

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

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

    【讨论】:

    • 请问B类在哪里添加一些业务逻辑(例如:句柄标题)?
    【解决方案2】:

    您可以使用 extends 关键字从类继承或扩展。这允许您在相似但不完全相同的类之间共享属性和方法。此外,它允许不同的子类型共享一个公共的运行时类型,这样静态分析就不会失败。 (更多内容见下文); 典型的例子是使用不同类型的动物。

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2020-02-06
      • 2013-04-21
      • 2013-12-14
      • 2016-10-21
      相关资源
      最近更新 更多