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

Dart类突然需实现==运算符、移除const构造,原因何在?

Dart类突然要求实现==运算符并移除const构造函数的原因及解决办法

为什么会要求实现==运算符?

这不是Dart的强制更新要求,大概率是你在代码里对Message类实例做了需要值相等性判断的操作:

  • 比如把实例放进Set集合、作为Map的key;
  • 或者调用了某些依赖包的API,要求对象必须支持正确的相等性比较。

Dart默认的==是引用相等(只有两个变量指向同一个内存地址时才返回true),但很多场景需要的是值相等(所有属性值都相同就判定相等)。这种情况下,分析器会提示你重写==运算符,同时必须配套重写hashCode——只写==不写hashCode会导致Set、Map这类依赖哈希值的集合出现逻辑bug。

为什么要求移除构造函数的const关键字?

你的示例代码里构造函数并没有加const,可能是之前的代码版本里加过?或者是依赖包更新触发了这个提示:

  • const构造函数要求类的所有成员必须是final类型(因为const实例是完全不可变的);
  • 你的reference成员没有final修饰,所以如果之前给构造函数加了const,就会违反这个规则,必须移除const,或者把reference改成final。

针对你的Message类的修复代码

正确实现==和hashCode

class Message {
  final String userId;
  final String messageText;
  final DateTime sentAt;
  DocumentReference? reference;

  Message({
    required this.userId,
    required this.messageText,
    required this.sentAt,
    this.reference,
  });

  Map<String, dynamic> toJson() => {
        'userId': userId,
        'messageText': messageText,
        'sentAt': sentAt.toString(),
      };

  factory Message.fromJson(Map<String, dynamic> json) {
    return Message(
      userId: json['userId'] ?? "",
      messageText: json['messageText'] ?? "",
      sentAt: DateTime.parse(json['sentAt'] as String),
    );
  }
  factory Message.fromSnapshot(DocumentSnapshot snapshot) {
    final message = Message.fromJson(snapshot.data() as Map<String, dynamic>);
    return message;
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Message &&
          runtimeType == other.runtimeType &&
          userId == other.userId &&
          messageText == other.messageText &&
          sentAt == other.sentAt &&
          reference == other.reference;

  @override
  int get hashCode => Object.hash(userId, messageText, sentAt, reference);
}

关于const构造函数的处理

如果确实需要const构造函数,把reference改成final即可:

final DocumentReference? reference;

const Message({
  required this.userId,
  required this.messageText,
  required this.sentAt,
  this.reference,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:45:46