You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

继承场景下copyWith方法实现报错,求修复方案与最优实践

继承场景下Dart copyWith方法的修复与优化方案

一、修复Pwm类copyWith的报错问题

报错核心原因是父类Pin的copyWith方法签名与子类Pwm不一致:Pin类的copyWith是必填位置参数,而Pwm类用可选命名参数重写,违反了Dart方法重写规则(重写方法必须与父类参数类型、数量、命名方式完全匹配)。

修复步骤:

  1. 修改父类Pin的copyWith为可选命名参数,保留原有功能的同时适配子类重写:
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){
    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 ?? this.io,
      mode: mode ?? this.mode,
      value: value ?? this.value,
      name: name ?? this.name,
      usage: usage ?? this.usage
    );
  }
}
  1. 子类Pwm的copyWith保持现有逻辑,此时override不再报错:
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,
  });

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

二、是否需要抽象父类优化实现?

是否引入抽象父类(如Controller)取决于业务场景:

  • 如果需要对Pin和Pwm进行统一接口处理(比如集合统一管理、方法参数传递用基类类型),或者有共同抽象行为(如统一配置更新、状态重置),那么抽象父类有价值。示例:
abstract class Controller {
  Controller copyWith(); // 定义抽象copyWith方法,子类按需实现
  // 可添加其他共同抽象方法,如reset、toJson等
}

class Pin extends Controller {
  // ... 现有代码,实现copyWith
}

class Pwm extends Controller {
  // ... 现有代码,实现copyWith
}
  • 如果只是简单继承关系,无统一操作需求,暂时无需引入抽象父类,避免过度设计。

内容的提问来源于stack exchange,提问作者KueCubit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:57:40