【问题标题】:Method required by interface not met by extension method扩展方法不满足接口所需的方法
【发布时间】:2020-01-09 23:10:10
【问题描述】:

对于我正在构建的教育应用程序,我有一个需要copyWith 方法的模块接口:

abstract class Module {
  // ...
  Module copyWith() => throw 'You should call the instance\'s copyWith.';
}

问题是我在模块子类的扩展上使用了 generates the copyWith 方法的 codegen 包:

part 'audio_module.g.dart';

@immutable
@CopyWith()
class AudioModule implements Module {
  /* ... */
}
// GENERATED CODE - DO NOT MODIFY BY HAND

part of audio_module;

// **************************************************************************
// CopyWithGenerator
// **************************************************************************

extension AudioModuleCopyWithExtension on AudioModule {
  AudioModule copyWith(/* ... */) {
    return AudioModule(/* ... */);
  }
}

在我的 AudioModule 课程中,我因此收到此错误,因为我认为它不包括扩展方法:

Missing concrete implementation of 'Module.copyWith'.
Try implementing the missing method, or make the class abstract.

如果子类(以某种方式)确实实现了copyWith,为什么会发生这种情况?

谢谢

编辑

我最终使用的解决方法是改用functional_data code gen package,它使用copyWith 方法构建一个类,然后您可以扩展该类。没有扩展。

【问题讨论】:

    标签: flutter dart interface abstract-class


    【解决方案1】:

    使用扩展方法,您的类AudioModule 不会实现/覆盖Module 中的抽象方法。扩展方法在底层就像静态方法一样工作,因此它并没有真正将copyWith() 添加到AudioModule

    只需查看 Dart 文档或 google 即可了解 Dart 扩展方法和冲突解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2018-05-22
      相关资源
      最近更新 更多