Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 在Dart中,如何不将空参数从子类传递到它的超类?_Class_Dart_Inheritance - Fatal编程技术网

Class 在Dart中,如何不将空参数从子类传递到它的超类?

Class 在Dart中,如何不将空参数从子类传递到它的超类?,class,dart,inheritance,Class,Dart,Inheritance,假设您有以下类及其子类 class ParentClass { final int a; final int b; ParentClass({this.a = 1, this.b = 2}); } class ChildClass extends ParentClass { ChildClass({ int? a, int? b, }) : super(a: a, b: b); } 我想做的是,当a或b未提供给ChildClass的构造函数时,使a和b在P

假设您有以下类及其子类

class ParentClass {
  final int a;
  final int b;
  ParentClass({this.a = 1, this.b = 2});
}

class ChildClass extends ParentClass {
  ChildClass({
    int? a,
    int? b,
  }) : super(a: a, b: b);
}
我想做的是,当
a
b
未提供给
ChildClass
的构造函数时,使
a
b
ParentClass
中定义其默认值,分别为1和2:

void main() {
   final child = ChildClass();
   print(child.a);   // expect to see '1'
   print(child.b);   // expect to see '2'
}
然而,我从上面的代码中实际得到的是两者的“null”。显然,
ChildClass
将“null”传递给
ParentClass
,并在这种情况下忽略其可选参数的默认值


是否有一种方法可以避免将未指定的可选参数从
ChildClass
传递到
ParentClass
,或者即使传递了“null”也可以在
ChildClass
中保留默认值,而不手动指定相同的默认值?

不确定这是否解决了您的问题但我会这样做:

class ParentClass {
  final int a;
  final int b;
  ParentClass({int? a, int? b})
      : this.a = a ?? 1,
        this.b = b ?? 2;
}

class ChildClass extends ParentClass {
  ChildClass({
    int? a,
    int? b,
  }) : super(a: a, b: b);
}

当前无法让派生类重用基类方法/构造函数中的默认值而不复制它们。这是一个常见的问题,而且一直存在。同时,您可以通过为默认值创建命名常量或使类型可为null并使用
null
作为默认值来缓解此问题。