[英]How to extend a class in Dart/Flutter
我有 class 答:
class A{
String title;
String content;
IconData iconData;
Function onTab;
A({this.title, this.content, this.iconData, this.onTab});
}
我如何創建 class B 擴展 class 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) => {
});
您必須在子類上定義構造函數。
class B extends A {
bool read;
B({title, content, iconData, onTab, this.read}) : super(title: title, content: content, iconData: iconData, onTab: onTab);
}
您可以使用 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();
}
僅針對 2023 年進行更新,自 Dart 2.17 以來,我們擁有超級初始化器 - Michael Thomsen 在此處進行了詳細描述
您不再需要顯式調用 super。
例子:
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.