我能够通过在网上发现的研究中提出解决方案,到目前为止,我提出了这一点。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';
class DocumentReferenceJsonConverter
implements JsonConverter<DocumentReference?, Object?> {
const DocumentReferenceJsonConverter();
@override
DocumentReference? fromJson(Object? json) {
return tryCast<DocumentReference>(json);
}
@override
Object? toJson(DocumentReference? documentReference) => documentReference;
}
T? tryCast<T>(value) {
return value == null ? null : value as T;
}
...
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_profile.freezed.dart';
part 'user_profile.g.dart';
@freezed
class UserProfile with _$UserProfile {
const UserProfile._();
@TimestampConverter()
@DocumentReferenceJsonConverter()
@JsonSerializable(
explicitToJson: true,
fieldRename: FieldRename.snake,
includeIfNull: false,
)
factory UserProfile({
@JsonKey(ignore: true) DocumentReference? reference,
String? avatarUrl,
required String email,
required String firstName,
required String lastName,
Gender? gender,
DateTime? birthday,
String? additionalInfo,
Contact? contact,
DocumentReference? familyReference,
DateTime? createdAt,
}) = _UserProfile;
factory UserProfile.empty() => UserProfile(email: '', firstName: '', lastName: '');
factory UserProfile.fromJson(Map<String, dynamic> json) => _$UserProfileFromJson(json);
factory UserProfile.fromDocument(DocumentSnapshot documentSnapshot) {
final data = documentSnapshot.data();
return data != null
? UserProfile.fromJson(data as Map<String, dynamic>)
.copyWith(reference: documentSnapshot.reference)
: UserProfile.empty();
}