首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dart类需要对象==的实现。

Dart类需要对象==的实现。
EN

Stack Overflow用户
提问于 2022-08-21 12:48:32
回答 1查看 32关注 0票数 0

当我突然编码时,我的所有文件都变成红色,需要一个实现并删除构造函数const关键字。因此,我感到困惑的是,它是否是对dart类的更新,以要求该实现或其他什么。

下面是一个示例类:

代码语言:javascript
复制
    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;
      }
      // Without this operator there is a compile error.
      @override
      operator ==(Object other) {
        // TODO: implement ==
        throw UnimplementedError();
      }
    }
EN

回答 1

Stack Overflow用户

发布于 2022-08-21 13:06:32

您可以使用Equatable包实现相等。要使用const承包商,所有字段都必须是最终的。

代码语言:javascript
复制
class Message extends Equatable {
  final String userId;
  final String messageText;
  final DateTime sentAt;
  final DocumentReference? reference;

  const 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
  List<Object?> get props => [userId, messageText, sentAt, reference];

  Message copyWith({
    String? userId,
    String? messageText,
    DateTime? sentAt,
    DocumentReference? reference,
  }) {
    return Message(
      userId: userId ?? this.userId,
      messageText: messageText ?? this.messageText,
      sentAt: sentAt ?? this.sentAt,
      reference: reference ?? this.reference,
    );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73434553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档