当前位置: 首页 > 知识库问答 >
问题:

如何在firebase中添加DocumentReference类型的对象(颤振/飞镖)?

严宏旷
2023-03-14

我想在firebase中的post文档中引用类别文档。这是我的数据类,我还使用冻结和json_序列化程序:


    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

所以尝试使用JsonConzer,但我不知道如何将json对象转换为Document参考...


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

共有2个答案

娄学文
2023-03-14

我能够从网上找到的研究中总结出我的解决方案,到目前为止,我得出了这个结论。

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();
  }
荣晨朗
2023-03-14

我一直在调查,发现analyzer软件包的某些版本存在问题。我把它留在这里,以防它对社区中的某些人有用(如果您使用“0.39.15”或“0.39.16”版本,这可能是原因)。如果是这种情况,现在可以在pubspec中设置覆盖。亚马尔:

dependency_overrides:
  analyzer: '0.39.14'

此外,您应该清除所有缓存后:

flutter clean
flutter pub cache repair
flutter pub run build_runner clean
 类似资料:
  • 以下是firebase文档数据 我想向购买的id添加一个新的映射值。这是当前代码 但是使用此代码替换了map值,如何向现有map添加另一个map值 这样地

  • 在flutter示例页面中,有一个名为“将数据发送到新屏幕”的项目。我对第65行的构造函数有一个重新保护的问题。

  • 目前我正在尝试颤振网页,我需要在颤振主频道工作。但是,后来我需要继续我的其他项目。在他们身上,我正在研究颤振稳定通道。 但是,每当我使用命令“flutter channel stable”或“fluter channel master”切换我的flutter通道时,它每次都会重新下载sdk和其他工具。 目前,我已经下载了稳定的颤振sdk和稳定的dart sdk。 我已将它们移动到“FlutterS

  • 我试图改变从API返回的日期字符串的格式。下面的日期格式输入字符串在java中工作正常,但在Dart中则不行。

  • 下面的代码片段: 我尝试使用“automatickeepaliveClientMixin和@override bool get wantKeepAlive=>true”-即保持它活动,以便下次调用它时,它不会再次调用initState(),但是它没有工作。