【问题标题】:Dart / Flutter - class doesn't have to implement abstract class's abstract methods?Dart / Flutter - 类不必实现抽象类的抽象方法?
【发布时间】:2021-04-10 12:10:06
【问题描述】:

在 Flutter 中我们有类

abstract class PreferredSizeWidget implements Widget {
  Size get preferredSize;
}

@immutable
abstract class Widget extends DiagnosticableTree {
  const Widget({ this.key });
  final Key? key;
  @protected
  @factory
  Element createElement();
  @override
  String toStringShort() {
    final String type = objectRuntimeType(this, 'Widget');
    return key == null ? type : '$type-$key';
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.dense;
  }

  @override
  @nonVirtual
  bool operator ==(Object other) => super == other;

  @override
  @nonVirtual
  int get hashCode => super.hashCode;
  static bool canUpdate(Widget oldWidget, Widget newWidget) {
    return oldWidget.runtimeType == newWidget.runtimeType
        && oldWidget.key == newWidget.key;
  }
  static int _debugConcreteSubtype(Widget widget) {
    return widget is StatefulWidget ? 1 :
           widget is StatelessWidget ? 2 :
           0;
    }
}

我的问题是:为什么如果我们混合使用 PreferredSizeWidget 类,我们就不必实现所有抽象类的 Widget 方法和抽象方法?

我试图模拟一些代码

class A implements B {}

abstract class B extends C {}

abstract class C {
  void test() {
    print("test");
  }
}

出现错误

Error: The non-abstract class 'A' is missing implementations for these members:
 - C.test
class A implements B {
      ^
lib/main.dart:16:8:

【问题讨论】:

    标签: flutter dart interface abstract-class abstract


    【解决方案1】:

    我自己没有运行它,但在你的情况下,A 不再是抽象的,所以它 必须实现一切,在 PreferredSizeWidget 的情况下 - 你 通常在小部件上扩展/实现/混合它(已经 实现小部件中的所有内容)因此只剩下你 首选尺寸

    @Norbert515的回答。

    主要的一点是,即使我们混合/扩展 PreferredSizeWidget,我们实际上实现了所有 Widget 方法,但由于我们通常在 Widget 上混合它,我们不必隐式覆盖这些方法。

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2012-08-06
      • 2013-05-30
      • 2016-11-08
      • 2015-06-29
      相关资源
      最近更新 更多