无效的覆盖 copyWith

Invalid override copyWith

提问人:KueCubit 提问时间:8/16/2023 更新时间:8/17/2023 访问量:32

问:

我一直在想,有没有一种在扩展中实现 copyWith 的最佳方法? 在 Pwm 类 copyWith 方法中出错 如何修复 DAT?

此PIN码

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
    );
  }

}

**而这个错误类**

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,
    );
  }
}

有没有最好的方法可以在扩展中实现 copyWith? 我需要用抽象来扩展 PIN 吗? 喜欢:

类 Controller{

}

class Pin extends Controller{}

类 Pwm extends Controller{} E32 表示 esp32

DART 扩展

评论


答:

0赞 jamesdlin 8/16/2023 #1

(将来,请复制并粘贴您收到的错误消息。

您的问题是仅采用位置参数Pin.copyWith

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

但覆盖仅采用命名参数Pwm.copyWith

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

重写的签名必须与基本方法的签名兼容;也就是说,它必须可以使用基方法的签名(例如 )。pwm.copyWith(name, io, value, mode, usage)

您可以通过以下方式修复它:

  • 更改为使用可选的命名参数。Pin.copyWith
  • 更改为对其共享的参数使用位置参数。Pwm.copyWith