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

Dart/Flutter中如何定义与现有类行为完全一致仅类名不同的类?

解决方案

你遇到的继承报错是因为子类没有显式声明构造函数:Dart会为没有自定义构造函数的类默认生成一个无参构造函数,而父类UrlCallFailedException的构造函数需要接收两个可选参数,默认生成的无参构造函数无法匹配,因此抛出参数数量错误。

你只需要为两个子类声明透传参数的构造函数,直接继承父类的所有逻辑即可,不需要重复编写toString等实现代码:

// 兼容所有Dart版本的写法
class FailedToLoadCriticalDataException extends UrlCallFailedException {
  FailedToLoadCriticalDataException([String dataTypeName, String urlEndpoint])
      : super(dataTypeName, urlEndpoint);
}

class FailedToLoadNonCriticalDataException extends UrlCallFailedException {
  FailedToLoadNonCriticalDataException([String dataTypeName, String urlEndpoint])
      : super(dataTypeName, urlEndpoint);
}

如果你使用Dart 2.17及以上版本,可以用超类初始化参数的语法简化写法:

// Dart 2.17+ 简化写法
class FailedToLoadCriticalDataException extends UrlCallFailedException {
  FailedToLoadCriticalDataException([super._dataTypeName, super._urlEndpoint]);
}

class FailedToLoadNonCriticalDataException extends UrlCallFailedException {
  FailedToLoadNonCriticalDataException([super._dataTypeName, super._urlEndpoint]);
}

使用示例

改造后你可以正常传入参数抛出异常,父类的toString方法会自动识别当前子类的类名,完全符合你的需求:

// 抛出异常
throw FailedToLoadNonCriticalDataException("Foo", "https://example.com/api");
// 输出内容示例:(FailedToLoadNonCriticalDataException) Failed to fetch Foo (https://example.com/api)

// 类型判断不受影响
try {
  // 业务逻辑
} on FailedToLoadCriticalDataException {
  // 处理致命异常,退出应用
} on FailedToLoadNonCriticalDataException {
  // 处理非致命异常,容错继续运行
}

注意事项

如果子类和UrlCallFailedException不在同一个Dart库(不同.dart文件且无part/part of关联),父类的下划线开头私有属性无法在子类中直接访问,此时你只需要把父类的_dataTypeName、_urlEndpoint属性去掉下划线改为公开,或者调整父类构造参数为公开即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:36:03