dartextends

Invalid override copyWith


I've been wondering are there a best way to implement copyWith in extends? got error in Pwm class copyWith method how to fix dat?

This Pin Code

class Pin{

  final String? name;
  final int io;
  final bool value;
  final Mode mode;
  final Usage? usage;
  const Pin({required this.io,required this.value, required this.mode, this.name, this.usage});

  factory Pin.fromList(List<dynamic> list){
    // "pin1" : (33,hardwareR4A.pin1.value(),"IN" if hardwareR4A.pin1.init() == Pin.IN else "OUT"),
    return Pin(io: list[0], value: convertValueToBool(list[1]), mode: Mode.values.firstWhere((element) => element.name == list[2]), usage: null);
  }

  Pin copyWith(
    String? name,
    int io,
    bool value,
    Mode mode,
    Usage? usage,
  ){
    return Pin(
      io: io,
      mode: mode,
      value: value,
      name: name,
      usage: usage
    );
  }

}

**And this error class **

class Pwm extends Pin {

  final int frequency;
  final int duty;
  final int resolution;

  const Pwm({
    required super.io,
    required super.value,
    required super.mode,
    super.name,
    super.usage,
    required this.frequency,
    required this.duty,
    required this.resolution,
  }) : super();

  @override
  Pwm copyWith({
    String? name,
    int? io,
    bool? value,
    Mode? mode,
    Usage? usage,
    int? frequency,
    int? duty,
    int? resolution,
  }) {
    return Pwm(
      duty: duty ?? this.duty,
      frequency: frequency ?? this.frequency,
      io: io ?? this.io,
      mode: mode ?? this.mode,
      resolution: resolution ?? this.resolution,
      value: value ?? this.value,
      name: name ?? this.name,
      usage: usage ?? this.usage,
    );
  }
}

Are there a best way to implement copyWith in extends? do i need to extends pin with abstraction? like :

class Controller{

}

class Pin extends Controller{}

class Pwm extends Controller{} E32 mean esp32


Solution

  • (In the future, please copy-and-paste the error message that you received.)

    Your problem is that Pin.copyWith takes only positional parameters:

     Pin copyWith(
       String? name,
       int io,
       bool value,
       Mode mode,
       Usage? usage,
     ){
    

    but the Pwm.copyWith override takes only named parameters:

     @override
     Pwm copyWith({
       String? name,
       int? io,
       bool? value,
       Mode? mode,
       Usage? usage,
       int? frequency,
       int? duty,
       int? resolution,
     }) {
    

    An override's signature must be compatible with the base method's; that is, it must be callable using the base method's signature (e.g. pwm.copyWith(name, io, value, mode, usage)).

    You can fix it either by: