如何在Firebase(Flutter/Dart)中使用DocumentReference类型添加对象?


我想在Firebase中的帖子文档中引用类别文档。 这是我的数据类,我还使用冻结和json_serializer:




    part 'post_dto.freezed.dart';
    part 'post_dto.g.dart';
    part 'category_dto.freezed.dart';
    part 'category_dto.g.dart';
    
    @freezed
    abstract class PostDTO with _$PostDTO {
      const PostDTO._();
    
      const factory PostDTO({
        @JsonKey(ignore: true) String? id,
        required String title,
        required String description,
        @DocumentReferenceConveter() DocumentReference? categoryReference,
      }) = _PostDTO;
    
      factory PostDTO.fromJson(Map json) =>
          _$PostDTOFromJson(json);
    
      factory PostDTO.fromFireStore(DocumentSnapshot document) {
        Map data = document.data() as Map;
        return PostDTO.fromJson(data).copyWith(id: document.id);
      }
    }
    
    @freezed
    abstract class CategoryDTO with _$CategoryDTO {
      const CategoryDTO._();
    
      const factory CategoryDTO({
        required String icon,
        required String name,
      }) = _CategoryDTO;
    
     factory CategoryDTO.fromFireStore(DocumentSnapshot document) {
        Map data = document.data() as Map;
        return CategoryDTO.fromJson(data);
      }
    
      factory CategoryDTO.fromJson(Map json) =>
          _$CategoryDTOFromJson(json);
    }

  

当我运行build_runner时,我会收到此错误:




    [SEVERE] json_serializable:json_serializable on lib/infrastructure/post/post_dto.dart:
    
    Could not generate `fromJson` code for `categoryReference`.
    To support the type `DocumentReference` you can:
    * Use `JsonConverter`
      https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
    * Use `JsonKey` fields `fromJson` and `toJson`
      https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
      https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
    package:UPLFY/infrastructure/post/post_dto.freezed.dart:373:41
        ╷
    373 │   final DocumentReference? categoryReference;
        │                                         ^^^^^^^^^^^^^^^^^
        ╵
    [INFO] Running build completed, took 2.5s
    
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 44ms
    
    [SEVERE] Failed after 2.5s

  

因此尝试使用JSONConverter,但我不确定如何将JSON对象转换为文档referference ...




    class DocumentReferenceConveter
        implements JsonConverter, Object> {
      const DocumentReferenceConveter();
    
      @override
      DocumentReference fromJson(Object json) {
        return //TODO: Convert json to DocumentReference
      }
    
      @override
      Object toJson(DocumentReference documentReference) =>
          documentReference;
    }

  

我能够通过在网上发现的研究中提出解决方案,到目前为止,我提出了这一点。


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();
  }

如何在Firebase(Flutter/Dart)中使用DocumentReference类型添加对象?的相关文章

随机推荐