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

Dart重写Object.==方法实现不匹配报错的原因与解决方法

Dart报错:'Object.==' 无效实现重写的原因及解决办法

报错原因

你在自定义类中重写==运算符时,方法签名不符合Dart标准。Dart中Object类的==运算符签名是bool operator ==(Object other),但你的实现签名不匹配(比如写成无参数、返回值不是bool、参数类型错误的版本,比如dynamic operator ==())。虽然Dart的动态类型特性让代码能临时运行,但静态分析器会判定这是无效的重写,所以类名处会显示错误标识。

解决办法

  • 修正==运算符的签名,严格遵循Object类的定义,示例代码如下:
    class YourCustomClass {
      final String id;
      final int value;
    
      YourCustomClass(this.id, this.value);
    
      @override
      bool operator ==(Object other) {
        // 先判断是否是同一个对象
        if (identical(this, other)) return true;
        // 再判断类型和属性是否相等
        return other is YourCustomClass && 
               other.id == id && 
               other.value == value;
      }
    }
    
  • 必须同步重写hashCode:Dart规范要求,若两个对象通过==判定为相等,它们的hashCode必须相同,否则会导致HashSet、HashMap等集合类行为异常,示例:
    @override
    int get hashCode => Object.hash(id, value);
    
  • 如果是误写了方法(比如把运算符写成普通方法),直接删除错误代码,按上述规范重写即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:33:12