1
是否有可能在構造函數中自動初始化父類中的字段?如何自動初始化父領域?
我得到的語法錯誤:
無法參數預置「this.name」任何領域匹配
class Type {
String name;
}
class Language extends Type {
String id;
Language(this.name) {
是否有可能在構造函數中自動初始化父類中的字段?如何自動初始化父領域?
我得到的語法錯誤:
無法參數預置「this.name」任何領域匹配
class Type {
String name;
}
class Language extends Type {
String id;
Language(this.name) {
雖然你的情況很常見,此時dart language spec特別說:
Executing an initializing formal this.id causes the field id of the immediately surrounding class to be assigned the value of the corresponding actual parameter.
這基本上告訴我們,構造函數參數中的this.variable
表示法只能用於即時變量te類而不是任何父類。有幾個可用的解決方案:首先是構造函數體內分配給它:
class Type {
String name;
}
class Language extends Type {
String id;
Language(name) {
this.name = name;
}
}
另外,如果我們可以改變父類有一個構造函數,將初始化變量,然後我們就可以使用初始化列表中的子類:
class Type {
String name;
Type();
Type.withName(this.name);
}
class Language extends Type {
String id;
Language(name) : super.withName(name);
}
這是假設有一些理由,即Type
默認構造函數不自動初始化name
所以我們創建了一個名爲2號構造來代替。