Error: The superclass, ‘Animal‘, has no unnamed constructor that takes no arguments.

  • Post author:
  • Post category:其他


Error: The superclass, ‘Animal’, has no unnamed constructor that takes no arguments.

错误:超类“Animal”没有不带参数的未命名构造函数。



问题描述:

因为构造函数没法继承

继承时候报错,提示父类里面的构造函数是由参数的,需要在子类里面也写上构造函数,将父类的构造函数传参

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

  void printInfo() {
    print('$name is $age years old');
  }
}

//通过extends关键词继承Animal类
class Cat extends Animal {
 
}

void main(List<String> args) {
  Cat cat = new Cat();
 print( cat.name);
}



解决方案:

super关键词

Try declaring a zero argument constructor in ‘Animal’, or declaring a constructor in Cat that explicitly invokes a constructor in ‘Animal’.dart(no_default_super_constructor)

尝试在“Animal”中声明零参数构造函数,或在Cat中声明显式调用“Animal”中构造函数的构造函数。dart(无默认超级构造函数)

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

  void printInfo() {
    print('$name is $age years old');
  }
}

//通过extends关键词继承Animal类
class Cat extends Animal {
  Cat(String name, int age) : super(name, age);

}

void main(List<String> args) {
  Cat cat = new Cat("Huahua",3);
 print( cat.name);
}



版权声明:本文为qq_43336158原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。