我的 FirebaseFirestore 如下图所示
我的反序列化代码如下:
class StripeProductPlan extends Equatable {
final DocumentReference selfRef;
final Map<String, String> metaData;
final String name;
final String? role;
final String? taxCode;
const StripeProductPlan({
required this.selfRef,
required this.metaData,
required this.name,
this.role,
this.taxCode,
});
factory StripeProductPlan.fromSnapshot(
DocumentSnapshot<Map<String, dynamic>> snapshot) {
final data = snapshot.data()!;
return StripeProductPlan(
metaData: data['metaData'] as Map<String, String>,
selfRef: snapshot.reference,
name: data['name'] as String,
role: data['role'] as String? ?? '',
taxCode: data['taxCode'] as String? ?? '',
);
}
除了元数据反序列化之外,其他一切都有效。我该如何解决这个问题?
要将 Firestore 文档中的元数据反序列化为 Dart 类,您可以定义与 Firestore 文档结构匹配的 Dart 模型类。根据您提供的图像,以下是如何定义 Dart 类并实现反序列化的示例:
class Metadata {
final bool isTestingPlan;
final int maxParticipants;
final String orderIdx;
final String productId;
Metadata({
required this.isTestingPlan,
required this.maxParticipants,
required this.orderIdx,
required this.productId,
});
// Factory constructor to create an instance of Metadata from a Firestore document
factory Metadata.fromFirestore(Map<String, dynamic> data) {
return Metadata(
isTestingPlan: data['isTestingPlan'] == 'true',
maxParticipants: int.parse(data['maxParticipants']),
orderIdx: data['orderIdx'],
productId: data['productId'],
);
}
// Method to convert the Metadata instance back to a Map
Map<String, dynamic> toFirestore() {
return {
'isTestingPlan': isTestingPlan.toString(),
'maxParticipants': maxParticipants.toString(),
'orderIdx': orderIdx,
'productId': productId,
};
}
}
现在,更新
StripeProductPlan
类以使用元数据类:
factory StripeProductPlan.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot) {
final data = snapshot.data()!;
return StripeProductPlan(
//you can change like this--------
metaData: Metadata.fromMap(data['metadata'] as Map<String, dynamic>),
selfRef: snapshot.reference,
name: data['name'] as String,
role: data['role'] as String? ?? '',
taxCode: data['taxCode'] as String? ?? '',
);
}
我在你的截图中看到:
您的地图字段称为
medatadata
,而在您的班级中称为 metaData
,这是不正确的。字段名称必须匹配。看看区别吧,数据库中的字段以小写字母开头d
,而类中的字段以大写字母开头D.
要以最简单的方式解决此问题,请更改类中的字段名称以匹配数据库中的字段名称:
class StripeProductPlan extends Equatable {
final DocumentReference selfRef;
final Map<String, String> metadata; //👈
final String name;
final String? role;
final String? taxCode;
//...
}