Search code examples
flutterdartinterfaceabstract-class

Method required by interface not met by extension method


For an education app I'm building, I have a module interface that requires a copyWith method:

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

The problem is that I'm using a codegen package that generates the copyWith method on an extension for the module subclasses:

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(/* ... */);
  }
}

On my AudioModule class I'm thus getting this error because I think it's not counting extension method:

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

Why is this happening if the subclass (in one way or another) does implements the copyWith?

Thank you

Edit

The workaround I ended up using was to instead use the functional_data code gen package which builds a class with the copyWith method on it that you then extend. No extensions.


Solution

  • With the extension method, your class AudioModule does not implement/override the abstracte method in Module. Extension methods work like static methods under the hood, so it does not really add copyWith() to AudioModule.

    Just have a look at the Dart docs or google for Dart extension methods and conflict resolution.