给定此代码:

abstract class Animal {

        String name;

        Animal (String this.name) {
        }

}

class Dog extends Animal {

        // Why does this fail
        Dog() {
            super("Spot");
            print("Dog was created");
        }

        // Compared to this
        // Dog() : super("Spot");

}

根据多张单据:

您可以使用以下语法调用超类的构造函数:

Dog() : super("Spot");

我假设这是一种快捷语法,可以快速调用超类的构造函数.但是如果我还想在狗的构造器中做其他事情,比如调用print,该怎么办呢.

为什么这不起作用,编写代码的正确方式是什么?

// Why does this fail
Dog() {
    super("Spot");
    print("Dog was created");
}

推荐答案

您可以这样拨打super:

abstract class Animal {
  String name;
  Animal (String this.name);
}

class Dog extends Animal {
  Dog() : super('Spot') {
    print("Dog was created");
  }
}

void main() {
  var d = new Dog(); // Prints 'Dog was created'.
  print(d.name);     // Prints 'Spot'.
}

Dart相关问答推荐

Flutter 布局:如何在 Flutter 中将 Row 放入 Flex(或另一个 Row)中?还使用堆栈小部件

在 Flutter 中检测键盘事件

StreamBuilder 会在无状态小部件中自动关闭流吗?

在Flutter中解析 JSON 到 Map

如何在 Dart 中创建一个空 Set

如何在动态链接中传递参数?

Flutter-创建value和name数组

如何在 Flutter DropDown 按钮中搜索

Flutter url_launcher 未在发布模式下启动 url

不推荐使用AnteStorStateofType,请改用findAncestorStateOfType

Flutter判断变量是否为 NaN

Dart 语法高亮不是高亮 dart 代码

断言失败时如何在 Dart 中打印消息?

如何在 Dart 2 中clone复杂对象

在 Dart 中切换失败

何时使用polymer点击或点击?

Dart:如何判断变量类型是否为字符串

你如何在 Dart 中打印美元符号 $

dart中的动态和对象有什么区别?

如何停止 Dart 的 .forEach()?