如何在 Flutter 中使用 json_serialized 反序列化 Firestore 文档及其 id?

Dom*_*ski 6 dart flutter google-cloud-firestore

我的 Firestore 数据库中有一个简单的消息文档,其中包含一些字段。

在此输入图像描述

我用json_serializable反序列化它来反对。我的课程如下所示:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';

part 'message_firestore.g.dart';

@JsonSerializable(nullable: true, explicitToJson: true)
class MessageFirestore extends Equatable {
  MessageFirestore(
      this.id, this.content, this.conversationId, this.senderId, this.dateSent);

  factory MessageFirestore.fromJson(Map<String, dynamic> json) =>
      _$MessageFirestoreFromJson(json);

  Map<String, dynamic> toJson() => _$MessageFirestoreToJson(this);

  @JsonKey(name: 'Id')
  final String id;
  @JsonKey(name: 'Content')
  final String content;
  @JsonKey(name: 'ConversationId')
  final String conversationId;
  @JsonKey(name: 'SenderId')
  final String senderId;
  @JsonKey(name: 'DateSent', fromJson: _fromJson, toJson: _toJson)
  final DateTime dateSent;

  static DateTime _fromJson(Timestamp val) =>
      DateTime.fromMillisecondsSinceEpoch(val.millisecondsSinceEpoch);
  static Timestamp _toJson(DateTime time) =>
      Timestamp.fromMillisecondsSinceEpoch(time.millisecondsSinceEpoch);
}
Run Code Online (Sandbox Code Playgroud)

Id文档中 没有调用任何字段,因此当前其 id 尚未被反序列化。但是,key从 Firestore 检索到的映射的 id 是它的 id,因此可以通过手动反序列化映射来读取该值。 我希望在反序列化期间能够访问文档的 id (_b03002...)。

有什么方法可以配置json_serializable读取这个id并将其存储在id属性中吗?

Yao*_*hen 14

您可以修改fromJson构造函数,以便在第一个参数上提供 id。

factory MessageFirestore.fromJson(String id, Map<String, dynamic> json) {
  return _$MessageFirestoreFromJson(json)..id = id;
}
Run Code Online (Sandbox Code Playgroud)

然后,从你的呼叫者那里,它会是这样的

Message(snapshot.documentID, snapshot.data)
Run Code Online (Sandbox Code Playgroud)