firebase Flutter Cloud Firestore ODM,如何将DocumentReference转换< Model>为DocumentReference&lt;Map&lt;String,dynamic&gt;&gt;

uinbv5nw  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(117)

如果我在Firebase中有两个集合:

Invoices:
    invoice1 {
        Vendor: (reference) /Vendors/vendor1
    }

Vendors:
    vendor1 {
        Name: "John Doe"
}

如果我用Cloud Firestore ODM生成器将它们建模为:

@Collection<Invoice>('Invoices')
@firestoreSerializable
class Invoice {
  Invoice({
      required this.id,
      required this.vendor,
  });

    @Id()
    String id;
    @JsonKey(name: 'Vendor')
    DocumentReference<Map<String, dynamic>> vendor;
}

final invoicesRef = InvoiceCollectionReference();

@Collection<Vendor>('Vendors')
@firestoreSerializable
class Vendor {
    Vendor({
      required this.id,
      required this.name,
  });

    @Id()
    String id;
    @JsonKey(name: 'Name')
    String name;
}

final vendorsRef = VendorCollectionReference();

当我从vendorsRef中选择一个供应商时,我会获得一个VendorDocumentReference。为了创建一个新的发票,我需要将它转换为DocumentReference<Map<String,dynamic>>。如何实现这种转换?
VendorDocumentReference或DocumentReference似乎没有执行此转换的方法。

nmpmafwu

nmpmafwu1#

算了,我用转换器解决了:

class VendorConverter extends JsonConverter<DocumentReference<Vendor>,
    DocumentReference<Map<String, dynamic>>> {
  @override
  DocumentReference<Vendor> fromJson(
      DocumentReference<Map<String, dynamic>> json) {
        return vendorsRef.doc(json.id).reference;
  }

  @override
  DocumentReference<Map<String, dynamic>> toJson(
      DocumentReference<Vendor> object) {
    final path = vendorsRef.doc(object.id).path;
    return FirebaseFirestore.instance.doc(path);
  }

  const VendorConverter();
}

相关问题