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

Flutter中Dart自定义类对象用==与identical比较不相等问题

核心原因
  • Dart自定义类默认没有重写==运算符时,==的判断逻辑和identical完全一致:仅校验两个引用是否指向内存中的同一个实例,不会对比对象内部的属性值。
  • 你两次调用Person构造函数创建的是两个独立的堆内存对象,内存地址不同,所以两种判断方式默认都会返回不相等。其中identical是Dart自带的严格相等判断,永远只校验是否为同一内存对象,不会受自定义==逻辑的影响。
解决方法

要实现按属性值判断对象相等,需要手动重写自定义类的==运算符和对应的hashCode,两种实现方式如下:

方式1:原生手动重写

class Person {
  final String nombre;
  final String apellido;

  Person(this.nombre, this.apellido);

  // 重写==逻辑,按属性判断相等
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Person &&
          runtimeType == other.runtimeType &&
          nombre == other.nombre &&
          apellido == other.apellido;

  // 必须同步重写hashCode,保证属性相等的对象hashCode也相等,否则在Map、Set等容器中会出现逻辑异常
  @override
  int get hashCode => Object.hash(nombre, apellido);
}

重写完成后,你原来的p == p2就会返回true,符合属性相等的判断预期。

方式2:使用Equatable库简化实现(无需手动写校验逻辑)

// 先在pubspec.yaml添加equatable依赖
class Person extends Equatable {
  final String nombre;
  final String apellido;

  Person(this.nombre, this.apellido);

  // 把所有需要参与相等判断的属性加入props列表即可
  @override
  List<Object?> get props => [nombre, apellido];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:24:02